org.el (org-cycle): Fix misplaced autoload cookie
[org-mode/org-tableheadings.git] / lisp / org.el
blob1d103ff1e698d73d96b3a5ff6428637ab4980b06
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-timestamps-up "org-clock" ())
117 (declare-function org-clock-timestamps-down "org-clock" ())
118 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
120 ;; load languages based on value of `org-babel-load-languages'
121 (defvar org-babel-load-languages)
122 ;;;###autoload
123 (defun org-babel-do-load-languages (sym value)
124 "Load the languages defined in `org-babel-load-languages'."
125 (set-default sym value)
126 (mapc (lambda (pair)
127 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
128 (if active
129 (progn
130 (require (intern (concat "ob-" lang))))
131 (progn
132 (funcall 'fmakunbound
133 (intern (concat "org-babel-execute:" lang)))
134 (funcall 'fmakunbound
135 (intern (concat "org-babel-expand-body:" lang)))))))
136 org-babel-load-languages))
138 (defcustom org-babel-load-languages '((emacs-lisp . t))
139 "Languages which can be evaluated in Org-mode buffers.
140 This list can be used to load support for any of the languages
141 below, note that each language will depend on a different set of
142 system executables and/or Emacs modes. When a language is
143 \"loaded\", then code blocks in that language can be evaluated
144 with `org-babel-execute-src-block' bound by default to C-c
145 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
146 be set to remove code block evaluation from the C-c C-c
147 keybinding. By default only Emacs Lisp (which has no
148 requirements) is loaded."
149 :group 'org-babel
150 :set 'org-babel-do-load-languages
151 :version "24.1"
152 :type '(alist :tag "Babel Languages"
153 :key-type
154 (choice
155 (const :tag "Awk" awk)
156 (const :tag "C" C)
157 (const :tag "R" R)
158 (const :tag "Asymptote" asymptote)
159 (const :tag "Calc" calc)
160 (const :tag "Clojure" clojure)
161 (const :tag "CSS" css)
162 (const :tag "Ditaa" ditaa)
163 (const :tag "Dot" dot)
164 (const :tag "Emacs Lisp" emacs-lisp)
165 (const :tag "Fortran" fortran)
166 (const :tag "Gnuplot" gnuplot)
167 (const :tag "Haskell" haskell)
168 (const :tag "IO" io)
169 (const :tag "Java" java)
170 (const :tag "Javascript" js)
171 (const :tag "LaTeX" latex)
172 (const :tag "Ledger" ledger)
173 (const :tag "Lilypond" lilypond)
174 (const :tag "Lisp" lisp)
175 (const :tag "Maxima" maxima)
176 (const :tag "Matlab" matlab)
177 (const :tag "Mscgen" mscgen)
178 (const :tag "Ocaml" ocaml)
179 (const :tag "Octave" octave)
180 (const :tag "Org" org)
181 (const :tag "Perl" perl)
182 (const :tag "Pico Lisp" picolisp)
183 (const :tag "PlantUML" plantuml)
184 (const :tag "Python" python)
185 (const :tag "Ruby" ruby)
186 (const :tag "Sass" sass)
187 (const :tag "Scala" scala)
188 (const :tag "Scheme" scheme)
189 (const :tag "Screen" screen)
190 (const :tag "Shell Script" sh)
191 (const :tag "Shen" shen)
192 (const :tag "Sql" sql)
193 (const :tag "Sqlite" sqlite))
194 :value-type (boolean :tag "Activate" :value t)))
196 ;;;; Customization variables
197 (defcustom org-clone-delete-id nil
198 "Remove ID property of clones of a subtree.
199 When non-nil, clones of a subtree don't inherit the ID property.
200 Otherwise they inherit the ID property with a new unique
201 identifier."
202 :type 'boolean
203 :version "24.1"
204 :group 'org-id)
206 ;;; Version
207 (require 'org-compat)
208 (org-check-version)
209 ;;;###autoload
210 (defun org-version (&optional here full message)
211 "Show the org-mode version in the echo area.
212 With prefix argument HERE, insert it at point.
213 When FULL is non-nil, use a verbose version string.
214 When MESSAGE is non-nil, display a message with the version."
215 (interactive "P")
216 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
217 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
218 (org-trash (or
219 (and (fboundp 'org-release) (fboundp 'org-git-version))
220 (load (concat org-dir "org-version.el")
221 'noerror 'nomessage 'nosuffix)))
222 (org-version (org-release))
223 (git-version (org-git-version))
224 (version (format "Org-mode version %s (%s @ %s)"
225 org-version
226 git-version
227 (if org-install-dir
228 (if (string= org-dir org-install-dir)
229 org-install-dir
230 (concat "mixed installation! " org-install-dir " and " org-dir))
231 "org-install.el can not be found!")))
232 (_version (if full version org-version)))
233 (if (org-called-interactively-p 'interactive)
234 (if here
235 (insert version)
236 (message version))
237 (if message (message _version))
238 _version)))
240 (defconst org-version (org-version))
242 ;;; Compatibility constants
244 ;;; The custom variables
246 (defgroup org nil
247 "Outline-based notes management and organizer."
248 :tag "Org"
249 :group 'outlines
250 :group 'calendar)
252 (defcustom org-mode-hook nil
253 "Mode hook for Org-mode, run after the mode was turned on."
254 :group 'org
255 :type 'hook)
257 (defcustom org-load-hook nil
258 "Hook that is run after org.el has been loaded."
259 :group 'org
260 :type 'hook)
262 (defcustom org-log-buffer-setup-hook nil
263 "Hook that is run after an Org log buffer is created."
264 :group 'org
265 :version "24.1"
266 :type 'hook)
268 (defvar org-modules) ; defined below
269 (defvar org-modules-loaded nil
270 "Have the modules been loaded already?")
272 (defun org-load-modules-maybe (&optional force)
273 "Load all extensions listed in `org-modules'."
274 (when (or force (not org-modules-loaded))
275 (mapc (lambda (ext)
276 (condition-case nil (require ext)
277 (error (message "Problems while trying to load feature `%s'" ext))))
278 org-modules)
279 (setq org-modules-loaded t)))
281 (defun org-set-modules (var value)
282 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
283 (set var value)
284 (when (featurep 'org)
285 (org-load-modules-maybe 'force)))
287 (when (org-bound-and-true-p org-modules)
288 (let ((a (member 'org-infojs org-modules)))
289 (and a (setcar a 'org-jsinfo))))
291 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
292 "Modules that should always be loaded together with org.el.
293 If a description starts with <C>, the file is not part of Emacs
294 and loading it will require that you have downloaded and properly installed
295 the org-mode distribution.
297 You can also use this system to load external packages (i.e. neither Org
298 core modules, nor modules from the CONTRIB directory). Just add symbols
299 to the end of the list. If the package is called org-xyz.el, then you need
300 to add the symbol `xyz', and the package must have a call to
302 (provide 'org-xyz)"
303 :group 'org
304 :set 'org-set-modules
305 :type
306 '(set :greedy t
307 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
308 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
309 (const :tag " crypt: Encryption of subtrees" org-crypt)
310 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
311 (const :tag " docview: Links to doc-view buffers" org-docview)
312 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
313 (const :tag " id: Global IDs for identifying entries" org-id)
314 (const :tag " info: Links to Info nodes" org-info)
315 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
316 (const :tag " habit: Track your consistency with habits" org-habit)
317 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
318 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
319 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
320 (const :tag " mew Links to Mew folders/messages" org-mew)
321 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
322 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
323 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
324 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
325 (const :tag " vm: Links to VM folders/messages" org-vm)
326 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
327 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
328 (const :tag " mouse: Additional mouse support" org-mouse)
329 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
331 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
332 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
333 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
334 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
335 (const :tag "C collector: Collect properties into tables" org-collector)
336 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
337 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
338 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
339 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
340 (const :tag "C eval: Include command output as text" org-eval)
341 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
342 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
343 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
344 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
345 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
347 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
349 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
350 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
351 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
352 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
353 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
354 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
355 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
356 (const :tag "C mtags: Support for muse-like tags" org-mtags)
357 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
358 (const :tag "C registry: A registry for Org-mode links" org-registry)
359 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
360 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
361 (const :tag "C secretary: Team management with org-mode" org-secretary)
362 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
363 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
364 (const :tag "C track: Keep up with Org-mode development" org-track)
365 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
366 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
367 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
369 (defcustom org-support-shift-select nil
370 "Non-nil means make shift-cursor commands select text when possible.
372 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
373 start selecting a region, or enlarge regions started in this way.
374 In Org-mode, in special contexts, these same keys are used for
375 other purposes, important enough to compete with shift selection.
376 Org tries to balance these needs by supporting `shift-select-mode'
377 outside these special contexts, under control of this variable.
379 The default of this variable is nil, to avoid confusing behavior. Shifted
380 cursor keys will then execute Org commands in the following contexts:
381 - on a headline, changing TODO state (left/right) and priority (up/down)
382 - on a time stamp, changing the time
383 - in a plain list item, changing the bullet type
384 - in a property definition line, switching between allowed values
385 - in the BEGIN line of a clock table (changing the time block).
386 Outside these contexts, the commands will throw an error.
388 When this variable is t and the cursor is not in a special
389 context, Org-mode will support shift-selection for making and
390 enlarging regions. To make this more effective, the bullet
391 cycling will no longer happen anywhere in an item line, but only
392 if the cursor is exactly on the bullet.
394 If you set this variable to the symbol `always', then the keys
395 will not be special in headlines, property lines, and item lines,
396 to make shift selection work there as well. If this is what you
397 want, you can use the following alternative commands: `C-c C-t'
398 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
399 can be used to switch TODO sets, `C-c -' to cycle item bullet
400 types, and properties can be edited by hand or in column view.
402 However, when the cursor is on a timestamp, shift-cursor commands
403 will still edit the time stamp - this is just too good to give up.
405 XEmacs user should have this variable set to nil, because
406 `shift-select-mode' is in Emacs 23 or later only."
407 :group 'org
408 :type '(choice
409 (const :tag "Never" nil)
410 (const :tag "When outside special context" t)
411 (const :tag "Everywhere except timestamps" always)))
413 (defcustom org-loop-over-headlines-in-active-region nil
414 "Shall some commands act upon headlines in the active region?
416 When set to `t', some commands will be performed in all headlines
417 within the active region.
419 When set to `start-level', some commands will be performed in all
420 headlines within the active region, provided that these headlines
421 are of the same level than the first one.
423 When set to a string, those commands will be performed on the
424 matching headlines within the active region. Such string must be
425 a tags/property/todo match as it is used in the agenda tags view.
427 The list of commands is: `org-schedule', `org-deadline',
428 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
429 `org-archive-to-archive-sibling'. The archiving commands skip
430 already archived entries."
431 :type '(choice (const :tag "Don't loop" nil)
432 (const :tag "All headlines in active region" t)
433 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
434 (string :tag "Tags/Property/Todo matcher"))
435 :version "24.1"
436 :group 'org-todo
437 :group 'org-archive)
439 (defgroup org-startup nil
440 "Options concerning startup of Org-mode."
441 :tag "Org Startup"
442 :group 'org)
444 (defcustom org-startup-folded t
445 "Non-nil means entering Org-mode will switch to OVERVIEW.
446 This can also be configured on a per-file basis by adding one of
447 the following lines anywhere in the buffer:
449 #+STARTUP: fold (or `overview', this is equivalent)
450 #+STARTUP: nofold (or `showall', this is equivalent)
451 #+STARTUP: content
452 #+STARTUP: showeverything"
453 :group 'org-startup
454 :type '(choice
455 (const :tag "nofold: show all" nil)
456 (const :tag "fold: overview" t)
457 (const :tag "content: all headlines" content)
458 (const :tag "show everything, even drawers" showeverything)))
460 (defcustom org-startup-truncated t
461 "Non-nil means entering Org-mode will set `truncate-lines'.
462 This is useful since some lines containing links can be very long and
463 uninteresting. Also tables look terrible when wrapped."
464 :group 'org-startup
465 :type 'boolean)
467 (defcustom org-startup-indented nil
468 "Non-nil means turn on `org-indent-mode' on startup.
469 This can also be configured on a per-file basis by adding one of
470 the following lines anywhere in the buffer:
472 #+STARTUP: indent
473 #+STARTUP: noindent"
474 :group 'org-structure
475 :type '(choice
476 (const :tag "Not" nil)
477 (const :tag "Globally (slow on startup in large files)" t)))
479 (defcustom org-use-sub-superscripts t
480 "Non-nil means interpret \"_\" and \"^\" for export.
481 When this option is turned on, you can use TeX-like syntax for sub- and
482 superscripts. Several characters after \"_\" or \"^\" will be
483 considered as a single item - so grouping with {} is normally not
484 needed. For example, the following things will be parsed as single
485 sub- or superscripts.
487 10^24 or 10^tau several digits will be considered 1 item.
488 10^-12 or 10^-tau a leading sign with digits or a word
489 x^2-y^3 will be read as x^2 - y^3, because items are
490 terminated by almost any nonword/nondigit char.
491 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
493 Still, ambiguity is possible - so when in doubt use {} to enclose the
494 sub/superscript. If you set this variable to the symbol `{}',
495 the braces are *required* in order to trigger interpretations as
496 sub/superscript. This can be helpful in documents that need \"_\"
497 frequently in plain text.
499 Not all export backends support this, but HTML does.
501 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
502 :group 'org-startup
503 :group 'org-export-translation
504 :version "24.1"
505 :type '(choice
506 (const :tag "Always interpret" t)
507 (const :tag "Only with braces" {})
508 (const :tag "Never interpret" nil)))
510 (if (fboundp 'defvaralias)
511 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
514 (defcustom org-startup-with-beamer-mode nil
515 "Non-nil means turn on `org-beamer-mode' on startup.
516 This can also be configured on a per-file basis by adding one of
517 the following lines anywhere in the buffer:
519 #+STARTUP: beamer"
520 :group 'org-startup
521 :version "24.1"
522 :type 'boolean)
524 (defcustom org-startup-align-all-tables nil
525 "Non-nil means align all tables when visiting a file.
526 This is useful when the column width in tables is forced with <N> cookies
527 in table fields. Such tables will look correct only after the first re-align.
528 This can also be configured on a per-file basis by adding one of
529 the following lines anywhere in the buffer:
530 #+STARTUP: align
531 #+STARTUP: noalign"
532 :group 'org-startup
533 :type 'boolean)
535 (defcustom org-startup-with-inline-images nil
536 "Non-nil means show inline images when loading a new Org file.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
539 #+STARTUP: inlineimages
540 #+STARTUP: noinlineimages"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-insert-mode-line-in-empty-file nil
546 "Non-nil means insert the first line setting Org-mode in empty files.
547 When the function `org-mode' is called interactively in an empty file, this
548 normally means that the file name does not automatically trigger Org-mode.
549 To ensure that the file will always be in Org-mode in the future, a
550 line enforcing Org-mode will be inserted into the buffer, if this option
551 has been set."
552 :group 'org-startup
553 :type 'boolean)
555 (defcustom org-replace-disputed-keys nil
556 "Non-nil means use alternative key bindings for some keys.
557 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
558 These keys are also used by other packages like shift-selection-mode'
559 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
560 If you want to use Org-mode together with one of these other modes,
561 or more generally if you would like to move some Org-mode commands to
562 other keys, set this variable and configure the keys with the variable
563 `org-disputed-keys'.
565 This option is only relevant at load-time of Org-mode, and must be set
566 *before* org.el is loaded. Changing it requires a restart of Emacs to
567 become effective."
568 :group 'org-startup
569 :type 'boolean)
571 (defcustom org-use-extra-keys nil
572 "Non-nil means use extra key sequence definitions for certain commands.
573 This happens automatically if you run XEmacs or if `window-system'
574 is nil. This variable lets you do the same manually. You must
575 set it before loading org.
577 Example: on Carbon Emacs 22 running graphically, with an external
578 keyboard on a Powerbook, the default way of setting M-left might
579 not work for either Alt or ESC. Setting this variable will make
580 it work for ESC."
581 :group 'org-startup
582 :type 'boolean)
584 (if (fboundp 'defvaralias)
585 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
587 (defcustom org-disputed-keys
588 '(([(shift up)] . [(meta p)])
589 ([(shift down)] . [(meta n)])
590 ([(shift left)] . [(meta -)])
591 ([(shift right)] . [(meta +)])
592 ([(control shift right)] . [(meta shift +)])
593 ([(control shift left)] . [(meta shift -)]))
594 "Keys for which Org-mode and other modes compete.
595 This is an alist, cars are the default keys, second element specifies
596 the alternative to use when `org-replace-disputed-keys' is t.
598 Keys can be specified in any syntax supported by `define-key'.
599 The value of this option takes effect only at Org-mode's startup,
600 therefore you'll have to restart Emacs to apply it after changing."
601 :group 'org-startup
602 :type 'alist)
604 (defun org-key (key)
605 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
606 Or return the original if not disputed.
607 Also apply the translations defined in `org-xemacs-key-equivalents'."
608 (when org-replace-disputed-keys
609 (let* ((nkey (key-description key))
610 (x (org-find-if (lambda (x)
611 (equal (key-description (car x)) nkey))
612 org-disputed-keys)))
613 (setq key (if x (cdr x) key))))
614 (when (featurep 'xemacs)
615 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
616 key)
618 (defun org-find-if (predicate seq)
619 (catch 'exit
620 (while seq
621 (if (funcall predicate (car seq))
622 (throw 'exit (car seq))
623 (pop seq)))))
625 (defun org-defkey (keymap key def)
626 "Define a key, possibly translated, as returned by `org-key'."
627 (define-key keymap (org-key key) def))
629 (defcustom org-ellipsis nil
630 "The ellipsis to use in the Org-mode outline.
631 When nil, just use the standard three dots. When a string, use that instead,
632 When a face, use the standard 3 dots, but with the specified face.
633 The change affects only Org-mode (which will then use its own display table).
634 Changing this requires executing `M-x org-mode' in a buffer to become
635 effective."
636 :group 'org-startup
637 :type '(choice (const :tag "Default" nil)
638 (face :tag "Face" :value org-warning)
639 (string :tag "String" :value "...#")))
641 (defvar org-display-table nil
642 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
644 (defgroup org-keywords nil
645 "Keywords in Org-mode."
646 :tag "Org Keywords"
647 :group 'org)
649 (defcustom org-deadline-string "DEADLINE:"
650 "String to mark deadline entries.
651 A deadline is this string, followed by a time stamp. Should be a word,
652 terminated by a colon. You can insert a schedule keyword and
653 a timestamp with \\[org-deadline].
654 Changes become only effective after restarting Emacs."
655 :group 'org-keywords
656 :type 'string)
658 (defcustom org-scheduled-string "SCHEDULED:"
659 "String to mark scheduled TODO entries.
660 A schedule is this string, followed by a time stamp. Should be a word,
661 terminated by a colon. You can insert a schedule keyword and
662 a timestamp with \\[org-schedule].
663 Changes become only effective after restarting Emacs."
664 :group 'org-keywords
665 :type 'string)
667 (defcustom org-closed-string "CLOSED:"
668 "String used as the prefix for timestamps logging closing a TODO entry."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-clock-string "CLOCK:"
673 "String used as prefix for timestamps clocking work hours on an item."
674 :group 'org-keywords
675 :type 'string)
677 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
678 org-scheduled-string "\\|"
679 org-deadline-string "\\|"
680 org-closed-string "\\|"
681 org-clock-string "\\)")
682 "Matches a line with planning or clock info.")
684 (defcustom org-comment-string "COMMENT"
685 "Entries starting with this keyword will never be exported.
686 An entry can be toggled between COMMENT and normal with
687 \\[org-toggle-comment].
688 Changes become only effective after restarting Emacs."
689 :group 'org-keywords
690 :type 'string)
692 (defcustom org-quote-string "QUOTE"
693 "Entries starting with this keyword will be exported in fixed-width font.
694 Quoting applies only to the text in the entry following the headline, and does
695 not extend beyond the next headline, even if that is lower level.
696 An entry can be toggled between QUOTE and normal with
697 \\[org-toggle-fixed-width-section]."
698 :group 'org-keywords
699 :type 'string)
701 (defconst org-repeat-re
702 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
703 "Regular expression for specifying repeated events.
704 After a match, group 1 contains the repeat expression.")
706 (defgroup org-structure nil
707 "Options concerning the general structure of Org-mode files."
708 :tag "Org Structure"
709 :group 'org)
711 (defgroup org-reveal-location nil
712 "Options about how to make context of a location visible."
713 :tag "Org Reveal Location"
714 :group 'org-structure)
716 (defconst org-context-choice
717 '(choice
718 (const :tag "Always" t)
719 (const :tag "Never" nil)
720 (repeat :greedy t :tag "Individual contexts"
721 (cons
722 (choice :tag "Context"
723 (const agenda)
724 (const org-goto)
725 (const occur-tree)
726 (const tags-tree)
727 (const link-search)
728 (const mark-goto)
729 (const bookmark-jump)
730 (const isearch)
731 (const default))
732 (boolean))))
733 "Contexts for the reveal options.")
735 (defcustom org-show-hierarchy-above '((default . t))
736 "Non-nil means show full hierarchy when revealing a location.
737 Org-mode often shows locations in an org-mode file which might have
738 been invisible before. When this is set, the hierarchy of headings
739 above the exposed location is shown.
740 Turning this off for example for sparse trees makes them very compact.
741 Instead of t, this can also be an alist specifying this option for different
742 contexts. Valid contexts are
743 agenda when exposing an entry from the agenda
744 org-goto when using the command `org-goto' on key C-c C-j
745 occur-tree when using the command `org-occur' on key C-c /
746 tags-tree when constructing a sparse tree based on tags matches
747 link-search when exposing search matches associated with a link
748 mark-goto when exposing the jump goal of a mark
749 bookmark-jump when exposing a bookmark location
750 isearch when exiting from an incremental search
751 default default for all contexts not set explicitly"
752 :group 'org-reveal-location
753 :type org-context-choice)
755 (defcustom org-show-following-heading '((default . nil))
756 "Non-nil means show following heading when revealing a location.
757 Org-mode often shows locations in an org-mode file which might have
758 been invisible before. When this is set, the heading following the
759 match is shown.
760 Turning this off for example for sparse trees makes them very compact,
761 but makes it harder to edit the location of the match. In such a case,
762 use the command \\[org-reveal] to show more context.
763 Instead of t, this can also be an alist specifying this option for different
764 contexts. See `org-show-hierarchy-above' for valid contexts."
765 :group 'org-reveal-location
766 :type org-context-choice)
768 (defcustom org-show-siblings '((default . nil) (isearch t))
769 "Non-nil means show all sibling heading when revealing a location.
770 Org-mode often shows locations in an org-mode file which might have
771 been invisible before. When this is set, the sibling of the current entry
772 heading are all made visible. If `org-show-hierarchy-above' is t,
773 the same happens on each level of the hierarchy above the current entry.
775 By default this is on for the isearch context, off for all other contexts.
776 Turning this off for example for sparse trees makes them very compact,
777 but makes it harder to edit the location of the match. In such a case,
778 use the command \\[org-reveal] to show more context.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. See `org-show-hierarchy-above' for valid contexts."
781 :group 'org-reveal-location
782 :type org-context-choice)
784 (defcustom org-show-entry-below '((default . nil))
785 "Non-nil means show the entry below a headline when revealing a location.
786 Org-mode often shows locations in an org-mode file which might have
787 been invisible before. When this is set, the text below the headline that is
788 exposed is also shown.
790 By default this is off for all contexts.
791 Instead of t, this can also be an alist specifying this option for different
792 contexts. See `org-show-hierarchy-above' for valid contexts."
793 :group 'org-reveal-location
794 :type org-context-choice)
796 (defcustom org-indirect-buffer-display 'other-window
797 "How should indirect tree buffers be displayed?
798 This applies to indirect buffers created with the commands
799 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
800 Valid values are:
801 current-window Display in the current window
802 other-window Just display in another window.
803 dedicated-frame Create one new frame, and re-use it each time.
804 new-frame Make a new frame each time. Note that in this case
805 previously-made indirect buffers are kept, and you need to
806 kill these buffers yourself."
807 :group 'org-structure
808 :group 'org-agenda-windows
809 :type '(choice
810 (const :tag "In current window" current-window)
811 (const :tag "In current frame, other window" other-window)
812 (const :tag "Each time a new frame" new-frame)
813 (const :tag "One dedicated frame" dedicated-frame)))
815 (defcustom org-use-speed-commands nil
816 "Non-nil means activate single letter commands at beginning of a headline.
817 This may also be a function to test for appropriate locations where speed
818 commands should be active."
819 :group 'org-structure
820 :type '(choice
821 (const :tag "Never" nil)
822 (const :tag "At beginning of headline stars" t)
823 (function)))
825 (defcustom org-speed-commands-user nil
826 "Alist of additional speed commands.
827 This list will be checked before `org-speed-commands-default'
828 when the variable `org-use-speed-commands' is non-nil
829 and when the cursor is at the beginning of a headline.
830 The car if each entry is a string with a single letter, which must
831 be assigned to `self-insert-command' in the global map.
832 The cdr is either a command to be called interactively, a function
833 to be called, or a form to be evaluated.
834 An entry that is just a list with a single string will be interpreted
835 as a descriptive headline that will be added when listing the speed
836 commands in the Help buffer using the `?' speed command."
837 :group 'org-structure
838 :type '(repeat :value ("k" . ignore)
839 (choice :value ("k" . ignore)
840 (list :tag "Descriptive Headline" (string :tag "Headline"))
841 (cons :tag "Letter and Command"
842 (string :tag "Command letter")
843 (choice
844 (function)
845 (sexp))))))
847 (defgroup org-cycle nil
848 "Options concerning visibility cycling in Org-mode."
849 :tag "Org Cycle"
850 :group 'org-structure)
852 (defcustom org-cycle-skip-children-state-if-no-children t
853 "Non-nil means skip CHILDREN state in entries that don't have any."
854 :group 'org-cycle
855 :type 'boolean)
857 (defcustom org-cycle-max-level nil
858 "Maximum level which should still be subject to visibility cycling.
859 Levels higher than this will, for cycling, be treated as text, not a headline.
860 When `org-odd-levels-only' is set, a value of N in this variable actually
861 means 2N-1 stars as the limiting headline.
862 When nil, cycle all levels.
863 Note that the limiting level of cycling is also influenced by
864 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
865 `org-inlinetask-min-level' is, cycling will be limited to levels one less
866 than its value."
867 :group 'org-cycle
868 :type '(choice
869 (const :tag "No limit" nil)
870 (integer :tag "Maximum level")))
872 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
873 "Names of drawers. Drawers are not opened by cycling on the headline above.
874 Drawers only open with a TAB on the drawer line itself. A drawer looks like
875 this:
876 :DRAWERNAME:
877 .....
878 :END:
879 The drawer \"PROPERTIES\" is special for capturing properties through
880 the property API.
882 Drawers can be defined on the per-file basis with a line like:
884 #+DRAWERS: HIDDEN STATE PROPERTIES"
885 :group 'org-structure
886 :group 'org-cycle
887 :type '(repeat (string :tag "Drawer Name")))
889 (defcustom org-hide-block-startup nil
890 "Non-nil means entering Org-mode will fold all blocks.
891 This can also be set in on a per-file basis with
893 #+STARTUP: hideblocks
894 #+STARTUP: showblocks"
895 :group 'org-startup
896 :group 'org-cycle
897 :type 'boolean)
899 (defcustom org-cycle-global-at-bob nil
900 "Cycle globally if cursor is at beginning of buffer and not at a headline.
901 This makes it possible to do global cycling without having to use S-TAB or
902 \\[universal-argument] TAB. For this special case to work, the first line
903 of the buffer must not be a headline -- it may be empty or some other text.
904 When used in this way, `org-cycle-hook' is disabled temporarily to make
905 sure the cursor stays at the beginning of the buffer. When this option is
906 nil, don't do anything special at the beginning of the buffer."
907 :group 'org-cycle
908 :type 'boolean)
910 (defcustom org-cycle-level-after-item/entry-creation t
911 "Non-nil means cycle entry level or item indentation in new empty entries.
913 When the cursor is at the end of an empty headline, i.e with only stars
914 and maybe a TODO keyword, TAB will then switch the entry to become a child,
915 and then all possible ancestor states, before returning to the original state.
916 This makes data entry extremely fast: M-RET to create a new headline,
917 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
919 When the cursor is at the end of an empty plain list item, one TAB will
920 make it a subitem, two or more tabs will back up to make this an item
921 higher up in the item hierarchy."
922 :group 'org-cycle
923 :type 'boolean)
925 (defcustom org-cycle-emulate-tab t
926 "Where should `org-cycle' emulate TAB.
927 nil Never
928 white Only in completely white lines
929 whitestart Only at the beginning of lines, before the first non-white char
930 t Everywhere except in headlines
931 exc-hl-bol Everywhere except at the start of a headline
932 If TAB is used in a place where it does not emulate TAB, the current subtree
933 visibility is cycled."
934 :group 'org-cycle
935 :type '(choice (const :tag "Never" nil)
936 (const :tag "Only in completely white lines" white)
937 (const :tag "Before first char in a line" whitestart)
938 (const :tag "Everywhere except in headlines" t)
939 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
942 (defcustom org-cycle-separator-lines 2
943 "Number of empty lines needed to keep an empty line between collapsed trees.
944 If you leave an empty line between the end of a subtree and the following
945 headline, this empty line is hidden when the subtree is folded.
946 Org-mode will leave (exactly) one empty line visible if the number of
947 empty lines is equal or larger to the number given in this variable.
948 So the default 2 means at least 2 empty lines after the end of a subtree
949 are needed to produce free space between a collapsed subtree and the
950 following headline.
952 If the number is negative, and the number of empty lines is at least -N,
953 all empty lines are shown.
955 Special case: when 0, never leave empty lines in collapsed view."
956 :group 'org-cycle
957 :type 'integer)
958 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
960 (defcustom org-pre-cycle-hook nil
961 "Hook that is run before visibility cycling is happening.
962 The function(s) in this hook must accept a single argument which indicates
963 the new state that will be set right after running this hook. The
964 argument is a symbol. Before a global state change, it can have the values
965 `overview', `content', or `all'. Before a local state change, it can have
966 the values `folded', `children', or `subtree'."
967 :group 'org-cycle
968 :type 'hook)
970 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
971 org-cycle-hide-drawers
972 org-cycle-show-empty-lines
973 org-optimize-window-after-visibility-change)
974 "Hook that is run after `org-cycle' has changed the buffer visibility.
975 The function(s) in this hook must accept a single argument which indicates
976 the new state that was set by the most recent `org-cycle' command. The
977 argument is a symbol. After a global state change, it can have the values
978 `overview', `contents', or `all'. After a local state change, it can have
979 the values `folded', `children', or `subtree'."
980 :group 'org-cycle
981 :type 'hook)
983 (defgroup org-edit-structure nil
984 "Options concerning structure editing in Org-mode."
985 :tag "Org Edit Structure"
986 :group 'org-structure)
988 (defcustom org-odd-levels-only nil
989 "Non-nil means skip even levels and only use odd levels for the outline.
990 This has the effect that two stars are being added/taken away in
991 promotion/demotion commands. It also influences how levels are
992 handled by the exporters.
993 Changing it requires restart of `font-lock-mode' to become effective
994 for fontification also in regions already fontified.
995 You may also set this on a per-file basis by adding one of the following
996 lines to the buffer:
998 #+STARTUP: odd
999 #+STARTUP: oddeven"
1000 :group 'org-edit-structure
1001 :group 'org-appearance
1002 :type 'boolean)
1004 (defcustom org-adapt-indentation t
1005 "Non-nil means adapt indentation to outline node level.
1007 When this variable is set, Org assumes that you write outlines by
1008 indenting text in each node to align with the headline (after the stars).
1009 The following issues are influenced by this variable:
1011 - When this is set and the *entire* text in an entry is indented, the
1012 indentation is increased by one space in a demotion command, and
1013 decreased by one in a promotion command. If any line in the entry
1014 body starts with text at column 0, indentation is not changed at all.
1016 - Property drawers and planning information is inserted indented when
1017 this variable s set. When nil, they will not be indented.
1019 - TAB indents a line relative to context. The lines below a headline
1020 will be indented when this variable is set.
1022 Note that this is all about true indentation, by adding and removing
1023 space characters. See also `org-indent.el' which does level-dependent
1024 indentation in a virtual way, i.e. at display time in Emacs."
1025 :group 'org-edit-structure
1026 :type 'boolean)
1028 (defcustom org-special-ctrl-a/e nil
1029 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1031 When t, `C-a' will bring back the cursor to the beginning of the
1032 headline text, i.e. after the stars and after a possible TODO
1033 keyword. In an item, this will be the position after bullet and
1034 check-box, if any. When the cursor is already at that position,
1035 another `C-a' will bring it to the beginning of the line.
1037 `C-e' will jump to the end of the headline, ignoring the presence
1038 of tags in the headline. A second `C-e' will then jump to the
1039 true end of the line, after any tags. This also means that, when
1040 this variable is non-nil, `C-e' also will never jump beyond the
1041 end of the heading of a folded section, i.e. not after the
1042 ellipses.
1044 When set to the symbol `reversed', the first `C-a' or `C-e' works
1045 normally, going to the true line boundary first. Only a directly
1046 following, identical keypress will bring the cursor to the
1047 special positions.
1049 This may also be a cons cell where the behavior for `C-a' and
1050 `C-e' is set separately."
1051 :group 'org-edit-structure
1052 :type '(choice
1053 (const :tag "off" nil)
1054 (const :tag "on: after stars/bullet and before tags first" t)
1055 (const :tag "reversed: true line boundary first" reversed)
1056 (cons :tag "Set C-a and C-e separately"
1057 (choice :tag "Special C-a"
1058 (const :tag "off" nil)
1059 (const :tag "on: after stars/bullet first" t)
1060 (const :tag "reversed: before stars/bullet first" reversed))
1061 (choice :tag "Special C-e"
1062 (const :tag "off" nil)
1063 (const :tag "on: before tags first" t)
1064 (const :tag "reversed: after tags first" reversed)))))
1065 (if (fboundp 'defvaralias)
1066 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1068 (defcustom org-special-ctrl-k nil
1069 "Non-nil means `C-k' will behave specially in headlines.
1070 When nil, `C-k' will call the default `kill-line' command.
1071 When t, the following will happen while the cursor is in the headline:
1073 - When the cursor is at the beginning of a headline, kill the entire
1074 line and possible the folded subtree below the line.
1075 - When in the middle of the headline text, kill the headline up to the tags.
1076 - When after the headline text, kill the tags."
1077 :group 'org-edit-structure
1078 :type 'boolean)
1080 (defcustom org-ctrl-k-protect-subtree nil
1081 "Non-nil means, do not delete a hidden subtree with C-k.
1082 When set to the symbol `error', simply throw an error when C-k is
1083 used to kill (part-of) a headline that has hidden text behind it.
1084 Any other non-nil value will result in a query to the user, if it is
1085 OK to kill that hidden subtree. When nil, kill without remorse."
1086 :group 'org-edit-structure
1087 :version "24.1"
1088 :type '(choice
1089 (const :tag "Do not protect hidden subtrees" nil)
1090 (const :tag "Protect hidden subtrees with a security query" t)
1091 (const :tag "Never kill a hidden subtree with C-k" error)))
1093 (defcustom org-catch-invisible-edits nil
1094 "Check if in invisible region before inserting or deleting a character.
1095 Valid values are:
1097 nil Do not check, so just do invisible edits.
1098 error Throw an error and do nothing.
1099 show Make point visible, and do the requested edit.
1100 show-and-error Make point visible, then throw an error and abort the edit.
1101 smart Make point visible, and do insertion/deletion if it is
1102 adjacent to visible text and the change feels predictable.
1103 Never delete a previously invisible character or add in the
1104 middle or right after an invisible region. Basically, this
1105 allows insertion and backward-delete right before ellipses.
1106 FIXME: maybe in this case we should not even show?"
1107 :group 'org-edit-structure
1108 :version "24.1"
1109 :type '(choice
1110 (const :tag "Do not check" nil)
1111 (const :tag "Throw error when trying to edit" error)
1112 (const :tag "Unhide, but do not do the edit" show-and-error)
1113 (const :tag "Show invisible part and do the edit" show)
1114 (const :tag "Be smart and do the right thing" smart)))
1116 (defcustom org-yank-folded-subtrees t
1117 "Non-nil means when yanking subtrees, fold them.
1118 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1119 it starts with a heading and all other headings in it are either children
1120 or siblings, then fold all the subtrees. However, do this only if no
1121 text after the yank would be swallowed into a folded tree by this action."
1122 :group 'org-edit-structure
1123 :type 'boolean)
1125 (defcustom org-yank-adjusted-subtrees nil
1126 "Non-nil means when yanking subtrees, adjust the level.
1127 With this setting, `org-paste-subtree' is used to insert the subtree, see
1128 this function for details."
1129 :group 'org-edit-structure
1130 :type 'boolean)
1132 (defcustom org-M-RET-may-split-line '((default . t))
1133 "Non-nil means M-RET will split the line at the cursor position.
1134 When nil, it will go to the end of the line before making a
1135 new line.
1136 You may also set this option in a different way for different
1137 contexts. Valid contexts are:
1139 headline when creating a new headline
1140 item when creating a new item
1141 table in a table field
1142 default the value to be used for all contexts not explicitly
1143 customized"
1144 :group 'org-structure
1145 :group 'org-table
1146 :type '(choice
1147 (const :tag "Always" t)
1148 (const :tag "Never" nil)
1149 (repeat :greedy t :tag "Individual contexts"
1150 (cons
1151 (choice :tag "Context"
1152 (const headline)
1153 (const item)
1154 (const table)
1155 (const default))
1156 (boolean)))))
1159 (defcustom org-insert-heading-respect-content nil
1160 "Non-nil means insert new headings after the current subtree.
1161 When nil, the new heading is created directly after the current line.
1162 The commands \\[org-insert-heading-respect-content] and
1163 \\[org-insert-todo-heading-respect-content] turn this variable on
1164 for the duration of the command."
1165 :group 'org-structure
1166 :type 'boolean)
1168 (defcustom org-blank-before-new-entry '((heading . auto)
1169 (plain-list-item . auto))
1170 "Should `org-insert-heading' leave a blank line before new heading/item?
1171 The value is an alist, with `heading' and `plain-list-item' as CAR,
1172 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1173 which case Org will look at the surrounding headings/items and try to
1174 make an intelligent decision whether to insert a blank line or not.
1176 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1177 set, the setting here is ignored and no empty line is inserted, to avoid
1178 breaking the list structure."
1179 :group 'org-edit-structure
1180 :type '(list
1181 (cons (const heading)
1182 (choice (const :tag "Never" nil)
1183 (const :tag "Always" t)
1184 (const :tag "Auto" auto)))
1185 (cons (const plain-list-item)
1186 (choice (const :tag "Never" nil)
1187 (const :tag "Always" t)
1188 (const :tag "Auto" auto)))))
1190 (defcustom org-insert-heading-hook nil
1191 "Hook being run after inserting a new heading."
1192 :group 'org-edit-structure
1193 :type 'hook)
1195 (defcustom org-enable-fixed-width-editor t
1196 "Non-nil means lines starting with \":\" are treated as fixed-width.
1197 This currently only means they are never auto-wrapped.
1198 When nil, such lines will be treated like ordinary lines.
1199 See also the QUOTE keyword."
1200 :group 'org-edit-structure
1201 :type 'boolean)
1203 (defcustom org-goto-auto-isearch t
1204 "Non-nil means typing characters in `org-goto' starts incremental search."
1205 :group 'org-edit-structure
1206 :type 'boolean)
1208 (defgroup org-sparse-trees nil
1209 "Options concerning sparse trees in Org-mode."
1210 :tag "Org Sparse Trees"
1211 :group 'org-structure)
1213 (defcustom org-highlight-sparse-tree-matches t
1214 "Non-nil means highlight all matches that define a sparse tree.
1215 The highlights will automatically disappear the next time the buffer is
1216 changed by an edit command."
1217 :group 'org-sparse-trees
1218 :type 'boolean)
1220 (defcustom org-remove-highlights-with-change t
1221 "Non-nil means any change to the buffer will remove temporary highlights.
1222 Such highlights are created by `org-occur' and `org-clock-display'.
1223 When nil, `C-c C-c needs to be used to get rid of the highlights.
1224 The highlights created by `org-preview-latex-fragment' always need
1225 `C-c C-c' to be removed."
1226 :group 'org-sparse-trees
1227 :group 'org-time
1228 :type 'boolean)
1231 (defcustom org-occur-hook '(org-first-headline-recenter)
1232 "Hook that is run after `org-occur' has constructed a sparse tree.
1233 This can be used to recenter the window to show as much of the structure
1234 as possible."
1235 :group 'org-sparse-trees
1236 :type 'hook)
1238 (defgroup org-imenu-and-speedbar nil
1239 "Options concerning imenu and speedbar in Org-mode."
1240 :tag "Org Imenu and Speedbar"
1241 :group 'org-structure)
1243 (defcustom org-imenu-depth 2
1244 "The maximum level for Imenu access to Org-mode headlines.
1245 This also applied for speedbar access."
1246 :group 'org-imenu-and-speedbar
1247 :type 'integer)
1249 (defgroup org-table nil
1250 "Options concerning tables in Org-mode."
1251 :tag "Org Table"
1252 :group 'org)
1254 (defcustom org-enable-table-editor 'optimized
1255 "Non-nil means lines starting with \"|\" are handled by the table editor.
1256 When nil, such lines will be treated like ordinary lines.
1258 When equal to the symbol `optimized', the table editor will be optimized to
1259 do the following:
1260 - Automatic overwrite mode in front of whitespace in table fields.
1261 This makes the structure of the table stay in tact as long as the edited
1262 field does not exceed the column width.
1263 - Minimize the number of realigns. Normally, the table is aligned each time
1264 TAB or RET are pressed to move to another field. With optimization this
1265 happens only if changes to a field might have changed the column width.
1266 Optimization requires replacing the functions `self-insert-command',
1267 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1268 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1269 very good at guessing when a re-align will be necessary, but you can always
1270 force one with \\[org-ctrl-c-ctrl-c].
1272 If you would like to use the optimized version in Org-mode, but the
1273 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1275 This variable can be used to turn on and off the table editor during a session,
1276 but in order to toggle optimization, a restart is required.
1278 See also the variable `org-table-auto-blank-field'."
1279 :group 'org-table
1280 :type '(choice
1281 (const :tag "off" nil)
1282 (const :tag "on" t)
1283 (const :tag "on, optimized" optimized)))
1285 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1286 (version<= emacs-version "24.1"))
1287 "Non-nil means cluster self-insert commands for undo when possible.
1288 If this is set, then, like in the Emacs command loop, 20 consecutive
1289 characters will be undone together.
1290 This is configurable, because there is some impact on typing performance."
1291 :group 'org-table
1292 :type 'boolean)
1294 (defcustom org-table-tab-recognizes-table.el t
1295 "Non-nil means TAB will automatically notice a table.el table.
1296 When it sees such a table, it moves point into it and - if necessary -
1297 calls `table-recognize-table'."
1298 :group 'org-table-editing
1299 :type 'boolean)
1301 (defgroup org-link nil
1302 "Options concerning links in Org-mode."
1303 :tag "Org Link"
1304 :group 'org)
1306 (defvar org-link-abbrev-alist-local nil
1307 "Buffer-local version of `org-link-abbrev-alist', which see.
1308 The value of this is taken from the #+LINK lines.")
1309 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1311 (defcustom org-link-abbrev-alist nil
1312 "Alist of link abbreviations.
1313 The car of each element is a string, to be replaced at the start of a link.
1314 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1315 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1317 [[linkkey:tag][description]]
1319 The 'linkkey' must be a word word, starting with a letter, followed
1320 by letters, numbers, '-' or '_'.
1322 If REPLACE is a string, the tag will simply be appended to create the link.
1323 If the string contains \"%s\", the tag will be inserted there. If the string
1324 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1325 at that point (see the function `url-hexify-string'). If the string contains
1326 the specifier \"%(my-function)\", then the custom function `my-function' will
1327 be invoked: this function takes the tag as its only argument and must return
1328 a string.
1330 REPLACE may also be a function that will be called with the tag as the
1331 only argument to create the link, which should be returned as a string.
1333 See the manual for examples."
1334 :group 'org-link
1335 :type '(repeat
1336 (cons
1337 (string :tag "Protocol")
1338 (choice
1339 (string :tag "Format")
1340 (function)))))
1342 (defcustom org-descriptive-links t
1343 "Non-nil means Org will display descriptive links.
1344 E.g. [[http://orgmode.org][Org website]] will be displayed as
1345 \"Org Website\", hiding the link itself and just displaying its
1346 description. When set to `nil', Org will display the full links
1347 literally.
1349 You can interactively set the value of this variable by calling
1350 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1351 :group 'org-link
1352 :type 'boolean)
1354 (defcustom org-link-file-path-type 'adaptive
1355 "How the path name in file links should be stored.
1356 Valid values are:
1358 relative Relative to the current directory, i.e. the directory of the file
1359 into which the link is being inserted.
1360 absolute Absolute path, if possible with ~ for home directory.
1361 noabbrev Absolute path, no abbreviation of home directory.
1362 adaptive Use relative path for files in the current directory and sub-
1363 directories of it. For other files, use an absolute path."
1364 :group 'org-link
1365 :type '(choice
1366 (const relative)
1367 (const absolute)
1368 (const noabbrev)
1369 (const adaptive)))
1371 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1372 "Types of links that should be activated in Org-mode files.
1373 This is a list of symbols, each leading to the activation of a certain link
1374 type. In principle, it does not hurt to turn on most link types - there may
1375 be a small gain when turning off unused link types. The types are:
1377 bracket The recommended [[link][description]] or [[link]] links with hiding.
1378 angle Links in angular brackets that may contain whitespace like
1379 <bbdb:Carsten Dominik>.
1380 plain Plain links in normal text, no whitespace, like http://google.com.
1381 radio Text that is matched by a radio target, see manual for details.
1382 tag Tag settings in a headline (link to tag search).
1383 date Time stamps (link to calendar).
1384 footnote Footnote labels.
1386 Changing this variable requires a restart of Emacs to become effective."
1387 :group 'org-link
1388 :type '(set :greedy t
1389 (const :tag "Double bracket links" bracket)
1390 (const :tag "Angular bracket links" angle)
1391 (const :tag "Plain text links" plain)
1392 (const :tag "Radio target matches" radio)
1393 (const :tag "Tags" tag)
1394 (const :tag "Timestamps" date)
1395 (const :tag "Footnotes" footnote)))
1397 (defcustom org-make-link-description-function nil
1398 "Function to use for generating link descriptions from links.
1399 When nil, the link location will be used. This function must take
1400 two parameters: the first one is the link, the second one is the
1401 description generated by `org-insert-link'. The function should
1402 return the description to use."
1403 :group 'org-link
1404 :type 'function)
1406 (defgroup org-link-store nil
1407 "Options concerning storing links in Org-mode."
1408 :tag "Org Store Link"
1409 :group 'org-link)
1411 (defcustom org-url-hexify-p t
1412 "When non-nil, hexify URL when creating a link."
1413 :type 'boolean
1414 :version "24.3"
1415 :group 'org-link-store)
1417 (defcustom org-email-link-description-format "Email %c: %.30s"
1418 "Format of the description part of a link to an email or usenet message.
1419 The following %-escapes will be replaced by corresponding information:
1421 %F full \"From\" field
1422 %f name, taken from \"From\" field, address if no name
1423 %T full \"To\" field
1424 %t first name in \"To\" field, address if no name
1425 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1426 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1427 %s subject
1428 %d date
1429 %m message-id.
1431 You may use normal field width specification between the % and the letter.
1432 This is for example useful to limit the length of the subject.
1434 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1435 :group 'org-link-store
1436 :type 'string)
1438 (defcustom org-from-is-user-regexp
1439 (let (r1 r2)
1440 (when (and user-mail-address (not (string= user-mail-address "")))
1441 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1442 (when (and user-full-name (not (string= user-full-name "")))
1443 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1444 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1445 "Regexp matched against the \"From:\" header of an email or usenet message.
1446 It should match if the message is from the user him/herself."
1447 :group 'org-link-store
1448 :type 'regexp)
1450 (defcustom org-context-in-file-links t
1451 "Non-nil means file links from `org-store-link' contain context.
1452 A search string will be added to the file name with :: as separator and
1453 used to find the context when the link is activated by the command
1454 `org-open-at-point'. When this option is t, the entire active region
1455 will be placed in the search string of the file link. If set to a
1456 positive integer, only the first n lines of context will be stored.
1458 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1459 negates this setting for the duration of the command."
1460 :group 'org-link-store
1461 :type '(choice boolean integer))
1463 (defcustom org-keep-stored-link-after-insertion nil
1464 "Non-nil means keep link in list for entire session.
1466 The command `org-store-link' adds a link pointing to the current
1467 location to an internal list. These links accumulate during a session.
1468 The command `org-insert-link' can be used to insert links into any
1469 Org-mode file (offering completion for all stored links). When this
1470 option is nil, every link which has been inserted once using \\[org-insert-link]
1471 will be removed from the list, to make completing the unused links
1472 more efficient."
1473 :group 'org-link-store
1474 :type 'boolean)
1476 (defgroup org-link-follow nil
1477 "Options concerning following links in Org-mode."
1478 :tag "Org Follow Link"
1479 :group 'org-link)
1481 (defcustom org-link-translation-function nil
1482 "Function to translate links with different syntax to Org syntax.
1483 This can be used to translate links created for example by the Planner
1484 or emacs-wiki packages to Org syntax.
1485 The function must accept two parameters, a TYPE containing the link
1486 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1487 which is everything after the link protocol. It should return a cons
1488 with possibly modified values of type and path.
1489 Org contains a function for this, so if you set this variable to
1490 `org-translate-link-from-planner', you should be able follow many
1491 links created by planner."
1492 :group 'org-link-follow
1493 :type 'function)
1495 (defcustom org-follow-link-hook nil
1496 "Hook that is run after a link has been followed."
1497 :group 'org-link-follow
1498 :type 'hook)
1500 (defcustom org-tab-follows-link nil
1501 "Non-nil means on links TAB will follow the link.
1502 Needs to be set before org.el is loaded.
1503 This really should not be used, it does not make sense, and the
1504 implementation is bad."
1505 :group 'org-link-follow
1506 :type 'boolean)
1508 (defcustom org-return-follows-link nil
1509 "Non-nil means on links RET will follow the link."
1510 :group 'org-link-follow
1511 :type 'boolean)
1513 (defcustom org-mouse-1-follows-link
1514 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1515 "Non-nil means mouse-1 on a link will follow the link.
1516 A longer mouse click will still set point. Does not work on XEmacs.
1517 Needs to be set before org.el is loaded."
1518 :group 'org-link-follow
1519 :type 'boolean)
1521 (defcustom org-mark-ring-length 4
1522 "Number of different positions to be recorded in the ring.
1523 Changing this requires a restart of Emacs to work correctly."
1524 :group 'org-link-follow
1525 :type 'integer)
1527 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1528 "Non-nil means internal links in Org files must exactly match a headline.
1529 When nil, the link search tries to match a phrase with all words
1530 in the search text."
1531 :group 'org-link-follow
1532 :version "24.1"
1533 :type '(choice
1534 (const :tag "Use fuzzy text search" nil)
1535 (const :tag "Match only exact headline" t)
1536 (const :tag "Match exact headline or query to create it"
1537 query-to-create)))
1539 (defcustom org-link-frame-setup
1540 '((vm . vm-visit-folder-other-frame)
1541 (vm-imap . vm-visit-imap-folder-other-frame)
1542 (gnus . org-gnus-no-new-news)
1543 (file . find-file-other-window)
1544 (wl . wl-other-frame))
1545 "Setup the frame configuration for following links.
1546 When following a link with Emacs, it may often be useful to display
1547 this link in another window or frame. This variable can be used to
1548 set this up for the different types of links.
1549 For VM, use any of
1550 `vm-visit-folder'
1551 `vm-visit-folder-other-window'
1552 `vm-visit-folder-other-frame'
1553 For Gnus, use any of
1554 `gnus'
1555 `gnus-other-frame'
1556 `org-gnus-no-new-news'
1557 For FILE, use any of
1558 `find-file'
1559 `find-file-other-window'
1560 `find-file-other-frame'
1561 For Wanderlust use any of
1562 `wl'
1563 `wl-other-frame'
1564 For the calendar, use the variable `calendar-setup'.
1565 For BBDB, it is currently only possible to display the matches in
1566 another window."
1567 :group 'org-link-follow
1568 :type '(list
1569 (cons (const vm)
1570 (choice
1571 (const vm-visit-folder)
1572 (const vm-visit-folder-other-window)
1573 (const vm-visit-folder-other-frame)))
1574 (cons (const gnus)
1575 (choice
1576 (const gnus)
1577 (const gnus-other-frame)
1578 (const org-gnus-no-new-news)))
1579 (cons (const file)
1580 (choice
1581 (const find-file)
1582 (const find-file-other-window)
1583 (const find-file-other-frame)))
1584 (cons (const wl)
1585 (choice
1586 (const wl)
1587 (const wl-other-frame)))))
1589 (defcustom org-display-internal-link-with-indirect-buffer nil
1590 "Non-nil means use indirect buffer to display infile links.
1591 Activating internal links (from one location in a file to another location
1592 in the same file) normally just jumps to the location. When the link is
1593 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1594 is displayed in
1595 another window. When this option is set, the other window actually displays
1596 an indirect buffer clone of the current buffer, to avoid any visibility
1597 changes to the current buffer."
1598 :group 'org-link-follow
1599 :type 'boolean)
1601 (defcustom org-open-non-existing-files nil
1602 "Non-nil means `org-open-file' will open non-existing files.
1603 When nil, an error will be generated.
1604 This variable applies only to external applications because they
1605 might choke on non-existing files. If the link is to a file that
1606 will be opened in Emacs, the variable is ignored."
1607 :group 'org-link-follow
1608 :type 'boolean)
1610 (defcustom org-open-directory-means-index-dot-org nil
1611 "Non-nil means a link to a directory really means to index.org.
1612 When nil, following a directory link will run dired or open a finder/explorer
1613 window on that directory."
1614 :group 'org-link-follow
1615 :type 'boolean)
1617 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1618 "Function and arguments to call for following mailto links.
1619 This is a list with the first element being a Lisp function, and the
1620 remaining elements being arguments to the function. In string arguments,
1621 %a will be replaced by the address, and %s will be replaced by the subject
1622 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1623 :group 'org-link-follow
1624 :type '(choice
1625 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1626 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1627 (const :tag "message-mail" (message-mail "%a" "%s"))
1628 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1630 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1631 "Non-nil means ask for confirmation before executing shell links.
1632 Shell links can be dangerous: just think about a link
1634 [[shell:rm -rf ~/*][Google Search]]
1636 This link would show up in your Org-mode document as \"Google Search\",
1637 but really it would remove your entire home directory.
1638 Therefore we advise against setting this variable to nil.
1639 Just change it to `y-or-n-p' if you want to confirm with a
1640 single keystroke rather than having to type \"yes\"."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1644 (const :tag "with y-or-n (faster)" y-or-n-p)
1645 (const :tag "no confirmation (dangerous)" nil)))
1646 (put 'org-confirm-shell-link-function
1647 'safe-local-variable
1648 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1650 (defcustom org-confirm-shell-link-not-regexp ""
1651 "A regexp to skip confirmation for shell links."
1652 :group 'org-link-follow
1653 :version "24.1"
1654 :type 'regexp)
1656 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1658 Elisp links can be dangerous: just think about a link
1660 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group 'org-link-follow
1668 :type '(choice
1669 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1670 (const :tag "with y-or-n (faster)" y-or-n-p)
1671 (const :tag "no confirmation (dangerous)" nil)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1676 (defcustom org-confirm-elisp-link-not-regexp ""
1677 "A regexp to skip confirmation for Elisp links."
1678 :group 'org-link-follow
1679 :version "24.1"
1680 :type 'regexp)
1682 (defconst org-file-apps-defaults-gnu
1683 '((remote . emacs)
1684 (system . mailcap)
1685 (t . mailcap))
1686 "Default file applications on a UNIX or GNU/Linux system.
1687 See `org-file-apps'.")
1689 (defconst org-file-apps-defaults-macosx
1690 '((remote . emacs)
1691 (t . "open %s")
1692 (system . "open %s")
1693 ("ps.gz" . "gv %s")
1694 ("eps.gz" . "gv %s")
1695 ("dvi" . "xdvi %s")
1696 ("fig" . "xfig %s"))
1697 "Default file applications on a MacOS X system.
1698 The system \"open\" is known as a default, but we use X11 applications
1699 for some files for which the OS does not have a good default.
1700 See `org-file-apps'.")
1702 (defconst org-file-apps-defaults-windowsnt
1703 (list
1704 '(remote . emacs)
1705 (cons t
1706 (list (if (featurep 'xemacs)
1707 'mswindows-shell-execute
1708 'w32-shell-execute)
1709 "open" 'file))
1710 (cons 'system
1711 (list (if (featurep 'xemacs)
1712 'mswindows-shell-execute
1713 'w32-shell-execute)
1714 "open" 'file)))
1715 "Default file applications on a Windows NT system.
1716 The system \"open\" is used for most files.
1717 See `org-file-apps'.")
1719 (defcustom org-file-apps
1721 (auto-mode . emacs)
1722 ("\\.mm\\'" . default)
1723 ("\\.x?html?\\'" . default)
1724 ("\\.pdf\\'" . default)
1726 "External applications for opening `file:path' items in a document.
1727 Org-mode uses system defaults for different file types, but
1728 you can use this variable to set the application for a given file
1729 extension. The entries in this list are cons cells where the car identifies
1730 files and the cdr the corresponding command. Possible values for the
1731 file identifier are
1732 \"string\" A string as a file identifier can be interpreted in different
1733 ways, depending on its contents:
1735 - Alphanumeric characters only:
1736 Match links with this file extension.
1737 Example: (\"pdf\" . \"evince %s\")
1738 to open PDFs with evince.
1740 - Regular expression: Match links where the
1741 filename matches the regexp. If you want to
1742 use groups here, use shy groups.
1744 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1745 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1746 to open *.html and *.xhtml with firefox.
1748 - Regular expression which contains (non-shy) groups:
1749 Match links where the whole link, including \"::\", and
1750 anything after that, matches the regexp.
1751 In a custom command string, %1, %2, etc. are replaced with
1752 the parts of the link that were matched by the groups.
1753 For backwards compatibility, if a command string is given
1754 that does not use any of the group matches, this case is
1755 handled identically to the second one (i.e. match against
1756 file name only).
1757 In a custom lisp form, you can access the group matches with
1758 (match-string n link).
1760 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1761 to open [[file:document.pdf::5]] with evince at page 5.
1763 `directory' Matches a directory
1764 `remote' Matches a remote file, accessible through tramp or efs.
1765 Remote files most likely should be visited through Emacs
1766 because external applications cannot handle such paths.
1767 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1768 so all files Emacs knows how to handle. Using this with
1769 command `emacs' will open most files in Emacs. Beware that this
1770 will also open html files inside Emacs, unless you add
1771 (\"html\" . default) to the list as well.
1772 t Default for files not matched by any of the other options.
1773 `system' The system command to open files, like `open' on Windows
1774 and Mac OS X, and mailcap under GNU/Linux. This is the command
1775 that will be selected if you call `C-c C-o' with a double
1776 \\[universal-argument] \\[universal-argument] prefix.
1778 Possible values for the command are:
1779 `emacs' The file will be visited by the current Emacs process.
1780 `default' Use the default application for this file type, which is the
1781 association for t in the list, most likely in the system-specific
1782 part.
1783 This can be used to overrule an unwanted setting in the
1784 system-specific variable.
1785 `system' Use the system command for opening files, like \"open\".
1786 This command is specified by the entry whose car is `system'.
1787 Most likely, the system-specific version of this variable
1788 does define this command, but you can overrule/replace it
1789 here.
1790 string A command to be executed by a shell; %s will be replaced
1791 by the path to the file.
1792 sexp A Lisp form which will be evaluated. The file path will
1793 be available in the Lisp variable `file'.
1794 For more examples, see the system specific constants
1795 `org-file-apps-defaults-macosx'
1796 `org-file-apps-defaults-windowsnt'
1797 `org-file-apps-defaults-gnu'."
1798 :group 'org-link-follow
1799 :type '(repeat
1800 (cons (choice :value ""
1801 (string :tag "Extension")
1802 (const :tag "System command to open files" system)
1803 (const :tag "Default for unrecognized files" t)
1804 (const :tag "Remote file" remote)
1805 (const :tag "Links to a directory" directory)
1806 (const :tag "Any files that have Emacs modes"
1807 auto-mode))
1808 (choice :value ""
1809 (const :tag "Visit with Emacs" emacs)
1810 (const :tag "Use default" default)
1811 (const :tag "Use the system command" system)
1812 (string :tag "Command")
1813 (sexp :tag "Lisp form")))))
1815 (defcustom org-doi-server-url "http://dx.doi.org/"
1816 "The URL of the DOI server."
1817 :type 'string
1818 :version "24.3"
1819 :group 'org-link-follow)
1821 (defgroup org-refile nil
1822 "Options concerning refiling entries in Org-mode."
1823 :tag "Org Refile"
1824 :group 'org)
1826 (defcustom org-directory "~/org"
1827 "Directory with org files.
1828 This is just a default location to look for Org files. There is no need
1829 at all to put your files into this directory. It is only used in the
1830 following situations:
1832 1. When a capture template specifies a target file that is not an
1833 absolute path. The path will then be interpreted relative to
1834 `org-directory'
1835 2. When a capture note is filed away in an interactive way (when exiting the
1836 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1837 with `org-directory' as the default path."
1838 :group 'org-refile
1839 :group 'org-remember
1840 :group 'org-capture
1841 :type 'directory)
1843 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1844 "Default target for storing notes.
1845 Used as a fall back file for org-remember.el and org-capture.el, for
1846 templates that do not specify a target file."
1847 :group 'org-refile
1848 :group 'org-remember
1849 :group 'org-capture
1850 :type '(choice
1851 (const :tag "Default from remember-data-file" nil)
1852 file))
1854 (defcustom org-goto-interface 'outline
1855 "The default interface to be used for `org-goto'.
1856 Allowed values are:
1857 outline The interface shows an outline of the relevant file
1858 and the correct heading is found by moving through
1859 the outline or by searching with incremental search.
1860 outline-path-completion Headlines in the current buffer are offered via
1861 completion. This is the interface also used by
1862 the refile command."
1863 :group 'org-refile
1864 :type '(choice
1865 (const :tag "Outline" outline)
1866 (const :tag "Outline-path-completion" outline-path-completion)))
1868 (defcustom org-goto-max-level 5
1869 "Maximum target level when running `org-goto' with refile interface."
1870 :group 'org-refile
1871 :type 'integer)
1873 (defcustom org-reverse-note-order nil
1874 "Non-nil means store new notes at the beginning of a file or entry.
1875 When nil, new notes will be filed to the end of a file or entry.
1876 This can also be a list with cons cells of regular expressions that
1877 are matched against file names, and values."
1878 :group 'org-remember
1879 :group 'org-capture
1880 :group 'org-refile
1881 :type '(choice
1882 (const :tag "Reverse always" t)
1883 (const :tag "Reverse never" nil)
1884 (repeat :tag "By file name regexp"
1885 (cons regexp boolean))))
1887 (defcustom org-log-refile nil
1888 "Information to record when a task is refiled.
1890 Possible values are:
1892 nil Don't add anything
1893 time Add a time stamp to the task
1894 note Prompt for a note and add it with template `org-log-note-headings'
1896 This option can also be set with on a per-file-basis with
1898 #+STARTUP: nologrefile
1899 #+STARTUP: logrefile
1900 #+STARTUP: lognoterefile
1902 You can have local logging settings for a subtree by setting the LOGGING
1903 property to one or more of these keywords.
1905 When bulk-refiling from the agenda, the value `note' is forbidden and
1906 will temporarily be changed to `time'."
1907 :group 'org-refile
1908 :group 'org-progress
1909 :version "24.1"
1910 :type '(choice
1911 (const :tag "No logging" nil)
1912 (const :tag "Record timestamp" time)
1913 (const :tag "Record timestamp with note." note)))
1915 (defcustom org-refile-targets nil
1916 "Targets for refiling entries with \\[org-refile].
1917 This is a list of cons cells. Each cell contains:
1918 - a specification of the files to be considered, either a list of files,
1919 or a symbol whose function or variable value will be used to retrieve
1920 a file name or a list of file names. If you use `org-agenda-files' for
1921 that, all agenda files will be scanned for targets. Nil means consider
1922 headings in the current buffer.
1923 - A specification of how to find candidate refile targets. This may be
1924 any of:
1925 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1926 This tag has to be present in all target headlines, inheritance will
1927 not be considered.
1928 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1929 todo keyword.
1930 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1931 headlines that are refiling targets.
1932 - a cons cell (:level . N). Any headline of level N is considered a target.
1933 Note that, when `org-odd-levels-only' is set, level corresponds to
1934 order in hierarchy, not to the number of stars.
1935 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1936 Note that, when `org-odd-levels-only' is set, level corresponds to
1937 order in hierarchy, not to the number of stars.
1939 Each element of this list generates a set of possible targets.
1940 The union of these sets is presented (with completion) to
1941 the user by `org-refile'.
1943 You can set the variable `org-refile-target-verify-function' to a function
1944 to verify each headline found by the simple criteria above.
1946 When this variable is nil, all top-level headlines in the current buffer
1947 are used, equivalent to the value `((nil . (:level . 1))'."
1948 :group 'org-refile
1949 :type '(repeat
1950 (cons
1951 (choice :value org-agenda-files
1952 (const :tag "All agenda files" org-agenda-files)
1953 (const :tag "Current buffer" nil)
1954 (function) (variable) (file))
1955 (choice :tag "Identify target headline by"
1956 (cons :tag "Specific tag" (const :value :tag) (string))
1957 (cons :tag "TODO keyword" (const :value :todo) (string))
1958 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1959 (cons :tag "Level number" (const :value :level) (integer))
1960 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1962 (defcustom org-refile-target-verify-function nil
1963 "Function to verify if the headline at point should be a refile target.
1964 The function will be called without arguments, with point at the
1965 beginning of the headline. It should return t and leave point
1966 where it is if the headline is a valid target for refiling.
1968 If the target should not be selected, the function must return nil.
1969 In addition to this, it may move point to a place from where the search
1970 should be continued. For example, the function may decide that the entire
1971 subtree of the current entry should be excluded and move point to the end
1972 of the subtree."
1973 :group 'org-refile
1974 :type 'function)
1976 (defcustom org-refile-use-cache nil
1977 "Non-nil means cache refile targets to speed up the process.
1978 The cache for a particular file will be updated automatically when
1979 the buffer has been killed, or when any of the marker used for flagging
1980 refile targets no longer points at a live buffer.
1981 If you have added new entries to a buffer that might themselves be targets,
1982 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1983 find that easier, `C-u C-u C-u C-c C-w'."
1984 :group 'org-refile
1985 :version "24.1"
1986 :type 'boolean)
1988 (defcustom org-refile-use-outline-path nil
1989 "Non-nil means provide refile targets as paths.
1990 So a level 3 headline will be available as level1/level2/level3.
1992 When the value is `file', also include the file name (without directory)
1993 into the path. In this case, you can also stop the completion after
1994 the file name, to get entries inserted as top level in the file.
1996 When `full-file-path', include the full file path."
1997 :group 'org-refile
1998 :type '(choice
1999 (const :tag "Not" nil)
2000 (const :tag "Yes" t)
2001 (const :tag "Start with file name" file)
2002 (const :tag "Start with full file path" full-file-path)))
2004 (defcustom org-outline-path-complete-in-steps t
2005 "Non-nil means complete the outline path in hierarchical steps.
2006 When Org-mode uses the refile interface to select an outline path
2007 \(see variable `org-refile-use-outline-path'), the completion of
2008 the path can be done is a single go, or if can be done in steps down
2009 the headline hierarchy. Going in steps is probably the best if you
2010 do not use a special completion package like `ido' or `icicles'.
2011 However, when using these packages, going in one step can be very
2012 fast, while still showing the whole path to the entry."
2013 :group 'org-refile
2014 :type 'boolean)
2016 (defcustom org-refile-allow-creating-parent-nodes nil
2017 "Non-nil means allow to create new nodes as refile targets.
2018 New nodes are then created by adding \"/new node name\" to the completion
2019 of an existing node. When the value of this variable is `confirm',
2020 new node creation must be confirmed by the user (recommended)
2021 When nil, the completion must match an existing entry.
2023 Note that, if the new heading is not seen by the criteria
2024 listed in `org-refile-targets', multiple instances of the same
2025 heading would be created by trying again to file under the new
2026 heading."
2027 :group 'org-refile
2028 :type '(choice
2029 (const :tag "Never" nil)
2030 (const :tag "Always" t)
2031 (const :tag "Prompt for confirmation" confirm)))
2033 (defcustom org-refile-active-region-within-subtree nil
2034 "Non-nil means also refile active region within a subtree.
2036 By default `org-refile' doesn't allow refiling regions if they
2037 don't contain a set of subtrees, but it might be convenient to
2038 do so sometimes: in that case, the first line of the region is
2039 converted to a headline before refiling."
2040 :group 'org-refile
2041 :version "24.1"
2042 :type 'boolean)
2044 (defgroup org-todo nil
2045 "Options concerning TODO items in Org-mode."
2046 :tag "Org TODO"
2047 :group 'org)
2049 (defgroup org-progress nil
2050 "Options concerning Progress logging in Org-mode."
2051 :tag "Org Progress"
2052 :group 'org-time)
2054 (defvar org-todo-interpretation-widgets
2055 '((:tag "Sequence (cycling hits every state)" sequence)
2056 (:tag "Type (cycling directly to DONE)" type))
2057 "The available interpretation symbols for customizing `org-todo-keywords'.
2058 Interested libraries should add to this list.")
2060 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2061 "List of TODO entry keyword sequences and their interpretation.
2062 \\<org-mode-map>This is a list of sequences.
2064 Each sequence starts with a symbol, either `sequence' or `type',
2065 indicating if the keywords should be interpreted as a sequence of
2066 action steps, or as different types of TODO items. The first
2067 keywords are states requiring action - these states will select a headline
2068 for inclusion into the global TODO list Org-mode produces. If one of
2069 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2070 signify that no further action is necessary. If \"|\" is not found,
2071 the last keyword is treated as the only DONE state of the sequence.
2073 The command \\[org-todo] cycles an entry through these states, and one
2074 additional state where no keyword is present. For details about this
2075 cycling, see the manual.
2077 TODO keywords and interpretation can also be set on a per-file basis with
2078 the special #+SEQ_TODO and #+TYP_TODO lines.
2080 Each keyword can optionally specify a character for fast state selection
2081 \(in combination with the variable `org-use-fast-todo-selection')
2082 and specifiers for state change logging, using the same syntax that
2083 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2084 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2085 indicates to record a time stamp each time this state is selected.
2087 Each keyword may also specify if a timestamp or a note should be
2088 recorded when entering or leaving the state, by adding additional
2089 characters in the parenthesis after the keyword. This looks like this:
2090 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2091 record only the time of the state change. With X and Y being either
2092 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2093 Y when leaving the state if and only if the *target* state does not
2094 define X. You may omit any of the fast-selection key or X or /Y,
2095 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2097 For backward compatibility, this variable may also be just a list
2098 of keywords. In this case the interpretation (sequence or type) will be
2099 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2100 :group 'org-todo
2101 :group 'org-keywords
2102 :type '(choice
2103 (repeat :tag "Old syntax, just keywords"
2104 (string :tag "Keyword"))
2105 (repeat :tag "New syntax"
2106 (cons
2107 (choice
2108 :tag "Interpretation"
2109 ;;Quick and dirty way to see
2110 ;;`org-todo-interpretations'. This takes the
2111 ;;place of item arguments
2112 :convert-widget
2113 (lambda (widget)
2114 (widget-put widget
2115 :args (mapcar
2116 #'(lambda (x)
2117 (widget-convert
2118 (cons 'const x)))
2119 org-todo-interpretation-widgets))
2120 widget))
2121 (repeat
2122 (string :tag "Keyword"))))))
2124 (defvar org-todo-keywords-1 nil
2125 "All TODO and DONE keywords active in a buffer.")
2126 (make-variable-buffer-local 'org-todo-keywords-1)
2127 (defvar org-todo-keywords-for-agenda nil)
2128 (defvar org-done-keywords-for-agenda nil)
2129 (defvar org-drawers-for-agenda nil)
2130 (defvar org-todo-keyword-alist-for-agenda nil)
2131 (defvar org-tag-alist-for-agenda nil)
2132 (defvar org-agenda-contributing-files nil)
2133 (defvar org-not-done-keywords nil)
2134 (make-variable-buffer-local 'org-not-done-keywords)
2135 (defvar org-done-keywords nil)
2136 (make-variable-buffer-local 'org-done-keywords)
2137 (defvar org-todo-heads nil)
2138 (make-variable-buffer-local 'org-todo-heads)
2139 (defvar org-todo-sets nil)
2140 (make-variable-buffer-local 'org-todo-sets)
2141 (defvar org-todo-log-states nil)
2142 (make-variable-buffer-local 'org-todo-log-states)
2143 (defvar org-todo-kwd-alist nil)
2144 (make-variable-buffer-local 'org-todo-kwd-alist)
2145 (defvar org-todo-key-alist nil)
2146 (make-variable-buffer-local 'org-todo-key-alist)
2147 (defvar org-todo-key-trigger nil)
2148 (make-variable-buffer-local 'org-todo-key-trigger)
2150 (defcustom org-todo-interpretation 'sequence
2151 "Controls how TODO keywords are interpreted.
2152 This variable is in principle obsolete and is only used for
2153 backward compatibility, if the interpretation of todo keywords is
2154 not given already in `org-todo-keywords'. See that variable for
2155 more information."
2156 :group 'org-todo
2157 :group 'org-keywords
2158 :type '(choice (const sequence)
2159 (const type)))
2161 (defcustom org-use-fast-todo-selection t
2162 "Non-nil means use the fast todo selection scheme with C-c C-t.
2163 This variable describes if and under what circumstances the cycling
2164 mechanism for TODO keywords will be replaced by a single-key, direct
2165 selection scheme.
2167 When nil, fast selection is never used.
2169 When the symbol `prefix', it will be used when `org-todo' is called
2170 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2171 `C-u t' in an agenda buffer.
2173 When t, fast selection is used by default. In this case, the prefix
2174 argument forces cycling instead.
2176 In all cases, the special interface is only used if access keys have
2177 actually been assigned by the user, i.e. if keywords in the configuration
2178 are followed by a letter in parenthesis, like TODO(t)."
2179 :group 'org-todo
2180 :type '(choice
2181 (const :tag "Never" nil)
2182 (const :tag "By default" t)
2183 (const :tag "Only with C-u C-c C-t" prefix)))
2185 (defcustom org-provide-todo-statistics t
2186 "Non-nil means update todo statistics after insert and toggle.
2187 ALL-HEADLINES means update todo statistics by including headlines
2188 with no TODO keyword as well, counting them as not done.
2189 A list of TODO keywords means the same, but skip keywords that are
2190 not in this list.
2192 When this is set, todo statistics is updated in the parent of the
2193 current entry each time a todo state is changed."
2194 :group 'org-todo
2195 :type '(choice
2196 (const :tag "Yes, only for TODO entries" t)
2197 (const :tag "Yes, including all entries" 'all-headlines)
2198 (repeat :tag "Yes, for TODOs in this list"
2199 (string :tag "TODO keyword"))
2200 (other :tag "No TODO statistics" nil)))
2202 (defcustom org-hierarchical-todo-statistics t
2203 "Non-nil means TODO statistics covers just direct children.
2204 When nil, all entries in the subtree are considered.
2205 This has only an effect if `org-provide-todo-statistics' is set.
2206 To set this to nil for only a single subtree, use a COOKIE_DATA
2207 property and include the word \"recursive\" into the value."
2208 :group 'org-todo
2209 :type 'boolean)
2211 (defcustom org-after-todo-state-change-hook nil
2212 "Hook which is run after the state of a TODO item was changed.
2213 The new state (a string with a TODO keyword, or nil) is available in the
2214 Lisp variable `org-state'."
2215 :group 'org-todo
2216 :type 'hook)
2218 (defvar org-blocker-hook nil
2219 "Hook for functions that are allowed to block a state change.
2221 Each function gets as its single argument a property list, see
2222 `org-trigger-hook' for more information about this list.
2224 If any of the functions in this hook returns nil, the state change
2225 is blocked.")
2227 (defvar org-trigger-hook nil
2228 "Hook for functions that are triggered by a state change.
2230 Each function gets as its single argument a property list with at least
2231 the following elements:
2233 (:type type-of-change :position pos-at-entry-start
2234 :from old-state :to new-state)
2236 Depending on the type, more properties may be present.
2238 This mechanism is currently implemented for:
2240 TODO state changes
2241 ------------------
2242 :type todo-state-change
2243 :from previous state (keyword as a string), or nil, or a symbol
2244 'todo' or 'done', to indicate the general type of state.
2245 :to new state, like in :from")
2247 (defcustom org-enforce-todo-dependencies nil
2248 "Non-nil means undone TODO entries will block switching the parent to DONE.
2249 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2250 be blocked if any prior sibling is not yet done.
2251 Finally, if the parent is blocked because of ordered siblings of its own,
2252 the child will also be blocked."
2253 :set (lambda (var val)
2254 (set var val)
2255 (if val
2256 (add-hook 'org-blocker-hook
2257 'org-block-todo-from-children-or-siblings-or-parent)
2258 (remove-hook 'org-blocker-hook
2259 'org-block-todo-from-children-or-siblings-or-parent)))
2260 :group 'org-todo
2261 :type 'boolean)
2263 (defcustom org-enforce-todo-checkbox-dependencies nil
2264 "Non-nil means unchecked boxes will block switching the parent to DONE.
2265 When this is nil, checkboxes have no influence on switching TODO states.
2266 When non-nil, you first need to check off all check boxes before the TODO
2267 entry can be switched to DONE.
2268 This variable needs to be set before org.el is loaded, and you need to
2269 restart Emacs after a change to make the change effective. The only way
2270 to change is while Emacs is running is through the customize interface."
2271 :set (lambda (var val)
2272 (set var val)
2273 (if val
2274 (add-hook 'org-blocker-hook
2275 'org-block-todo-from-checkboxes)
2276 (remove-hook 'org-blocker-hook
2277 'org-block-todo-from-checkboxes)))
2278 :group 'org-todo
2279 :type 'boolean)
2281 (defcustom org-treat-insert-todo-heading-as-state-change nil
2282 "Non-nil means inserting a TODO heading is treated as state change.
2283 So when the command \\[org-insert-todo-heading] is used, state change
2284 logging will apply if appropriate. When nil, the new TODO item will
2285 be inserted directly, and no logging will take place."
2286 :group 'org-todo
2287 :type 'boolean)
2289 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2290 "Non-nil means switching TODO states with S-cursor counts as state change.
2291 This is the default behavior. However, setting this to nil allows a
2292 convenient way to select a TODO state and bypass any logging associated
2293 with that."
2294 :group 'org-todo
2295 :type 'boolean)
2297 (defcustom org-todo-state-tags-triggers nil
2298 "Tag changes that should be triggered by TODO state changes.
2299 This is a list. Each entry is
2301 (state-change (tag . flag) .......)
2303 State-change can be a string with a state, and empty string to indicate the
2304 state that has no TODO keyword, or it can be one of the symbols `todo'
2305 or `done', meaning any not-done or done state, respectively."
2306 :group 'org-todo
2307 :group 'org-tags
2308 :type '(repeat
2309 (cons (choice :tag "When changing to"
2310 (const :tag "Not-done state" todo)
2311 (const :tag "Done state" done)
2312 (string :tag "State"))
2313 (repeat
2314 (cons :tag "Tag action"
2315 (string :tag "Tag")
2316 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2318 (defcustom org-log-done nil
2319 "Information to record when a task moves to the DONE state.
2321 Possible values are:
2323 nil Don't add anything, just change the keyword
2324 time Add a time stamp to the task
2325 note Prompt for a note and add it with template `org-log-note-headings'
2327 This option can also be set with on a per-file-basis with
2329 #+STARTUP: nologdone
2330 #+STARTUP: logdone
2331 #+STARTUP: lognotedone
2333 You can have local logging settings for a subtree by setting the LOGGING
2334 property to one or more of these keywords."
2335 :group 'org-todo
2336 :group 'org-progress
2337 :type '(choice
2338 (const :tag "No logging" nil)
2339 (const :tag "Record CLOSED timestamp" time)
2340 (const :tag "Record CLOSED timestamp with note." note)))
2342 ;; Normalize old uses of org-log-done.
2343 (cond
2344 ((eq org-log-done t) (setq org-log-done 'time))
2345 ((and (listp org-log-done) (memq 'done org-log-done))
2346 (setq org-log-done 'note)))
2348 (defcustom org-log-reschedule nil
2349 "Information to record when the scheduling date of a tasks is modified.
2351 Possible values are:
2353 nil Don't add anything, just change the date
2354 time Add a time stamp to the task
2355 note Prompt for a note and add it with template `org-log-note-headings'
2357 This option can also be set with on a per-file-basis with
2359 #+STARTUP: nologreschedule
2360 #+STARTUP: logreschedule
2361 #+STARTUP: lognotereschedule"
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "No logging" nil)
2366 (const :tag "Record timestamp" time)
2367 (const :tag "Record timestamp with note." note)))
2369 (defcustom org-log-redeadline nil
2370 "Information to record when the deadline date of a tasks is modified.
2372 Possible values are:
2374 nil Don't add anything, just change the date
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologredeadline
2381 #+STARTUP: logredeadline
2382 #+STARTUP: lognoteredeadline
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords."
2386 :group 'org-todo
2387 :group 'org-progress
2388 :type '(choice
2389 (const :tag "No logging" nil)
2390 (const :tag "Record timestamp" time)
2391 (const :tag "Record timestamp with note." note)))
2393 (defcustom org-log-note-clock-out nil
2394 "Non-nil means record a note when clocking out of an item.
2395 This can also be configured on a per-file basis by adding one of
2396 the following lines anywhere in the buffer:
2398 #+STARTUP: lognoteclock-out
2399 #+STARTUP: nolognoteclock-out"
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type 'boolean)
2404 (defcustom org-log-done-with-time t
2405 "Non-nil means the CLOSED time stamp will contain date and time.
2406 When nil, only the date will be recorded."
2407 :group 'org-progress
2408 :type 'boolean)
2410 (defcustom org-log-note-headings
2411 '((done . "CLOSING NOTE %t")
2412 (state . "State %-12s from %-12S %t")
2413 (note . "Note taken on %t")
2414 (reschedule . "Rescheduled from %S on %t")
2415 (delschedule . "Not scheduled, was %S on %t")
2416 (redeadline . "New deadline from %S on %t")
2417 (deldeadline . "Removed deadline, was %S on %t")
2418 (refile . "Refiled on %t")
2419 (clock-out . ""))
2420 "Headings for notes added to entries.
2421 The value is an alist, with the car being a symbol indicating the note
2422 context, and the cdr is the heading to be used. The heading may also be the
2423 empty string.
2424 %t in the heading will be replaced by a time stamp.
2425 %T will be an active time stamp instead the default inactive one
2426 %d will be replaced by a short-format time stamp.
2427 %D will be replaced by an active short-format time stamp.
2428 %s will be replaced by the new TODO state, in double quotes.
2429 %S will be replaced by the old TODO state, in double quotes.
2430 %u will be replaced by the user name.
2431 %U will be replaced by the full user name.
2433 In fact, it is not a good idea to change the `state' entry, because
2434 agenda log mode depends on the format of these entries."
2435 :group 'org-todo
2436 :group 'org-progress
2437 :type '(list :greedy t
2438 (cons (const :tag "Heading when closing an item" done) string)
2439 (cons (const :tag
2440 "Heading when changing todo state (todo sequence only)"
2441 state) string)
2442 (cons (const :tag "Heading when just taking a note" note) string)
2443 (cons (const :tag "Heading when clocking out" clock-out) string)
2444 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2445 (cons (const :tag "Heading when rescheduling" reschedule) string)
2446 (cons (const :tag "Heading when changing deadline" redeadline) string)
2447 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2448 (cons (const :tag "Heading when refiling" refile) string)))
2450 (unless (assq 'note org-log-note-headings)
2451 (push '(note . "%t") org-log-note-headings))
2453 (defcustom org-log-into-drawer nil
2454 "Non-nil means insert state change notes and time stamps into a drawer.
2455 When nil, state changes notes will be inserted after the headline and
2456 any scheduling and clock lines, but not inside a drawer.
2458 The value of this variable should be the name of the drawer to use.
2459 LOGBOOK is proposed as the default drawer for this purpose, you can
2460 also set this to a string to define the drawer of your choice.
2462 A value of t is also allowed, representing \"LOGBOOK\".
2464 If this variable is set, `org-log-state-notes-insert-after-drawers'
2465 will be ignored.
2467 You can set the property LOG_INTO_DRAWER to overrule this setting for
2468 a subtree."
2469 :group 'org-todo
2470 :group 'org-progress
2471 :type '(choice
2472 (const :tag "Not into a drawer" nil)
2473 (const :tag "LOGBOOK" t)
2474 (string :tag "Other")))
2476 (if (fboundp 'defvaralias)
2477 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2479 (defun org-log-into-drawer ()
2480 "Return the value of `org-log-into-drawer', but let properties overrule.
2481 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2482 used instead of the default value."
2483 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2484 (cond
2485 ((or (not p) (equal p "nil")) org-log-into-drawer)
2486 ((equal p "t") "LOGBOOK")
2487 (t p))))
2489 (defcustom org-log-state-notes-insert-after-drawers nil
2490 "Non-nil means insert state change notes after any drawers in entry.
2491 Only the drawers that *immediately* follow the headline and the
2492 deadline/scheduled line are skipped.
2493 When nil, insert notes right after the heading and perhaps the line
2494 with deadline/scheduling if present.
2496 This variable will have no effect if `org-log-into-drawer' is
2497 set."
2498 :group 'org-todo
2499 :group 'org-progress
2500 :type 'boolean)
2502 (defcustom org-log-states-order-reversed t
2503 "Non-nil means the latest state note will be directly after heading.
2504 When nil, the state change notes will be ordered according to time."
2505 :group 'org-todo
2506 :group 'org-progress
2507 :type 'boolean)
2509 (defcustom org-todo-repeat-to-state nil
2510 "The TODO state to which a repeater should return the repeating task.
2511 By default this is the first task in a TODO sequence, or the previous state
2512 in a TODO_TYP set. But you can specify another task here.
2513 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2514 :group 'org-todo
2515 :version "24.1"
2516 :type '(choice (const :tag "Head of sequence" nil)
2517 (string :tag "Specific state")))
2519 (defcustom org-log-repeat 'time
2520 "Non-nil means record moving through the DONE state when triggering repeat.
2521 An auto-repeating task is immediately switched back to TODO when
2522 marked DONE. If you are not logging state changes (by adding \"@\"
2523 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2524 record a closing note, there will be no record of the task moving
2525 through DONE. This variable forces taking a note anyway.
2527 nil Don't force a record
2528 time Record a time stamp
2529 note Prompt for a note and add it with template `org-log-note-headings'
2531 This option can also be set with on a per-file-basis with
2533 #+STARTUP: nologrepeat
2534 #+STARTUP: logrepeat
2535 #+STARTUP: lognoterepeat
2537 You can have local logging settings for a subtree by setting the LOGGING
2538 property to one or more of these keywords."
2539 :group 'org-todo
2540 :group 'org-progress
2541 :type '(choice
2542 (const :tag "Don't force a record" nil)
2543 (const :tag "Force recording the DONE state" time)
2544 (const :tag "Force recording a note with the DONE state" note)))
2547 (defgroup org-priorities nil
2548 "Priorities in Org-mode."
2549 :tag "Org Priorities"
2550 :group 'org-todo)
2552 (defcustom org-enable-priority-commands t
2553 "Non-nil means priority commands are active.
2554 When nil, these commands will be disabled, so that you never accidentally
2555 set a priority."
2556 :group 'org-priorities
2557 :type 'boolean)
2559 (defcustom org-highest-priority ?A
2560 "The highest priority of TODO items. A character like ?A, ?B etc.
2561 Must have a smaller ASCII number than `org-lowest-priority'."
2562 :group 'org-priorities
2563 :type 'character)
2565 (defcustom org-lowest-priority ?C
2566 "The lowest priority of TODO items. A character like ?A, ?B etc.
2567 Must have a larger ASCII number than `org-highest-priority'."
2568 :group 'org-priorities
2569 :type 'character)
2571 (defcustom org-default-priority ?B
2572 "The default priority of TODO items.
2573 This is the priority an item gets if no explicit priority is given.
2574 When starting to cycle on an empty priority the first step in the cycle
2575 depends on `org-priority-start-cycle-with-default'. The resulting first
2576 step priority must not exceed the range from `org-highest-priority' to
2577 `org-lowest-priority' which means that `org-default-priority' has to be
2578 in this range exclusive or inclusive the range boundaries. Else the
2579 first step refuses to set the default and the second will fall back
2580 to (depending on the command used) the highest or lowest priority."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-priority-start-cycle-with-default t
2585 "Non-nil means start with default priority when starting to cycle.
2586 When this is nil, the first step in the cycle will be (depending on the
2587 command used) one higher or lower than the default priority.
2588 See also `org-default-priority'."
2589 :group 'org-priorities
2590 :type 'boolean)
2592 (defcustom org-get-priority-function nil
2593 "Function to extract the priority from a string.
2594 The string is normally the headline. If this is nil Org computes the
2595 priority from the priority cookie like [#A] in the headline. It returns
2596 an integer, increasing by 1000 for each priority level.
2597 The user can set a different function here, which should take a string
2598 as an argument and return the numeric priority."
2599 :group 'org-priorities
2600 :version "24.1"
2601 :type 'function)
2603 (defgroup org-time nil
2604 "Options concerning time stamps and deadlines in Org-mode."
2605 :tag "Org Time"
2606 :group 'org)
2608 (defcustom org-insert-labeled-timestamps-at-point nil
2609 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2610 When nil, these labeled time stamps are forces into the second line of an
2611 entry, just after the headline. When scheduling from the global TODO list,
2612 the time stamp will always be forced into the second line."
2613 :group 'org-time
2614 :type 'boolean)
2616 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2617 "Formats for `format-time-string' which are used for time stamps.
2618 It is not recommended to change this constant.")
2620 (defcustom org-time-stamp-rounding-minutes '(0 5)
2621 "Number of minutes to round time stamps to.
2622 These are two values, the first applies when first creating a time stamp.
2623 The second applies when changing it with the commands `S-up' and `S-down'.
2624 When changing the time stamp, this means that it will change in steps
2625 of N minutes, as given by the second value.
2627 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2628 numbers should be factors of 60, so for example 5, 10, 15.
2630 When this is larger than 1, you can still force an exact time stamp by using
2631 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2632 and by using a prefix arg to `S-up/down' to specify the exact number
2633 of minutes to shift."
2634 :group 'org-time
2635 :get #'(lambda (var) ; Make sure both elements are there
2636 (if (integerp (default-value var))
2637 (list (default-value var) 5)
2638 (default-value var)))
2639 :type '(list
2640 (integer :tag "when inserting times")
2641 (integer :tag "when modifying times")))
2643 ;; Normalize old customizations of this variable.
2644 (when (integerp org-time-stamp-rounding-minutes)
2645 (setq org-time-stamp-rounding-minutes
2646 (list org-time-stamp-rounding-minutes
2647 org-time-stamp-rounding-minutes)))
2649 (defcustom org-display-custom-times nil
2650 "Non-nil means overlay custom formats over all time stamps.
2651 The formats are defined through the variable `org-time-stamp-custom-formats'.
2652 To turn this on on a per-file basis, insert anywhere in the file:
2653 #+STARTUP: customtime"
2654 :group 'org-time
2655 :set 'set-default
2656 :type 'sexp)
2657 (make-variable-buffer-local 'org-display-custom-times)
2659 (defcustom org-time-stamp-custom-formats
2660 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2661 "Custom formats for time stamps. See `format-time-string' for the syntax.
2662 These are overlaid over the default ISO format if the variable
2663 `org-display-custom-times' is set. Time like %H:%M should be at the
2664 end of the second format. The custom formats are also honored by export
2665 commands, if custom time display is turned on at the time of export."
2666 :group 'org-time
2667 :type 'sexp)
2669 (defun org-time-stamp-format (&optional long inactive)
2670 "Get the right format for a time string."
2671 (let ((f (if long (cdr org-time-stamp-formats)
2672 (car org-time-stamp-formats))))
2673 (if inactive
2674 (concat "[" (substring f 1 -1) "]")
2675 f)))
2677 (defcustom org-time-clocksum-format "%d:%02d"
2678 "The format string used when creating CLOCKSUM lines.
2679 This is also used when org-mode generates a time duration."
2680 :group 'org-time
2681 :type 'string)
2683 (defcustom org-time-clocksum-use-fractional nil
2684 "If non-nil, \\[org-clock-display] uses fractional times.
2685 org-mode generates a time duration."
2686 :group 'org-time
2687 :type 'boolean)
2689 (defcustom org-time-clocksum-fractional-format "%.2f"
2690 "The format string used when creating CLOCKSUM lines, or when
2691 org-mode generates a time duration."
2692 :group 'org-time
2693 :type 'string)
2695 (defcustom org-deadline-warning-days 14
2696 "No. of days before expiration during which a deadline becomes active.
2697 This variable governs the display in sparse trees and in the agenda.
2698 When 0 or negative, it means use this number (the absolute value of it)
2699 even if a deadline has a different individual lead time specified.
2701 Custom commands can set this variable in the options section."
2702 :group 'org-time
2703 :group 'org-agenda-daily/weekly
2704 :type 'integer)
2706 (defcustom org-read-date-prefer-future t
2707 "Non-nil means assume future for incomplete date input from user.
2708 This affects the following situations:
2709 1. The user gives a month but not a year.
2710 For example, if it is April and you enter \"feb 2\", this will be read
2711 as Feb 2, *next* year. \"May 5\", however, will be this year.
2712 2. The user gives a day, but no month.
2713 For example, if today is the 15th, and you enter \"3\", Org-mode will
2714 read this as the third of *next* month. However, if you enter \"17\",
2715 it will be considered as *this* month.
2717 If you set this variable to the symbol `time', then also the following
2718 will work:
2720 3. If the user gives a time.
2721 If the time is before now, it will be interpreted as tomorrow.
2723 Currently none of this works for ISO week specifications.
2725 When this option is nil, the current day, month and year will always be
2726 used as defaults.
2728 See also `org-agenda-jump-prefer-future'."
2729 :group 'org-time
2730 :type '(choice
2731 (const :tag "Never" nil)
2732 (const :tag "Check month and day" t)
2733 (const :tag "Check month, day, and time" time)))
2735 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2736 "Should the agenda jump command prefer the future for incomplete dates?
2737 The default is to do the same as configured in `org-read-date-prefer-future'.
2738 But you can also set a deviating value here.
2739 This may t or nil, or the symbol `org-read-date-prefer-future'."
2740 :group 'org-agenda
2741 :group 'org-time
2742 :version "24.1"
2743 :type '(choice
2744 (const :tag "Use org-read-date-prefer-future"
2745 org-read-date-prefer-future)
2746 (const :tag "Never" nil)
2747 (const :tag "Always" t)))
2749 (defcustom org-read-date-force-compatible-dates t
2750 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2752 Depending on the system Emacs is running on, certain dates cannot
2753 be represented with the type used internally to represent time.
2754 Dates between 1970-1-1 and 2038-1-1 can always be represented
2755 correctly. Some systems allow for earlier dates, some for later,
2756 some for both. One way to find out it to insert any date into an
2757 Org buffer, putting the cursor on the year and hitting S-up and
2758 S-down to test the range.
2760 When this variable is set to t, the date/time prompt will not let
2761 you specify dates outside the 1970-2037 range, so it is certain that
2762 these dates will work in whatever version of Emacs you are
2763 running, and also that you can move a file from one Emacs implementation
2764 to another. WHenever Org is forcing the year for you, it will display
2765 a message and beep.
2767 When this variable is nil, Org will check if the date is
2768 representable in the specific Emacs implementation you are using.
2769 If not, it will force a year, usually the current year, and beep
2770 to remind you. Currently this setting is not recommended because
2771 the likelihood that you will open your Org files in an Emacs that
2772 has limited date range is not negligible.
2774 A workaround for this problem is to use diary sexp dates for time
2775 stamps outside of this range."
2776 :group 'org-time
2777 :version "24.1"
2778 :type 'boolean)
2780 (defcustom org-read-date-display-live t
2781 "Non-nil means display current interpretation of date prompt live.
2782 This display will be in an overlay, in the minibuffer."
2783 :group 'org-time
2784 :type 'boolean)
2786 (defcustom org-read-date-popup-calendar t
2787 "Non-nil means pop up a calendar when prompting for a date.
2788 In the calendar, the date can be selected with mouse-1. However, the
2789 minibuffer will also be active, and you can simply enter the date as well.
2790 When nil, only the minibuffer will be available."
2791 :group 'org-time
2792 :type 'boolean)
2793 (if (fboundp 'defvaralias)
2794 (defvaralias 'org-popup-calendar-for-date-prompt
2795 'org-read-date-popup-calendar))
2797 (defcustom org-read-date-minibuffer-setup-hook nil
2798 "Hook to be used to set up keys for the date/time interface.
2799 Add key definitions to `minibuffer-local-map', which will be a temporary
2800 copy."
2801 :group 'org-time
2802 :type 'hook)
2804 (defcustom org-extend-today-until 0
2805 "The hour when your day really ends. Must be an integer.
2806 This has influence for the following applications:
2807 - When switching the agenda to \"today\". It it is still earlier than
2808 the time given here, the day recognized as TODAY is actually yesterday.
2809 - When a date is read from the user and it is still before the time given
2810 here, the current date and time will be assumed to be yesterday, 23:59.
2811 Also, timestamps inserted in capture templates follow this rule.
2813 IMPORTANT: This is a feature whose implementation is and likely will
2814 remain incomplete. Really, it is only here because past midnight seems to
2815 be the favorite working time of John Wiegley :-)"
2816 :group 'org-time
2817 :type 'integer)
2819 (defcustom org-use-effective-time nil
2820 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2821 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2822 \"effective time\" of any timestamps between midnight and 8am will be
2823 23:59 of the previous day."
2824 :group 'org-time
2825 :version "24.1"
2826 :type 'boolean)
2828 (defcustom org-edit-timestamp-down-means-later nil
2829 "Non-nil means S-down will increase the time in a time stamp.
2830 When nil, S-up will increase."
2831 :group 'org-time
2832 :type 'boolean)
2834 (defcustom org-calendar-follow-timestamp-change t
2835 "Non-nil means make the calendar window follow timestamp changes.
2836 When a timestamp is modified and the calendar window is visible, it will be
2837 moved to the new date."
2838 :group 'org-time
2839 :type 'boolean)
2841 (defgroup org-tags nil
2842 "Options concerning tags in Org-mode."
2843 :tag "Org Tags"
2844 :group 'org)
2846 (defcustom org-tag-alist nil
2847 "List of tags allowed in Org-mode files.
2848 When this list is nil, Org-mode will base TAG input on what is already in the
2849 buffer.
2850 The value of this variable is an alist, the car of each entry must be a
2851 keyword as a string, the cdr may be a character that is used to select
2852 that tag through the fast-tag-selection interface.
2853 See the manual for details."
2854 :group 'org-tags
2855 :type '(repeat
2856 (choice
2857 (cons (string :tag "Tag name")
2858 (character :tag "Access char"))
2859 (list :tag "Start radio group"
2860 (const :startgroup)
2861 (option (string :tag "Group description")))
2862 (list :tag "End radio group"
2863 (const :endgroup)
2864 (option (string :tag "Group description")))
2865 (const :tag "New line" (:newline)))))
2867 (defcustom org-tag-persistent-alist nil
2868 "List of tags that will always appear in all Org-mode files.
2869 This is in addition to any in buffer settings or customizations
2870 of `org-tag-alist'.
2871 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2872 The value of this variable is an alist, the car of each entry must be a
2873 keyword as a string, the cdr may be a character that is used to select
2874 that tag through the fast-tag-selection interface.
2875 See the manual for details.
2876 To disable these tags on a per-file basis, insert anywhere in the file:
2877 #+STARTUP: noptag"
2878 :group 'org-tags
2879 :type '(repeat
2880 (choice
2881 (cons (string :tag "Tag name")
2882 (character :tag "Access char"))
2883 (const :tag "Start radio group" (:startgroup))
2884 (const :tag "End radio group" (:endgroup))
2885 (const :tag "New line" (:newline)))))
2887 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2888 "If non-nil, always offer completion for all tags of all agenda files.
2889 Instead of customizing this variable directly, you might want to
2890 set it locally for capture buffers, because there no list of
2891 tags in that file can be created dynamically (there are none).
2893 (add-hook 'org-capture-mode-hook
2894 (lambda ()
2895 (set (make-local-variable
2896 'org-complete-tags-always-offer-all-agenda-tags)
2897 t)))"
2898 :group 'org-tags
2899 :version "24.1"
2900 :type 'boolean)
2902 (defvar org-file-tags nil
2903 "List of tags that can be inherited by all entries in the file.
2904 The tags will be inherited if the variable `org-use-tag-inheritance'
2905 says they should be.
2906 This variable is populated from #+FILETAGS lines.")
2908 (defcustom org-use-fast-tag-selection 'auto
2909 "Non-nil means use fast tag selection scheme.
2910 This is a special interface to select and deselect tags with single keys.
2911 When nil, fast selection is never used.
2912 When the symbol `auto', fast selection is used if and only if selection
2913 characters for tags have been configured, either through the variable
2914 `org-tag-alist' or through a #+TAGS line in the buffer.
2915 When t, fast selection is always used and selection keys are assigned
2916 automatically if necessary."
2917 :group 'org-tags
2918 :type '(choice
2919 (const :tag "Always" t)
2920 (const :tag "Never" nil)
2921 (const :tag "When selection characters are configured" 'auto)))
2923 (defcustom org-fast-tag-selection-single-key nil
2924 "Non-nil means fast tag selection exits after first change.
2925 When nil, you have to press RET to exit it.
2926 During fast tag selection, you can toggle this flag with `C-c'.
2927 This variable can also have the value `expert'. In this case, the window
2928 displaying the tags menu is not even shown, until you press C-c again."
2929 :group 'org-tags
2930 :type '(choice
2931 (const :tag "No" nil)
2932 (const :tag "Yes" t)
2933 (const :tag "Expert" expert)))
2935 (defvar org-fast-tag-selection-include-todo nil
2936 "Non-nil means fast tags selection interface will also offer TODO states.
2937 This is an undocumented feature, you should not rely on it.")
2939 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2940 "The column to which tags should be indented in a headline.
2941 If this number is positive, it specifies the column. If it is negative,
2942 it means that the tags should be flushright to that column. For example,
2943 -80 works well for a normal 80 character screen.
2944 When 0, place tags directly after headline text, with only one space in
2945 between."
2946 :group 'org-tags
2947 :type 'integer)
2949 (defcustom org-auto-align-tags t
2950 "Non-nil keeps tags aligned when modifying headlines.
2951 Some operations (i.e. demoting) change the length of a headline and
2952 therefore shift the tags around. With this option turned on, after
2953 each such operation the tags are again aligned to `org-tags-column'."
2954 :group 'org-tags
2955 :type 'boolean)
2957 (defcustom org-use-tag-inheritance t
2958 "Non-nil means tags in levels apply also for sublevels.
2959 When nil, only the tags directly given in a specific line apply there.
2960 This may also be a list of tags that should be inherited, or a regexp that
2961 matches tags that should be inherited. Additional control is possible
2962 with the variable `org-tags-exclude-from-inheritance' which gives an
2963 explicit list of tags to be excluded from inheritance., even if the value of
2964 `org-use-tag-inheritance' would select it for inheritance.
2966 If this option is t, a match early-on in a tree can lead to a large
2967 number of matches in the subtree when constructing the agenda or creating
2968 a sparse tree. If you only want to see the first match in a tree during
2969 a search, check out the variable `org-tags-match-list-sublevels'."
2970 :group 'org-tags
2971 :type '(choice
2972 (const :tag "Not" nil)
2973 (const :tag "Always" t)
2974 (repeat :tag "Specific tags" (string :tag "Tag"))
2975 (regexp :tag "Tags matched by regexp")))
2977 (defcustom org-tags-exclude-from-inheritance nil
2978 "List of tags that should never be inherited.
2979 This is a way to exclude a few tags from inheritance. For way to do
2980 the opposite, to actively allow inheritance for selected tags,
2981 see the variable `org-use-tag-inheritance'."
2982 :group 'org-tags
2983 :type '(repeat (string :tag "Tag")))
2985 (defun org-tag-inherit-p (tag)
2986 "Check if TAG is one that should be inherited."
2987 (cond
2988 ((member tag org-tags-exclude-from-inheritance) nil)
2989 ((eq org-use-tag-inheritance t) t)
2990 ((not org-use-tag-inheritance) nil)
2991 ((stringp org-use-tag-inheritance)
2992 (string-match org-use-tag-inheritance tag))
2993 ((listp org-use-tag-inheritance)
2994 (member tag org-use-tag-inheritance))
2995 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2997 (defcustom org-tags-match-list-sublevels t
2998 "Non-nil means list also sublevels of headlines matching a search.
2999 This variable applies to tags/property searches, and also to stuck
3000 projects because this search is based on a tags match as well.
3002 When set to the symbol `indented', sublevels are indented with
3003 leading dots.
3005 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3006 the sublevels of a headline matching a tag search often also match
3007 the same search. Listing all of them can create very long lists.
3008 Setting this variable to nil causes subtrees of a match to be skipped.
3010 This variable is semi-obsolete and probably should always be true. It
3011 is better to limit inheritance to certain tags using the variables
3012 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3013 :group 'org-tags
3014 :type '(choice
3015 (const :tag "No, don't list them" nil)
3016 (const :tag "Yes, do list them" t)
3017 (const :tag "List them, indented with leading dots" indented)))
3019 (defcustom org-tags-sort-function nil
3020 "When set, tags are sorted using this function as a comparator."
3021 :group 'org-tags
3022 :type '(choice
3023 (const :tag "No sorting" nil)
3024 (const :tag "Alphabetical" string<)
3025 (const :tag "Reverse alphabetical" string>)
3026 (function :tag "Custom function" nil)))
3028 (defvar org-tags-history nil
3029 "History of minibuffer reads for tags.")
3030 (defvar org-last-tags-completion-table nil
3031 "The last used completion table for tags.")
3032 (defvar org-after-tags-change-hook nil
3033 "Hook that is run after the tags in a line have changed.")
3035 (defgroup org-properties nil
3036 "Options concerning properties in Org-mode."
3037 :tag "Org Properties"
3038 :group 'org)
3040 (defcustom org-property-format "%-10s %s"
3041 "How property key/value pairs should be formatted by `indent-line'.
3042 When `indent-line' hits a property definition, it will format the line
3043 according to this format, mainly to make sure that the values are
3044 lined-up with respect to each other."
3045 :group 'org-properties
3046 :type 'string)
3048 (defcustom org-properties-postprocess-alist nil
3049 "Alist of properties and functions to adjust inserted values.
3050 Elements of this alist must be of the form
3052 ([string] [function])
3054 where [string] must be a property name and [function] must be a
3055 lambda expression: this lambda expression must take one argument,
3056 the value to adjust, and return the new value as a string.
3058 For example, this element will allow the property \"Remaining\"
3059 to be updated wrt the relation between the \"Effort\" property
3060 and the clock summary:
3062 ((\"Remaining\" (lambda(value)
3063 (let ((clocksum (org-clock-sum-current-item))
3064 (effort (org-duration-string-to-minutes
3065 (org-entry-get (point) \"Effort\"))))
3066 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3067 :group 'org-properties
3068 :version "24.1"
3069 :type '(alist :key-type (string :tag "Property")
3070 :value-type (function :tag "Function")))
3072 (defcustom org-use-property-inheritance nil
3073 "Non-nil means properties apply also for sublevels.
3075 This setting is chiefly used during property searches. Turning it on can
3076 cause significant overhead when doing a search, which is why it is not
3077 on by default.
3079 When nil, only the properties directly given in the current entry count.
3080 When t, every property is inherited. The value may also be a list of
3081 properties that should have inheritance, or a regular expression matching
3082 properties that should be inherited.
3084 However, note that some special properties use inheritance under special
3085 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3086 and the properties ending in \"_ALL\" when they are used as descriptor
3087 for valid values of a property.
3089 Note for programmers:
3090 When querying an entry with `org-entry-get', you can control if inheritance
3091 should be used. By default, `org-entry-get' looks only at the local
3092 properties. You can request inheritance by setting the inherit argument
3093 to t (to force inheritance) or to `selective' (to respect the setting
3094 in this variable)."
3095 :group 'org-properties
3096 :type '(choice
3097 (const :tag "Not" nil)
3098 (const :tag "Always" t)
3099 (repeat :tag "Specific properties" (string :tag "Property"))
3100 (regexp :tag "Properties matched by regexp")))
3102 (defun org-property-inherit-p (property)
3103 "Check if PROPERTY is one that should be inherited."
3104 (cond
3105 ((eq org-use-property-inheritance t) t)
3106 ((not org-use-property-inheritance) nil)
3107 ((stringp org-use-property-inheritance)
3108 (string-match org-use-property-inheritance property))
3109 ((listp org-use-property-inheritance)
3110 (member property org-use-property-inheritance))
3111 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3113 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3114 "The default column format, if no other format has been defined.
3115 This variable can be set on the per-file basis by inserting a line
3117 #+COLUMNS: %25ITEM ....."
3118 :group 'org-properties
3119 :type 'string)
3121 (defcustom org-columns-ellipses ".."
3122 "The ellipses to be used when a field in column view is truncated.
3123 When this is the empty string, as many characters as possible are shown,
3124 but then there will be no visual indication that the field has been truncated.
3125 When this is a string of length N, the last N characters of a truncated
3126 field are replaced by this string. If the column is narrower than the
3127 ellipses string, only part of the ellipses string will be shown."
3128 :group 'org-properties
3129 :type 'string)
3131 (defcustom org-columns-modify-value-for-display-function nil
3132 "Function that modifies values for display in column view.
3133 For example, it can be used to cut out a certain part from a time stamp.
3134 The function must take 2 arguments:
3136 column-title The title of the column (*not* the property name)
3137 value The value that should be modified.
3139 The function should return the value that should be displayed,
3140 or nil if the normal value should be used."
3141 :group 'org-properties
3142 :type 'function)
3144 (defcustom org-effort-property "Effort"
3145 "The property that is being used to keep track of effort estimates.
3146 Effort estimates given in this property need to have the format H:MM."
3147 :group 'org-properties
3148 :group 'org-progress
3149 :type '(string :tag "Property"))
3151 (defconst org-global-properties-fixed
3152 '(("VISIBILITY_ALL" . "folded children content all")
3153 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3154 "List of property/value pairs that can be inherited by any entry.
3156 These are fixed values, for the preset properties. The user variable
3157 that can be used to add to this list is `org-global-properties'.
3159 The entries in this list are cons cells where the car is a property
3160 name and cdr is a string with the value. If the value represents
3161 multiple items like an \"_ALL\" property, separate the items by
3162 spaces.")
3164 (defcustom org-global-properties nil
3165 "List of property/value pairs that can be inherited by any entry.
3167 This list will be combined with the constant `org-global-properties-fixed'.
3169 The entries in this list are cons cells where the car is a property
3170 name and cdr is a string with the value.
3172 You can set buffer-local values for the same purpose in the variable
3173 `org-file-properties' this by adding lines like
3175 #+PROPERTY: NAME VALUE"
3176 :group 'org-properties
3177 :type '(repeat
3178 (cons (string :tag "Property")
3179 (string :tag "Value"))))
3181 (defvar org-file-properties nil
3182 "List of property/value pairs that can be inherited by any entry.
3183 Valid for the current buffer.
3184 This variable is populated from #+PROPERTY lines.")
3185 (make-variable-buffer-local 'org-file-properties)
3187 (defgroup org-agenda nil
3188 "Options concerning agenda views in Org-mode."
3189 :tag "Org Agenda"
3190 :group 'org)
3192 (defvar org-category nil
3193 "Variable used by org files to set a category for agenda display.
3194 Such files should use a file variable to set it, for example
3196 # -*- mode: org; org-category: \"ELisp\"
3198 or contain a special line
3200 #+CATEGORY: ELisp
3202 If the file does not specify a category, then file's base name
3203 is used instead.")
3204 (make-variable-buffer-local 'org-category)
3205 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3207 (defcustom org-agenda-files nil
3208 "The files to be used for agenda display.
3209 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3210 \\[org-remove-file]. You can also use customize to edit the list.
3212 If an entry is a directory, all files in that directory that are matched by
3213 `org-agenda-file-regexp' will be part of the file list.
3215 If the value of the variable is not a list but a single file name, then
3216 the list of agenda files is actually stored and maintained in that file, one
3217 agenda file per line. In this file paths can be given relative to
3218 `org-directory'. Tilde expansion and environment variable substitution
3219 are also made."
3220 :group 'org-agenda
3221 :type '(choice
3222 (repeat :tag "List of files and directories" file)
3223 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3225 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3226 "Regular expression to match files for `org-agenda-files'.
3227 If any element in the list in that variable contains a directory instead
3228 of a normal file, all files in that directory that are matched by this
3229 regular expression will be included."
3230 :group 'org-agenda
3231 :type 'regexp)
3233 (defcustom org-agenda-text-search-extra-files nil
3234 "List of extra files to be searched by text search commands.
3235 These files will be search in addition to the agenda files by the
3236 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3237 Note that these files will only be searched for text search commands,
3238 not for the other agenda views like todo lists, tag searches or the weekly
3239 agenda. This variable is intended to list notes and possibly archive files
3240 that should also be searched by these two commands.
3241 In fact, if the first element in the list is the symbol `agenda-archives',
3242 than all archive files of all agenda files will be added to the search
3243 scope."
3244 :group 'org-agenda
3245 :type '(set :greedy t
3246 (const :tag "Agenda Archives" agenda-archives)
3247 (repeat :inline t (file))))
3249 (if (fboundp 'defvaralias)
3250 (defvaralias 'org-agenda-multi-occur-extra-files
3251 'org-agenda-text-search-extra-files))
3253 (defcustom org-agenda-skip-unavailable-files nil
3254 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3255 A nil value means to remove them, after a query, from the list."
3256 :group 'org-agenda
3257 :type 'boolean)
3259 (defcustom org-calendar-to-agenda-key [?c]
3260 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3261 The command `org-calendar-goto-agenda' will be bound to this key. The
3262 default is the character `c' because then `c' can be used to switch back and
3263 forth between agenda and calendar."
3264 :group 'org-agenda
3265 :type 'sexp)
3267 (defcustom org-calendar-insert-diary-entry-key [?i]
3268 "The key to be installed in `calendar-mode-map' for adding diary entries.
3269 This option is irrelevant until `org-agenda-diary-file' has been configured
3270 to point to an Org-mode file. When that is the case, the command
3271 `org-agenda-diary-entry' will be bound to the key given here, by default
3272 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3273 if you want to continue doing this, you need to change this to a different
3274 key."
3275 :group 'org-agenda
3276 :type 'sexp)
3278 (defcustom org-agenda-diary-file 'diary-file
3279 "File to which to add new entries with the `i' key in agenda and calendar.
3280 When this is the symbol `diary-file', the functionality in the Emacs
3281 calendar will be used to add entries to the `diary-file'. But when this
3282 points to a file, `org-agenda-diary-entry' will be used instead."
3283 :group 'org-agenda
3284 :type '(choice
3285 (const :tag "The standard Emacs diary file" diary-file)
3286 (file :tag "Special Org file diary entries")))
3288 (eval-after-load "calendar"
3289 '(progn
3290 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3291 'org-calendar-goto-agenda)
3292 (add-hook 'calendar-mode-hook
3293 (lambda ()
3294 (unless (eq org-agenda-diary-file 'diary-file)
3295 (define-key calendar-mode-map
3296 org-calendar-insert-diary-entry-key
3297 'org-agenda-diary-entry))))))
3299 (defgroup org-latex nil
3300 "Options for embedding LaTeX code into Org-mode."
3301 :tag "Org LaTeX"
3302 :group 'org)
3304 (defcustom org-format-latex-options
3305 '(:foreground default :background default :scale 1.0
3306 :html-foreground "Black" :html-background "Transparent"
3307 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3308 "Options for creating images from LaTeX fragments.
3309 This is a property list with the following properties:
3310 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3311 `default' means use the foreground of the default face.
3312 :background the background color, or \"Transparent\".
3313 `default' means use the background of the default face.
3314 :scale a scaling factor for the size of the images, to get more pixels
3315 :html-foreground, :html-background, :html-scale
3316 the same numbers for HTML export.
3317 :matchers a list indicating which matchers should be used to
3318 find LaTeX fragments. Valid members of this list are:
3319 \"begin\" find environments
3320 \"$1\" find single characters surrounded by $.$
3321 \"$\" find math expressions surrounded by $...$
3322 \"$$\" find math expressions surrounded by $$....$$
3323 \"\\(\" find math expressions surrounded by \\(...\\)
3324 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3325 :group 'org-latex
3326 :type 'plist)
3328 (defcustom org-format-latex-signal-error t
3329 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3330 When nil, just push out a message."
3331 :group 'org-latex
3332 :version "24.1"
3333 :type 'boolean)
3335 (defcustom org-latex-to-mathml-jar-file nil
3336 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3337 Use this to specify additional executable file say a jar file.
3339 When using MathToWeb as the converter, specify the full-path to
3340 your mathtoweb.jar file."
3341 :group 'org-latex
3342 :version "24.1"
3343 :type '(choice
3344 (const :tag "None" nil)
3345 (file :tag "JAR file" :must-match t)))
3347 (defcustom org-latex-to-mathml-convert-command nil
3348 "Command to convert LaTeX fragments to MathML.
3349 Replace format-specifiers in the command as noted below and use
3350 `shell-command' to convert LaTeX to MathML.
3351 %j: Executable file in fully expanded form as specified by
3352 `org-latex-to-mathml-jar-file'.
3353 %I: Input LaTeX file in fully expanded form
3354 %o: Output MathML file
3355 This command is used by `org-create-math-formula'.
3357 When using MathToWeb as the converter, set this to
3358 \"java -jar %j -unicode -force -df %o %I\"."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type '(choice
3362 (const :tag "None" nil)
3363 (string :tag "\nShell command")))
3365 (defcustom org-latex-create-formula-image-program 'dvipng
3366 "Program to convert LaTeX fragments with.
3368 dvipng Process the LaTeX fragments to dvi file, then convert
3369 dvi files to png files using dvipng.
3370 This will also include processing of non-math environments.
3371 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3372 to convert pdf files to png files"
3373 :group 'org-latex
3374 :version "24.1"
3375 :type '(choice
3376 (const :tag "dvipng" dvipng)
3377 (const :tag "imagemagick" imagemagick)))
3379 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3380 "Path to store latex preview images. A relative path here creates many
3381 directories relative to the processed org files paths. An absolute path
3382 puts all preview images at the same place."
3383 :group 'org-latex
3384 :version "24.3"
3385 :type 'string)
3387 (defun org-format-latex-mathml-available-p ()
3388 "Return t if `org-latex-to-mathml-convert-command' is usable."
3389 (save-match-data
3390 (when (and (boundp 'org-latex-to-mathml-convert-command)
3391 org-latex-to-mathml-convert-command)
3392 (let ((executable (car (split-string
3393 org-latex-to-mathml-convert-command))))
3394 (when (executable-find executable)
3395 (if (string-match
3396 "%j" org-latex-to-mathml-convert-command)
3397 (file-readable-p org-latex-to-mathml-jar-file)
3398 t))))))
3400 (defcustom org-format-latex-header "\\documentclass{article}
3401 \\usepackage[usenames]{color}
3402 \\usepackage{amsmath}
3403 \\usepackage[mathscr]{eucal}
3404 \\pagestyle{empty} % do not remove
3405 \[PACKAGES]
3406 \[DEFAULT-PACKAGES]
3407 % The settings below are copied from fullpage.sty
3408 \\setlength{\\textwidth}{\\paperwidth}
3409 \\addtolength{\\textwidth}{-3cm}
3410 \\setlength{\\oddsidemargin}{1.5cm}
3411 \\addtolength{\\oddsidemargin}{-2.54cm}
3412 \\setlength{\\evensidemargin}{\\oddsidemargin}
3413 \\setlength{\\textheight}{\\paperheight}
3414 \\addtolength{\\textheight}{-\\headheight}
3415 \\addtolength{\\textheight}{-\\headsep}
3416 \\addtolength{\\textheight}{-\\footskip}
3417 \\addtolength{\\textheight}{-3cm}
3418 \\setlength{\\topmargin}{1.5cm}
3419 \\addtolength{\\topmargin}{-2.54cm}"
3420 "The document header used for processing LaTeX fragments.
3421 It is imperative that this header make sure that no page number
3422 appears on the page. The package defined in the variables
3423 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3424 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3425 will be appended."
3426 :group 'org-latex
3427 :type 'string)
3429 (defvar org-format-latex-header-extra nil)
3431 (defun org-set-packages-alist (var val)
3432 "Set the packages alist and make sure it has 3 elements per entry."
3433 (set var (mapcar (lambda (x)
3434 (if (and (consp x) (= (length x) 2))
3435 (list (car x) (nth 1 x) t)
3437 val)))
3439 (defun org-get-packages-alist (var)
3441 "Get the packages alist and make sure it has 3 elements per entry."
3442 (mapcar (lambda (x)
3443 (if (and (consp x) (= (length x) 2))
3444 (list (car x) (nth 1 x) t)
3446 (default-value var)))
3448 ;; The following variables are defined here because is it also used
3449 ;; when formatting latex fragments. Originally it was part of the
3450 ;; LaTeX exporter, which is why the name includes "export".
3451 (defcustom org-export-latex-default-packages-alist
3452 '(("AUTO" "inputenc" t)
3453 ("T1" "fontenc" t)
3454 ("" "fixltx2e" nil)
3455 ("" "graphicx" t)
3456 ("" "longtable" nil)
3457 ("" "float" nil)
3458 ("" "wrapfig" nil)
3459 ("" "soul" t)
3460 ("" "textcomp" t)
3461 ("" "marvosym" t)
3462 ("" "wasysym" t)
3463 ("" "latexsym" t)
3464 ("" "amssymb" t)
3465 ("" "hyperref" nil)
3466 "\\tolerance=1000"
3468 "Alist of default packages to be inserted in the header.
3469 Change this only if one of the packages here causes an incompatibility
3470 with another package you are using.
3471 The packages in this list are needed by one part or another of Org-mode
3472 to function properly.
3474 - inputenc, fontenc: for basic font and character selection
3475 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3476 for interpreting the entities in `org-entities'. You can skip some of these
3477 packages if you don't use any of the symbols in it.
3478 - graphicx: for including images
3479 - float, wrapfig: for figure placement
3480 - longtable: for long tables
3481 - hyperref: for cross references
3483 Therefore you should not modify this variable unless you know what you
3484 are doing. The one reason to change it anyway is that you might be loading
3485 some other package that conflicts with one of the default packages.
3486 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3487 If SNIPPET-FLAG is t, the package also needs to be included when
3488 compiling LaTeX snippets into images for inclusion into HTML."
3489 :group 'org-export-latex
3490 :set 'org-set-packages-alist
3491 :get 'org-get-packages-alist
3492 :version "24.1"
3493 :type '(repeat
3494 (choice
3495 (list :tag "options/package pair"
3496 (string :tag "options")
3497 (string :tag "package")
3498 (boolean :tag "Snippet"))
3499 (string :tag "A line of LaTeX"))))
3501 (defcustom org-export-latex-packages-alist nil
3502 "Alist of packages to be inserted in every LaTeX header.
3503 These will be inserted after `org-export-latex-default-packages-alist'.
3504 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3505 SNIPPET-FLAG, when t, indicates that this package is also needed when
3506 turning LaTeX snippets into images for inclusion into HTML.
3507 Make sure that you only list packages here which:
3508 - you want in every file
3509 - do not conflict with the default packages in
3510 `org-export-latex-default-packages-alist'
3511 - do not conflict with the setup in `org-format-latex-header'."
3512 :group 'org-export-latex
3513 :set 'org-set-packages-alist
3514 :get 'org-get-packages-alist
3515 :type '(repeat
3516 (choice
3517 (list :tag "options/package pair"
3518 (string :tag "options")
3519 (string :tag "package")
3520 (boolean :tag "Snippet"))
3521 (string :tag "A line of LaTeX"))))
3524 (defgroup org-appearance nil
3525 "Settings for Org-mode appearance."
3526 :tag "Org Appearance"
3527 :group 'org)
3529 (defcustom org-level-color-stars-only nil
3530 "Non-nil means fontify only the stars in each headline.
3531 When nil, the entire headline is fontified.
3532 Changing it requires restart of `font-lock-mode' to become effective
3533 also in regions already fontified."
3534 :group 'org-appearance
3535 :type 'boolean)
3537 (defcustom org-hide-leading-stars nil
3538 "Non-nil means hide the first N-1 stars in a headline.
3539 This works by using the face `org-hide' for these stars. This
3540 face is white for a light background, and black for a dark
3541 background. You may have to customize the face `org-hide' to
3542 make this work.
3543 Changing it requires restart of `font-lock-mode' to become effective
3544 also in regions already fontified.
3545 You may also set this on a per-file basis by adding one of the following
3546 lines to the buffer:
3548 #+STARTUP: hidestars
3549 #+STARTUP: showstars"
3550 :group 'org-appearance
3551 :type 'boolean)
3553 (defcustom org-hidden-keywords nil
3554 "List of symbols corresponding to keywords to be hidden the org buffer.
3555 For example, a value '(title) for this list will make the document's title
3556 appear in the buffer without the initial #+TITLE: keyword."
3557 :group 'org-appearance
3558 :version "24.1"
3559 :type '(set (const :tag "#+AUTHOR" author)
3560 (const :tag "#+DATE" date)
3561 (const :tag "#+EMAIL" email)
3562 (const :tag "#+TITLE" title)))
3564 (defcustom org-custom-properties nil
3565 "List of properties (as strings) with a special meaning.
3566 The default use of these custom properties is to let the user
3567 hide them with `org-toggle-custom-properties-visibility'."
3568 :group 'org-properties
3569 :group 'org-appearance
3570 :version "24.3"
3571 :type '(repeat (string :tag "Property Name")))
3573 (defcustom org-fontify-done-headline nil
3574 "Non-nil means change the face of a headline if it is marked DONE.
3575 Normally, only the TODO/DONE keyword indicates the state of a headline.
3576 When this is non-nil, the headline after the keyword is set to the
3577 `org-headline-done' as an additional indication."
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-fontify-emphasized-text t
3582 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3583 Changing this variable requires a restart of Emacs to take effect."
3584 :group 'org-appearance
3585 :type 'boolean)
3587 (defcustom org-fontify-whole-heading-line nil
3588 "Non-nil means fontify the whole line for headings.
3589 This is useful when setting a background color for the
3590 org-level-* faces."
3591 :group 'org-appearance
3592 :type 'boolean)
3594 (defcustom org-highlight-latex-fragments-and-specials nil
3595 "Non-nil means fontify what is treated specially by the exporters."
3596 :group 'org-appearance
3597 :type 'boolean)
3599 (defcustom org-hide-emphasis-markers nil
3600 "Non-nil mean font-lock should hide the emphasis marker characters."
3601 :group 'org-appearance
3602 :type 'boolean)
3604 (defcustom org-pretty-entities nil
3605 "Non-nil means show entities as UTF8 characters.
3606 When nil, the \\name form remains in the buffer."
3607 :group 'org-appearance
3608 :version "24.1"
3609 :type 'boolean)
3611 (defcustom org-pretty-entities-include-sub-superscripts t
3612 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3613 :group 'org-appearance
3614 :version "24.1"
3615 :type 'boolean)
3617 (defvar org-emph-re nil
3618 "Regular expression for matching emphasis.
3619 After a match, the match groups contain these elements:
3620 0 The match of the full regular expression, including the characters
3621 before and after the proper match
3622 1 The character before the proper match, or empty at beginning of line
3623 2 The proper match, including the leading and trailing markers
3624 3 The leading marker like * or /, indicating the type of highlighting
3625 4 The text between the emphasis markers, not including the markers
3626 5 The character after the match, empty at the end of a line")
3627 (defvar org-verbatim-re nil
3628 "Regular expression for matching verbatim text.")
3629 (defvar org-emphasis-regexp-components) ; defined just below
3630 (defvar org-emphasis-alist) ; defined just below
3631 (defun org-set-emph-re (var val)
3632 "Set variable and compute the emphasis regular expression."
3633 (set var val)
3634 (when (and (boundp 'org-emphasis-alist)
3635 (boundp 'org-emphasis-regexp-components)
3636 org-emphasis-alist org-emphasis-regexp-components)
3637 (let* ((e org-emphasis-regexp-components)
3638 (pre (car e))
3639 (post (nth 1 e))
3640 (border (nth 2 e))
3641 (body (nth 3 e))
3642 (nl (nth 4 e))
3643 (body1 (concat body "*?"))
3644 (markers (mapconcat 'car org-emphasis-alist ""))
3645 (vmarkers (mapconcat
3646 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3647 org-emphasis-alist "")))
3648 ;; make sure special characters appear at the right position in the class
3649 (if (string-match "\\^" markers)
3650 (setq markers (concat (replace-match "" t t markers) "^")))
3651 (if (string-match "-" markers)
3652 (setq markers (concat (replace-match "" t t markers) "-")))
3653 (if (string-match "\\^" vmarkers)
3654 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3655 (if (string-match "-" vmarkers)
3656 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3657 (if (> nl 0)
3658 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3659 (int-to-string nl) "\\}")))
3660 ;; Make the regexp
3661 (setq org-emph-re
3662 (concat "\\([" pre "]\\|^\\)"
3663 "\\("
3664 "\\([" markers "]\\)"
3665 "\\("
3666 "[^" border "]\\|"
3667 "[^" border "]"
3668 body1
3669 "[^" border "]"
3670 "\\)"
3671 "\\3\\)"
3672 "\\([" post "]\\|$\\)"))
3673 (setq org-verbatim-re
3674 (concat "\\([" pre "]\\|^\\)"
3675 "\\("
3676 "\\([" vmarkers "]\\)"
3677 "\\("
3678 "[^" border "]\\|"
3679 "[^" border "]"
3680 body1
3681 "[^" border "]"
3682 "\\)"
3683 "\\3\\)"
3684 "\\([" post "]\\|$\\)")))))
3686 (defcustom org-emphasis-regexp-components
3687 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3688 "Components used to build the regular expression for emphasis.
3689 This is a list with five entries. Terminology: In an emphasis string
3690 like \" *strong word* \", we call the initial space PREMATCH, the final
3691 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3692 and \"trong wor\" is the body. The different components in this variable
3693 specify what is allowed/forbidden in each part:
3695 pre Chars allowed as prematch. Beginning of line will be allowed too.
3696 post Chars allowed as postmatch. End of line will be allowed too.
3697 border The chars *forbidden* as border characters.
3698 body-regexp A regexp like \".\" to match a body character. Don't use
3699 non-shy groups here, and don't allow newline here.
3700 newline The maximum number of newlines allowed in an emphasis exp.
3702 Use customize to modify this, or restart Emacs after changing it."
3703 :group 'org-appearance
3704 :set 'org-set-emph-re
3705 :type '(list
3706 (sexp :tag "Allowed chars in pre ")
3707 (sexp :tag "Allowed chars in post ")
3708 (sexp :tag "Forbidden chars in border ")
3709 (sexp :tag "Regexp for body ")
3710 (integer :tag "number of newlines allowed")
3711 (option (boolean :tag "Please ignore this button"))))
3713 (defcustom org-emphasis-alist
3714 `(("*" bold "<b>" "</b>")
3715 ("/" italic "<i>" "</i>")
3716 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3717 ("=" org-code "<code>" "</code>" verbatim)
3718 ("~" org-verbatim "<code>" "</code>" verbatim)
3719 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3720 "<del>" "</del>")
3722 "Special syntax for emphasized text.
3723 Text starting and ending with a special character will be emphasized, for
3724 example *bold*, _underlined_ and /italic/. This variable sets the marker
3725 characters, the face to be used by font-lock for highlighting in Org-mode
3726 Emacs buffers, and the HTML tags to be used for this.
3727 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3728 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3729 Use customize to modify this, or restart Emacs after changing it."
3730 :group 'org-appearance
3731 :set 'org-set-emph-re
3732 :type '(repeat
3733 (list
3734 (string :tag "Marker character")
3735 (choice
3736 (face :tag "Font-lock-face")
3737 (plist :tag "Face property list"))
3738 (string :tag "HTML start tag")
3739 (string :tag "HTML end tag")
3740 (option (const verbatim)))))
3742 (defvar org-protecting-blocks
3743 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3744 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3745 This is needed for font-lock setup.")
3747 ;;; Miscellaneous options
3749 (defgroup org-completion nil
3750 "Completion in Org-mode."
3751 :tag "Org Completion"
3752 :group 'org)
3754 (defcustom org-completion-use-ido nil
3755 "Non-nil means use ido completion wherever possible.
3756 Note that `ido-mode' must be active for this variable to be relevant.
3757 If you decide to turn this variable on, you might well want to turn off
3758 `org-outline-path-complete-in-steps'.
3759 See also `org-completion-use-iswitchb'."
3760 :group 'org-completion
3761 :type 'boolean)
3763 (defcustom org-completion-use-iswitchb nil
3764 "Non-nil means use iswitchb completion wherever possible.
3765 Note that `iswitchb-mode' must be active for this variable to be relevant.
3766 If you decide to turn this variable on, you might well want to turn off
3767 `org-outline-path-complete-in-steps'.
3768 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3769 :group 'org-completion
3770 :type 'boolean)
3772 (defcustom org-completion-fallback-command 'hippie-expand
3773 "The expansion command called by \\[pcomplete] in normal context.
3774 Normal means, no org-mode-specific context."
3775 :group 'org-completion
3776 :type 'function)
3778 ;;; Functions and variables from their packages
3779 ;; Declared here to avoid compiler warnings
3781 ;; XEmacs only
3782 (defvar outline-mode-menu-heading)
3783 (defvar outline-mode-menu-show)
3784 (defvar outline-mode-menu-hide)
3785 (defvar zmacs-regions) ; XEmacs regions
3787 ;; Emacs only
3788 (defvar mark-active)
3790 ;; Various packages
3791 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3792 (declare-function calendar-forward-day "cal-move" (arg))
3793 (declare-function calendar-goto-date "cal-move" (date))
3794 (declare-function calendar-goto-today "cal-move" ())
3795 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3796 (defvar calc-embedded-close-formula)
3797 (defvar calc-embedded-open-formula)
3798 (declare-function cdlatex-tab "ext:cdlatex" ())
3799 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3800 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3801 (defvar font-lock-unfontify-region-function)
3802 (declare-function iswitchb-read-buffer "iswitchb"
3803 (prompt &optional default require-match start matches-set))
3804 (defvar iswitchb-temp-buflist)
3805 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3806 (defvar org-agenda-tags-todo-honor-ignore-options)
3807 (declare-function org-agenda-skip "org-agenda" ())
3808 (declare-function
3809 org-agenda-format-item "org-agenda"
3810 (extra txt &optional category tags dotime noprefix remove-re habitp))
3811 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3812 (declare-function org-agenda-change-all-lines "org-agenda"
3813 (newhead hdmarker &optional fixface just-this))
3814 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3815 (declare-function org-agenda-maybe-redo "org-agenda" ())
3816 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3817 (beg end))
3818 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3819 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3820 "org-agenda" (&optional end))
3821 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3822 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3823 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3824 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3825 (declare-function org-indent-mode "org-indent" (&optional arg))
3826 (declare-function parse-time-string "parse-time" (string))
3827 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3828 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3829 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3830 (defvar remember-data-file)
3831 (defvar texmathp-why)
3832 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3833 (declare-function table--at-cell-p "table" (position &optional object at-column))
3835 (defvar w3m-current-url)
3836 (defvar w3m-current-title)
3838 (defvar org-latex-regexps)
3840 ;;; Autoload and prepare some org modules
3842 ;; Some table stuff that needs to be defined here, because it is used
3843 ;; by the functions setting up org-mode or checking for table context.
3845 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3846 "Detect an org-type or table-type table.")
3847 (defconst org-table-line-regexp "^[ \t]*|"
3848 "Detect an org-type table line.")
3849 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3850 "Detect an org-type table line.")
3851 (defconst org-table-hline-regexp "^[ \t]*|-"
3852 "Detect an org-type table hline.")
3853 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3854 "Detect a table-type table hline.")
3855 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3856 "Detect the first line outside a table when searching from within it.
3857 This works for both table types.")
3859 ;; Autoload the functions in org-table.el that are needed by functions here.
3861 (eval-and-compile
3862 (org-autoload "org-table"
3863 '(org-table-align org-table-begin org-table-blank-field
3864 org-table-convert org-table-convert-region org-table-copy-down
3865 org-table-copy-region org-table-create
3866 org-table-create-or-convert-from-region
3867 org-table-create-with-table.el org-table-current-dline
3868 org-table-cut-region org-table-delete-column org-table-edit-field
3869 org-table-edit-formulas org-table-end org-table-eval-formula
3870 org-table-export org-table-field-info
3871 org-table-get-stored-formulas org-table-goto-column
3872 org-table-hline-and-move org-table-import org-table-insert-column
3873 org-table-insert-hline org-table-insert-row org-table-iterate
3874 org-table-justify-field-maybe org-table-kill-row
3875 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3876 org-table-move-column org-table-move-column-left
3877 org-table-move-column-right org-table-move-row
3878 org-table-move-row-down org-table-move-row-up
3879 org-table-next-field org-table-next-row org-table-paste-rectangle
3880 org-table-previous-field org-table-recalculate
3881 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3882 org-table-toggle-coordinate-overlays
3883 org-table-toggle-formula-debugger org-table-wrap-region
3884 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3885 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3886 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3888 (defun org-at-table-p (&optional table-type)
3889 "Return t if the cursor is inside an org-type table.
3890 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3891 (if org-enable-table-editor
3892 (save-excursion
3893 (beginning-of-line 1)
3894 (looking-at (if table-type org-table-any-line-regexp
3895 org-table-line-regexp)))
3896 nil))
3897 (defsubst org-table-p () (org-at-table-p))
3899 (defun org-at-table.el-p ()
3900 "Return t if and only if we are at a table.el table."
3901 (and (org-at-table-p 'any)
3902 (save-excursion
3903 (goto-char (org-table-begin 'any))
3904 (looking-at org-table1-hline-regexp))))
3905 (defun org-table-recognize-table.el ()
3906 "If there is a table.el table nearby, recognize it and move into it."
3907 (if org-table-tab-recognizes-table.el
3908 (if (org-at-table.el-p)
3909 (progn
3910 (beginning-of-line 1)
3911 (if (looking-at org-table-dataline-regexp)
3913 (if (looking-at org-table1-hline-regexp)
3914 (progn
3915 (beginning-of-line 2)
3916 (if (looking-at org-table-any-border-regexp)
3917 (beginning-of-line -1)))))
3918 (if (re-search-forward "|" (org-table-end t) t)
3919 (progn
3920 (require 'table)
3921 (if (table--at-cell-p (point))
3923 (message "recognizing table.el table...")
3924 (table-recognize-table)
3925 (message "recognizing table.el table...done")))
3926 (error "This should not happen"))
3928 nil)
3929 nil))
3931 (defun org-at-table-hline-p ()
3932 "Return t if the cursor is inside a hline in a table."
3933 (if org-enable-table-editor
3934 (save-excursion
3935 (beginning-of-line 1)
3936 (looking-at org-table-hline-regexp))
3937 nil))
3939 (defvar org-table-clean-did-remove-column nil)
3941 (defun org-table-map-tables (function &optional quietly)
3942 "Apply FUNCTION to the start of all tables in the buffer."
3943 (save-excursion
3944 (save-restriction
3945 (widen)
3946 (goto-char (point-min))
3947 (while (re-search-forward org-table-any-line-regexp nil t)
3948 (unless quietly
3949 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3950 (beginning-of-line 1)
3951 (when (and (looking-at org-table-line-regexp)
3952 ;; Exclude tables in src/example/verbatim/clocktable blocks
3953 (not (org-in-block-p '("src" "example"))))
3954 (save-excursion (funcall function))
3955 (or (looking-at org-table-line-regexp)
3956 (forward-char 1)))
3957 (re-search-forward org-table-any-border-regexp nil 1))))
3958 (unless quietly (message "Mapping tables: done")))
3960 ;; Declare and autoload functions from org-exp.el & Co
3962 (declare-function org-default-export-plist "org-exp")
3963 (declare-function org-infile-export-plist "org-exp")
3964 (declare-function org-get-current-options "org-exp")
3965 (eval-and-compile
3966 (org-autoload "org-exp"
3967 '(org-export org-export-visible
3968 org-insert-export-options-template
3969 org-table-clean-before-export))
3970 (org-autoload "org-ascii"
3971 '(org-export-as-ascii org-export-ascii-preprocess
3972 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3973 org-export-region-as-ascii))
3974 (org-autoload "org-latex"
3975 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3976 org-replace-region-by-latex org-export-region-as-latex
3977 org-export-as-latex org-export-as-pdf
3978 org-export-as-pdf-and-open))
3979 (org-autoload "org-html"
3980 '(org-export-as-html-and-open
3981 org-export-as-html-batch org-export-as-html-to-buffer
3982 org-replace-region-by-html org-export-region-as-html
3983 org-export-as-html))
3984 (org-autoload "org-docbook"
3985 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3986 org-replace-region-by-docbook org-export-region-as-docbook
3987 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3988 org-export-as-docbook))
3989 (org-autoload "org-icalendar"
3990 '(org-export-icalendar-this-file
3991 org-export-icalendar-all-agenda-files
3992 org-export-icalendar-combine-agenda-files))
3993 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3994 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3996 ;; Declare and autoload functions from org-agenda.el
3998 (eval-and-compile
3999 (org-autoload "org-agenda"
4000 '(org-agenda org-agenda-list org-search-view
4001 org-todo-list org-tags-view org-agenda-list-stuck-projects
4002 org-diary org-agenda-to-appt
4003 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4005 ;; Autoload org-remember
4007 (eval-and-compile
4008 (org-autoload "org-remember"
4009 '(org-remember-insinuate org-remember-annotation
4010 org-remember-apply-template org-remember org-remember-handler)))
4012 (eval-and-compile
4013 (org-autoload "org-capture"
4014 '(org-capture org-capture-insert-template-here
4015 org-capture-import-remember-templates)))
4017 ;; Autoload org-clock.el
4019 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4020 (beg end))
4021 (declare-function org-clock-update-mode-line "org-clock" ())
4022 (declare-function org-resolve-clocks "org-clock"
4023 (&optional also-non-dangling-p prompt last-valid))
4024 (defvar org-clock-start-time)
4025 (defvar org-clock-marker (make-marker)
4026 "Marker recording the last clock-in.")
4027 (defvar org-clock-hd-marker (make-marker)
4028 "Marker recording the last clock-in, but the headline position.")
4029 (defvar org-clock-heading ""
4030 "The heading of the current clock entry.")
4031 (defun org-clock-is-active ()
4032 "Return non-nil if clock is currently running.
4033 The return value is actually the clock marker."
4034 (marker-buffer org-clock-marker))
4036 (eval-and-compile
4037 (org-autoload
4038 "org-clock"
4039 '(org-clock-in org-clock-out org-clock-cancel
4040 org-clock-goto org-clock-sum org-clock-display
4041 org-clock-remove-overlays org-clock-report
4042 org-clocktable-shift org-dblock-write:clocktable
4043 org-get-clocktable org-resolve-clocks)))
4045 (defun org-clock-update-time-maybe ()
4046 "If this is a CLOCK line, update it and return t.
4047 Otherwise, return nil."
4048 (interactive)
4049 (save-excursion
4050 (beginning-of-line 1)
4051 (skip-chars-forward " \t")
4052 (when (looking-at org-clock-string)
4053 (let ((re (concat "[ \t]*" org-clock-string
4054 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4055 "\\([ \t]*=>.*\\)?\\)?"))
4056 ts te h m s neg)
4057 (cond
4058 ((not (looking-at re))
4059 nil)
4060 ((not (match-end 2))
4061 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4062 (> org-clock-marker (point))
4063 (<= org-clock-marker (point-at-eol)))
4064 ;; The clock is running here
4065 (setq org-clock-start-time
4066 (apply 'encode-time
4067 (org-parse-time-string (match-string 1))))
4068 (org-clock-update-mode-line)))
4070 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4071 (end-of-line 1)
4072 (setq ts (match-string 1)
4073 te (match-string 3))
4074 (setq s (- (org-float-time
4075 (apply 'encode-time (org-parse-time-string te)))
4076 (org-float-time
4077 (apply 'encode-time (org-parse-time-string ts))))
4078 neg (< s 0)
4079 s (abs s)
4080 h (floor (/ s 3600))
4081 s (- s (* 3600 h))
4082 m (floor (/ s 60))
4083 s (- s (* 60 s)))
4084 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4085 t))))))
4087 (defun org-check-running-clock ()
4088 "Check if the current buffer contains the running clock.
4089 If yes, offer to stop it and to save the buffer with the changes."
4090 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4091 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4092 (buffer-name))))
4093 (org-clock-out)
4094 (when (y-or-n-p "Save changed buffer?")
4095 (save-buffer))))
4097 (defun org-clocktable-try-shift (dir n)
4098 "Check if this line starts a clock table, if yes, shift the time block."
4099 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4100 (org-clocktable-shift dir n)))
4102 ;; Autoload org-timer.el
4104 (eval-and-compile
4105 (org-autoload
4106 "org-timer"
4107 '(org-timer-start org-timer org-timer-item
4108 org-timer-change-times-in-region
4109 org-timer-set-timer
4110 org-timer-reset-timers
4111 org-timer-show-remaining-time)))
4113 ;; Autoload org-feed.el
4115 (eval-and-compile
4116 (org-autoload
4117 "org-feed"
4118 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4121 ;; Autoload org-indent.el
4123 ;; Define the variable already here, to make sure we have it.
4124 (defvar org-indent-mode nil
4125 "Non-nil if Org-Indent mode is enabled.
4126 Use the command `org-indent-mode' to change this variable.")
4128 (eval-and-compile
4129 (org-autoload
4130 "org-indent"
4131 '(org-indent-mode)))
4133 ;; Autoload org-mobile.el
4135 (eval-and-compile
4136 (org-autoload
4137 "org-mobile"
4138 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4140 ;; Autoload archiving code
4141 ;; The stuff that is needed for cycling and tags has to be defined here.
4143 (defgroup org-archive nil
4144 "Options concerning archiving in Org-mode."
4145 :tag "Org Archive"
4146 :group 'org-structure)
4148 (defcustom org-archive-location "%s_archive::"
4149 "The location where subtrees should be archived.
4151 The value of this variable is a string, consisting of two parts,
4152 separated by a double-colon. The first part is a filename and
4153 the second part is a headline.
4155 When the filename is omitted, archiving happens in the same file.
4156 %s in the filename will be replaced by the current file
4157 name (without the directory part). Archiving to a different file
4158 is useful to keep archived entries from contributing to the
4159 Org-mode Agenda.
4161 The archived entries will be filed as subtrees of the specified
4162 headline. When the headline is omitted, the subtrees are simply
4163 filed away at the end of the file, as top-level entries. Also in
4164 the heading you can use %s to represent the file name, this can be
4165 useful when using the same archive for a number of different files.
4167 Here are a few examples:
4168 \"%s_archive::\"
4169 If the current file is Projects.org, archive in file
4170 Projects.org_archive, as top-level trees. This is the default.
4172 \"::* Archived Tasks\"
4173 Archive in the current file, under the top-level headline
4174 \"* Archived Tasks\".
4176 \"~/org/archive.org::\"
4177 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4179 \"~/org/archive.org::* From %s\"
4180 Archive in file ~/org/archive.org (absolute path), under headlines
4181 \"From FILENAME\" where file name is the current file name.
4183 \"~/org/datetree.org::datetree/* Finished Tasks\"
4184 The \"datetree/\" string is special, signifying to archive
4185 items to the datetree. Items are placed in either the CLOSED
4186 date of the item, or the current date if there is no CLOSED date.
4187 The heading will be a subentry to the current date. There doesn't
4188 need to be a heading, but there always needs to be a slash after
4189 datetree. For example, to store archived items directly in the
4190 datetree, use \"~/org/datetree.org::datetree/\".
4192 \"basement::** Finished Tasks\"
4193 Archive in file ./basement (relative path), as level 3 trees
4194 below the level 2 heading \"** Finished Tasks\".
4196 You may set this option on a per-file basis by adding to the buffer a
4197 line like
4199 #+ARCHIVE: basement::** Finished Tasks
4201 You may also define it locally for a subtree by setting an ARCHIVE property
4202 in the entry. If such a property is found in an entry, or anywhere up
4203 the hierarchy, it will be used."
4204 :group 'org-archive
4205 :type 'string)
4207 (defcustom org-archive-tag "ARCHIVE"
4208 "The tag that marks a subtree as archived.
4209 An archived subtree does not open during visibility cycling, and does
4210 not contribute to the agenda listings.
4211 After changing this, font-lock must be restarted in the relevant buffers to
4212 get the proper fontification."
4213 :group 'org-archive
4214 :group 'org-keywords
4215 :type 'string)
4217 (defcustom org-agenda-skip-archived-trees t
4218 "Non-nil means the agenda will skip any items located in archived trees.
4219 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4220 variable is no longer recommended, you should leave it at the value t.
4221 Instead, use the key `v' to cycle the archives-mode in the agenda."
4222 :group 'org-archive
4223 :group 'org-agenda-skip
4224 :type 'boolean)
4226 (defcustom org-columns-skip-archived-trees t
4227 "Non-nil means ignore archived trees when creating column view."
4228 :group 'org-archive
4229 :group 'org-properties
4230 :type 'boolean)
4232 (defcustom org-cycle-open-archived-trees nil
4233 "Non-nil means `org-cycle' will open archived trees.
4234 An archived tree is a tree marked with the tag ARCHIVE.
4235 When nil, archived trees will stay folded. You can still open them with
4236 normal outline commands like `show-all', but not with the cycling commands."
4237 :group 'org-archive
4238 :group 'org-cycle
4239 :type 'boolean)
4241 (defcustom org-sparse-tree-open-archived-trees nil
4242 "Non-nil means sparse tree construction shows matches in archived trees.
4243 When nil, matches in these trees are highlighted, but the trees are kept in
4244 collapsed state."
4245 :group 'org-archive
4246 :group 'org-sparse-trees
4247 :type 'boolean)
4249 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4250 "The default date type when building a sparse tree.
4251 When this is nil, a date is a scheduled or a deadline timestamp.
4252 Otherwise, these types are allowed:
4254 all: all timestamps
4255 active: only active timestamps (<...>)
4256 inactive: only inactive timestamps (<...)
4257 scheduled: only scheduled timestamps
4258 deadline: only deadline timestamps"
4259 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4260 (const :tag "All timestamps" all)
4261 (const :tag "Only active timestamps" active)
4262 (const :tag "Only inactive timestamps" inactive)
4263 (const :tag "Only scheduled timestamps" scheduled)
4264 (const :tag "Only deadline timestamps" deadline))
4265 :version "24.3"
4266 :group 'org-sparse-trees)
4268 (defun org-cycle-hide-archived-subtrees (state)
4269 "Re-hide all archived subtrees after a visibility state change."
4270 (when (and (not org-cycle-open-archived-trees)
4271 (not (memq state '(overview folded))))
4272 (save-excursion
4273 (let* ((globalp (memq state '(contents all)))
4274 (beg (if globalp (point-min) (point)))
4275 (end (if globalp (point-max) (org-end-of-subtree t))))
4276 (org-hide-archived-subtrees beg end)
4277 (goto-char beg)
4278 (if (looking-at (concat ".*:" org-archive-tag ":"))
4279 (message "%s" (substitute-command-keys
4280 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4282 (defun org-force-cycle-archived ()
4283 "Cycle subtree even if it is archived."
4284 (interactive)
4285 (setq this-command 'org-cycle)
4286 (let ((org-cycle-open-archived-trees t))
4287 (call-interactively 'org-cycle)))
4289 (defun org-hide-archived-subtrees (beg end)
4290 "Re-hide all archived subtrees after a visibility state change."
4291 (save-excursion
4292 (let* ((re (concat ":" org-archive-tag ":")))
4293 (goto-char beg)
4294 (while (re-search-forward re end t)
4295 (when (org-at-heading-p)
4296 (org-flag-subtree t)
4297 (org-end-of-subtree t))))))
4299 (declare-function outline-end-of-heading "outline" ())
4300 (declare-function outline-flag-region "outline" (from to flag))
4301 (defun org-flag-subtree (flag)
4302 (save-excursion
4303 (org-back-to-heading t)
4304 (outline-end-of-heading)
4305 (outline-flag-region (point)
4306 (progn (org-end-of-subtree t) (point))
4307 flag)))
4309 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4311 (eval-and-compile
4312 (org-autoload "org-archive"
4313 '(org-add-archive-files org-archive-subtree
4314 org-archive-to-archive-sibling org-toggle-archive-tag
4315 org-archive-subtree-default
4316 org-archive-subtree-default-with-confirmation)))
4318 ;; Autoload Column View Code
4320 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4321 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4322 (declare-function org-columns-compute "org-colview" (property))
4324 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4325 '(org-columns-number-to-string org-columns-get-format-and-top-level
4326 org-columns-compute org-agenda-columns org-columns-remove-overlays
4327 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4329 ;; Autoload ID code
4331 (declare-function org-id-store-link "org-id")
4332 (declare-function org-id-locations-load "org-id")
4333 (declare-function org-id-locations-save "org-id")
4334 (defvar org-id-track-globally)
4335 (org-autoload "org-id"
4336 '(org-id-get-create org-id-new org-id-copy org-id-get
4337 org-id-get-with-outline-path-completion
4338 org-id-get-with-outline-drilling org-id-store-link
4339 org-id-goto org-id-find org-id-store-link))
4341 ;; Autoload Plotting Code
4343 (org-autoload "org-plot"
4344 '(org-plot/gnuplot))
4346 ;;; Variables for pre-computed regular expressions, all buffer local
4348 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4349 "Matches first line of a hidden block.")
4350 (make-variable-buffer-local 'org-drawer-regexp)
4351 (defvar org-todo-regexp nil
4352 "Matches any of the TODO state keywords.")
4353 (make-variable-buffer-local 'org-todo-regexp)
4354 (defvar org-not-done-regexp nil
4355 "Matches any of the TODO state keywords except the last one.")
4356 (make-variable-buffer-local 'org-not-done-regexp)
4357 (defvar org-not-done-heading-regexp nil
4358 "Matches a TODO headline that is not done.")
4359 (make-variable-buffer-local 'org-not-done-regexp)
4360 (defvar org-todo-line-regexp nil
4361 "Matches a headline and puts TODO state into group 2 if present.")
4362 (make-variable-buffer-local 'org-todo-line-regexp)
4363 (defvar org-complex-heading-regexp nil
4364 "Matches a headline and puts everything into groups:
4365 group 1: the stars
4366 group 2: The todo keyword, maybe
4367 group 3: Priority cookie
4368 group 4: True headline
4369 group 5: Tags")
4370 (make-variable-buffer-local 'org-complex-heading-regexp)
4371 (defvar org-complex-heading-regexp-format nil
4372 "Printf format to make regexp to match an exact headline.
4373 This regexp will match the headline of any node which has the
4374 exact headline text that is put into the format, but may have any
4375 TODO state, priority and tags.")
4376 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4377 (defvar org-todo-line-tags-regexp nil
4378 "Matches a headline and puts TODO state into group 2 if present.
4379 Also put tags into group 4 if tags are present.")
4380 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4381 (defvar org-ds-keyword-length 12
4382 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4383 (make-variable-buffer-local 'org-ds-keyword-length)
4384 (defvar org-deadline-regexp nil
4385 "Matches the DEADLINE keyword.")
4386 (make-variable-buffer-local 'org-deadline-regexp)
4387 (defvar org-deadline-time-regexp nil
4388 "Matches the DEADLINE keyword together with a time stamp.")
4389 (make-variable-buffer-local 'org-deadline-time-regexp)
4390 (defvar org-deadline-line-regexp nil
4391 "Matches the DEADLINE keyword and the rest of the line.")
4392 (make-variable-buffer-local 'org-deadline-line-regexp)
4393 (defvar org-scheduled-regexp nil
4394 "Matches the SCHEDULED keyword.")
4395 (make-variable-buffer-local 'org-scheduled-regexp)
4396 (defvar org-scheduled-time-regexp nil
4397 "Matches the SCHEDULED keyword together with a time stamp.")
4398 (make-variable-buffer-local 'org-scheduled-time-regexp)
4399 (defvar org-closed-time-regexp nil
4400 "Matches the CLOSED keyword together with a time stamp.")
4401 (make-variable-buffer-local 'org-closed-time-regexp)
4403 (defvar org-keyword-time-regexp nil
4404 "Matches any of the 4 keywords, together with the time stamp.")
4405 (make-variable-buffer-local 'org-keyword-time-regexp)
4406 (defvar org-keyword-time-not-clock-regexp nil
4407 "Matches any of the 3 keywords, together with the time stamp.")
4408 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4409 (defvar org-maybe-keyword-time-regexp nil
4410 "Matches a timestamp, possibly preceded by a keyword.")
4411 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4412 (defvar org-all-time-keywords nil
4413 "List of time keywords.")
4414 (make-variable-buffer-local 'org-all-time-keywords)
4416 (defconst org-plain-time-of-day-regexp
4417 (concat
4418 "\\(\\<[012]?[0-9]"
4419 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4420 "\\(--?"
4421 "\\(\\<[012]?[0-9]"
4422 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4423 "\\)?")
4424 "Regular expression to match a plain time or time range.
4425 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4426 groups carry important information:
4427 0 the full match
4428 1 the first time, range or not
4429 8 the second time, if it is a range.")
4431 (defconst org-plain-time-extension-regexp
4432 (concat
4433 "\\(\\<[012]?[0-9]"
4434 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4435 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4436 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4437 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4438 groups carry important information:
4439 0 the full match
4440 7 hours of duration
4441 9 minutes of duration")
4443 (defconst org-stamp-time-of-day-regexp
4444 (concat
4445 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4446 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4447 "\\(--?"
4448 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4449 "Regular expression to match a timestamp time or time range.
4450 After a match, the following groups carry important information:
4451 0 the full match
4452 1 date plus weekday, for back referencing to make sure both times are on the same day
4453 2 the first time, range or not
4454 4 the second time, if it is a range.")
4456 (defconst org-startup-options
4457 '(("fold" org-startup-folded t)
4458 ("overview" org-startup-folded t)
4459 ("nofold" org-startup-folded nil)
4460 ("showall" org-startup-folded nil)
4461 ("showeverything" org-startup-folded showeverything)
4462 ("content" org-startup-folded content)
4463 ("indent" org-startup-indented t)
4464 ("noindent" org-startup-indented nil)
4465 ("hidestars" org-hide-leading-stars t)
4466 ("showstars" org-hide-leading-stars nil)
4467 ("odd" org-odd-levels-only t)
4468 ("oddeven" org-odd-levels-only nil)
4469 ("align" org-startup-align-all-tables t)
4470 ("noalign" org-startup-align-all-tables nil)
4471 ("inlineimages" org-startup-with-inline-images t)
4472 ("noinlineimages" org-startup-with-inline-images nil)
4473 ("customtime" org-display-custom-times t)
4474 ("logdone" org-log-done time)
4475 ("lognotedone" org-log-done note)
4476 ("nologdone" org-log-done nil)
4477 ("lognoteclock-out" org-log-note-clock-out t)
4478 ("nolognoteclock-out" org-log-note-clock-out nil)
4479 ("logrepeat" org-log-repeat state)
4480 ("lognoterepeat" org-log-repeat note)
4481 ("nologrepeat" org-log-repeat nil)
4482 ("logreschedule" org-log-reschedule time)
4483 ("lognotereschedule" org-log-reschedule note)
4484 ("nologreschedule" org-log-reschedule nil)
4485 ("logredeadline" org-log-redeadline time)
4486 ("lognoteredeadline" org-log-redeadline note)
4487 ("nologredeadline" org-log-redeadline nil)
4488 ("logrefile" org-log-refile time)
4489 ("lognoterefile" org-log-refile note)
4490 ("nologrefile" org-log-refile nil)
4491 ("fninline" org-footnote-define-inline t)
4492 ("nofninline" org-footnote-define-inline nil)
4493 ("fnlocal" org-footnote-section nil)
4494 ("fnauto" org-footnote-auto-label t)
4495 ("fnprompt" org-footnote-auto-label nil)
4496 ("fnconfirm" org-footnote-auto-label confirm)
4497 ("fnplain" org-footnote-auto-label plain)
4498 ("fnadjust" org-footnote-auto-adjust t)
4499 ("nofnadjust" org-footnote-auto-adjust nil)
4500 ("constcgs" constants-unit-system cgs)
4501 ("constSI" constants-unit-system SI)
4502 ("noptag" org-tag-persistent-alist nil)
4503 ("hideblocks" org-hide-block-startup t)
4504 ("nohideblocks" org-hide-block-startup nil)
4505 ("beamer" org-startup-with-beamer-mode t)
4506 ("entitiespretty" org-pretty-entities t)
4507 ("entitiesplain" org-pretty-entities nil))
4508 "Variable associated with STARTUP options for org-mode.
4509 Each element is a list of three items: the startup options (as written
4510 in the #+STARTUP line), the corresponding variable, and the value to set
4511 this variable to if the option is found. An optional forth element PUSH
4512 means to push this value onto the list in the variable.")
4514 (defun org-update-property-plist (key val props)
4515 "Update PROPS with KEY and VAL."
4516 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4517 (key (if appending (substring key 0 (- (length key) 1)) key))
4518 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4519 (previous (cdr (assoc key props))))
4520 (if appending
4521 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4522 (cons (cons key val) remainder))))
4524 (defconst org-block-regexp
4525 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4526 "Regular expression for hiding blocks.")
4527 (defconst org-heading-keyword-regexp-format
4528 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4529 "Printf format for a regexp matching an headline with some keyword.
4530 This regexp will match the headline of any node which has the
4531 exact keyword that is put into the format. The keyword isn't in
4532 any group by default, but the stars and the body are.")
4533 (defconst org-heading-keyword-maybe-regexp-format
4534 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4535 "Printf format for a regexp matching an headline, possibly with some keyword.
4536 This regexp can match any headline with the specified keyword, or
4537 without a keyword. The keyword isn't in any group by default,
4538 but the stars and the body are.")
4540 (defun org-set-regexps-and-options ()
4541 "Precompute regular expressions for current buffer."
4542 (when (derived-mode-p 'org-mode)
4543 (org-set-local 'org-todo-kwd-alist nil)
4544 (org-set-local 'org-todo-key-alist nil)
4545 (org-set-local 'org-todo-key-trigger nil)
4546 (org-set-local 'org-todo-keywords-1 nil)
4547 (org-set-local 'org-done-keywords nil)
4548 (org-set-local 'org-todo-heads nil)
4549 (org-set-local 'org-todo-sets nil)
4550 (org-set-local 'org-todo-log-states nil)
4551 (org-set-local 'org-file-properties nil)
4552 (org-set-local 'org-file-tags nil)
4553 (let ((re (org-make-options-regexp
4554 '("CATEGORY" "TODO" "COLUMNS"
4555 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4556 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4557 "OPTIONS")
4558 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4559 (splitre "[ \t]+")
4560 (scripts org-use-sub-superscripts)
4561 kwds kws0 kwsa key log value cat arch tags const links hw dws
4562 tail sep kws1 prio props ftags drawers beamer-p
4563 ext-setup-or-nil setup-contents (start 0))
4564 (save-excursion
4565 (save-restriction
4566 (widen)
4567 (goto-char (point-min))
4568 (while (or (and ext-setup-or-nil
4569 (string-match re ext-setup-or-nil start)
4570 (setq start (match-end 0)))
4571 (and (setq ext-setup-or-nil nil start 0)
4572 (re-search-forward re nil t)))
4573 (setq key (upcase (match-string 1 ext-setup-or-nil))
4574 value (org-match-string-no-properties 2 ext-setup-or-nil))
4575 (if (stringp value) (setq value (org-trim value)))
4576 (cond
4577 ((equal key "CATEGORY")
4578 (setq cat value))
4579 ((member key '("SEQ_TODO" "TODO"))
4580 (push (cons 'sequence (org-split-string value splitre)) kwds))
4581 ((equal key "TYP_TODO")
4582 (push (cons 'type (org-split-string value splitre)) kwds))
4583 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4584 ;; general TODO-like setup
4585 (push (cons (intern (downcase (match-string 1 key)))
4586 (org-split-string value splitre)) kwds))
4587 ((equal key "TAGS")
4588 (setq tags (append tags (if tags '("\\n") nil)
4589 (org-split-string value splitre))))
4590 ((equal key "COLUMNS")
4591 (org-set-local 'org-columns-default-format value))
4592 ((equal key "LINK")
4593 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4594 (push (cons (match-string 1 value)
4595 (org-trim (match-string 2 value)))
4596 links)))
4597 ((equal key "PRIORITIES")
4598 (setq prio (org-split-string value " +")))
4599 ((equal key "PROPERTY")
4600 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4601 (setq props (org-update-property-plist (match-string 1 value)
4602 (match-string 2 value)
4603 props))))
4604 ((equal key "FILETAGS")
4605 (when (string-match "\\S-" value)
4606 (setq ftags
4607 (append
4608 ftags
4609 (apply 'append
4610 (mapcar (lambda (x) (org-split-string x ":"))
4611 (org-split-string value)))))))
4612 ((equal key "DRAWERS")
4613 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4614 ((equal key "CONSTANTS")
4615 (setq const (append const (org-split-string value splitre))))
4616 ((equal key "STARTUP")
4617 (let ((opts (org-split-string value splitre))
4618 l var val)
4619 (while (setq l (pop opts))
4620 (when (setq l (assoc l org-startup-options))
4621 (setq var (nth 1 l) val (nth 2 l))
4622 (if (not (nth 3 l))
4623 (set (make-local-variable var) val)
4624 (if (not (listp (symbol-value var)))
4625 (set (make-local-variable var) nil))
4626 (set (make-local-variable var) (symbol-value var))
4627 (add-to-list var val))))))
4628 ((equal key "ARCHIVE")
4629 (setq arch value)
4630 (remove-text-properties 0 (length arch)
4631 '(face t fontified t) arch))
4632 ((equal key "LATEX_CLASS")
4633 (setq beamer-p (equal value "beamer")))
4634 ((equal key "OPTIONS")
4635 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4636 (setq scripts (read (match-string 2 value)))))
4637 ((equal key "SETUPFILE")
4638 (setq setup-contents (org-file-contents
4639 (expand-file-name
4640 (org-remove-double-quotes value))
4641 'noerror))
4642 (if (not ext-setup-or-nil)
4643 (setq ext-setup-or-nil setup-contents start 0)
4644 (setq ext-setup-or-nil
4645 (concat (substring ext-setup-or-nil 0 start)
4646 "\n" setup-contents "\n"
4647 (substring ext-setup-or-nil start)))))))
4648 ;; search for property blocks
4649 (goto-char (point-min))
4650 (while (re-search-forward org-block-regexp nil t)
4651 (when (equal "PROPERTY" (upcase (match-string 1)))
4652 (setq value (replace-regexp-in-string
4653 "[\n\r]" " " (match-string 4)))
4654 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4655 (setq props (org-update-property-plist (match-string 1 value)
4656 (match-string 2 value)
4657 props)))))))
4658 (org-set-local 'org-use-sub-superscripts scripts)
4659 (when cat
4660 (org-set-local 'org-category (intern cat))
4661 (push (cons "CATEGORY" cat) props))
4662 (when prio
4663 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4664 (setq prio (mapcar 'string-to-char prio))
4665 (org-set-local 'org-highest-priority (nth 0 prio))
4666 (org-set-local 'org-lowest-priority (nth 1 prio))
4667 (org-set-local 'org-default-priority (nth 2 prio)))
4668 (and props (org-set-local 'org-file-properties (nreverse props)))
4669 (and ftags (org-set-local 'org-file-tags
4670 (mapcar 'org-add-prop-inherited ftags)))
4671 (and drawers (org-set-local 'org-drawers drawers))
4672 (and arch (org-set-local 'org-archive-location arch))
4673 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4674 ;; Process the TODO keywords
4675 (unless kwds
4676 ;; Use the global values as if they had been given locally.
4677 (setq kwds (default-value 'org-todo-keywords))
4678 (if (stringp (car kwds))
4679 (setq kwds (list (cons org-todo-interpretation
4680 (default-value 'org-todo-keywords)))))
4681 (setq kwds (reverse kwds)))
4682 (setq kwds (nreverse kwds))
4683 (let (inter kws kw)
4684 (while (setq kws (pop kwds))
4685 (let ((kws (or
4686 (run-hook-with-args-until-success
4687 'org-todo-setup-filter-hook kws)
4688 kws)))
4689 (setq inter (pop kws) sep (member "|" kws)
4690 kws0 (delete "|" (copy-sequence kws))
4691 kwsa nil
4692 kws1 (mapcar
4693 (lambda (x)
4694 ;; 1 2
4695 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4696 (progn
4697 (setq kw (match-string 1 x)
4698 key (and (match-end 2) (match-string 2 x))
4699 log (org-extract-log-state-settings x))
4700 (push (cons kw (and key (string-to-char key))) kwsa)
4701 (and log (push log org-todo-log-states))
4703 (error "Invalid TODO keyword %s" x)))
4704 kws0)
4705 kwsa (if kwsa (append '((:startgroup))
4706 (nreverse kwsa)
4707 '((:endgroup))))
4708 hw (car kws1)
4709 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4710 tail (list inter hw (car dws) (org-last dws))))
4711 (add-to-list 'org-todo-heads hw 'append)
4712 (push kws1 org-todo-sets)
4713 (setq org-done-keywords (append org-done-keywords dws nil))
4714 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4715 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4716 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4717 (setq org-todo-sets (nreverse org-todo-sets)
4718 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4719 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4720 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4721 ;; Process the constants
4722 (when const
4723 (let (e cst)
4724 (while (setq e (pop const))
4725 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4726 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4727 (setq org-table-formula-constants-local cst)))
4729 ;; Process the tags.
4730 (when tags
4731 (let (e tgs)
4732 (while (setq e (pop tags))
4733 (cond
4734 ((equal e "{") (push '(:startgroup) tgs))
4735 ((equal e "}") (push '(:endgroup) tgs))
4736 ((equal e "\\n") (push '(:newline) tgs))
4737 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4738 (push (cons (match-string 1 e)
4739 (string-to-char (match-string 2 e)))
4740 tgs))
4741 (t (push (list e) tgs))))
4742 (org-set-local 'org-tag-alist nil)
4743 (while (setq e (pop tgs))
4744 (or (and (stringp (car e))
4745 (assoc (car e) org-tag-alist))
4746 (push e org-tag-alist)))))
4748 ;; Compute the regular expressions and other local variables.
4749 ;; Using `org-outline-regexp-bol' would complicate them much,
4750 ;; because of the fixed white space at the end of that string.
4751 (if (not org-done-keywords)
4752 (setq org-done-keywords (and org-todo-keywords-1
4753 (list (org-last org-todo-keywords-1)))))
4754 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4755 (length org-scheduled-string)
4756 (length org-clock-string)
4757 (length org-closed-string)))
4758 org-drawer-regexp
4759 (concat "^[ \t]*:\\("
4760 (mapconcat 'regexp-quote org-drawers "\\|")
4761 "\\):[ \t]*$")
4762 org-not-done-keywords
4763 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4764 org-todo-regexp
4765 (concat "\\("
4766 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4767 "\\)")
4768 org-not-done-regexp
4769 (concat "\\("
4770 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4771 "\\)")
4772 org-not-done-heading-regexp
4773 (format org-heading-keyword-regexp-format org-not-done-regexp)
4774 org-todo-line-regexp
4775 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4776 org-complex-heading-regexp
4777 (concat "^\\(\\*+\\)"
4778 "\\(?: +" org-todo-regexp "\\)?"
4779 "\\(?: +\\(\\[#.\\]\\)\\)?"
4780 "\\(?: +\\(.*?\\)\\)??"
4781 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4782 "[ \t]*$")
4783 org-complex-heading-regexp-format
4784 (concat "^\\(\\*+\\)"
4785 "\\(?: +" org-todo-regexp "\\)?"
4786 "\\(?: +\\(\\[#.\\]\\)\\)?"
4787 "\\(?: +"
4788 ;; Stats cookies can be stuck to body.
4789 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4790 "\\(%s\\)"
4791 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4792 "\\)"
4793 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4794 "[ \t]*$")
4795 org-todo-line-tags-regexp
4796 (concat "^\\(\\*+\\)"
4797 "\\(?: +" org-todo-regexp "\\)?"
4798 "\\(?: +\\(.*?\\)\\)??"
4799 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4800 "[ \t]*$")
4801 org-deadline-regexp (concat "\\<" org-deadline-string)
4802 org-deadline-time-regexp
4803 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4804 org-deadline-line-regexp
4805 (concat "\\<\\(" org-deadline-string "\\).*")
4806 org-scheduled-regexp
4807 (concat "\\<" org-scheduled-string)
4808 org-scheduled-time-regexp
4809 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4810 org-closed-time-regexp
4811 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4812 org-keyword-time-regexp
4813 (concat "\\<\\(" org-scheduled-string
4814 "\\|" org-deadline-string
4815 "\\|" org-closed-string
4816 "\\|" org-clock-string "\\)"
4817 " *[[<]\\([^]>]+\\)[]>]")
4818 org-keyword-time-not-clock-regexp
4819 (concat "\\<\\(" org-scheduled-string
4820 "\\|" org-deadline-string
4821 "\\|" org-closed-string
4822 "\\)"
4823 " *[[<]\\([^]>]+\\)[]>]")
4824 org-maybe-keyword-time-regexp
4825 (concat "\\(\\<\\(" org-scheduled-string
4826 "\\|" org-deadline-string
4827 "\\|" org-closed-string
4828 "\\|" org-clock-string "\\)\\)?"
4829 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4830 org-all-time-keywords
4831 (mapcar (lambda (w) (substring w 0 -1))
4832 (list org-scheduled-string org-deadline-string
4833 org-clock-string org-closed-string))
4835 (org-compute-latex-and-specials-regexp)
4836 (org-set-font-lock-defaults))))
4838 (defun org-file-contents (file &optional noerror)
4839 "Return the contents of FILE, as a string."
4840 (if (or (not file)
4841 (not (file-readable-p file)))
4842 (if noerror
4843 (progn
4844 (message "Cannot read file \"%s\"" file)
4845 (ding) (sit-for 2)
4847 (error "Cannot read file \"%s\"" file))
4848 (with-temp-buffer
4849 (insert-file-contents file)
4850 (buffer-string))))
4852 (defun org-extract-log-state-settings (x)
4853 "Extract the log state setting from a TODO keyword string.
4854 This will extract info from a string like \"WAIT(w@/!)\"."
4855 (let (kw key log1 log2)
4856 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4857 (setq kw (match-string 1 x)
4858 key (and (match-end 2) (match-string 2 x))
4859 log1 (and (match-end 3) (match-string 3 x))
4860 log2 (and (match-end 4) (match-string 4 x)))
4861 (and (or log1 log2)
4862 (list kw
4863 (and log1 (if (equal log1 "!") 'time 'note))
4864 (and log2 (if (equal log2 "!") 'time 'note)))))))
4866 (defun org-remove-keyword-keys (list)
4867 "Remove a pair of parenthesis at the end of each string in LIST."
4868 (mapcar (lambda (x)
4869 (if (string-match "(.*)$" x)
4870 (substring x 0 (match-beginning 0))
4872 list))
4874 (defun org-assign-fast-keys (alist)
4875 "Assign fast keys to a keyword-key alist.
4876 Respect keys that are already there."
4877 (let (new e (alt ?0))
4878 (while (setq e (pop alist))
4879 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4880 (cdr e)) ;; Key already assigned.
4881 (push e new)
4882 (let ((clist (string-to-list (downcase (car e))))
4883 (used (append new alist)))
4884 (when (= (car clist) ?@)
4885 (pop clist))
4886 (while (and clist (rassoc (car clist) used))
4887 (pop clist))
4888 (unless clist
4889 (while (rassoc alt used)
4890 (incf alt)))
4891 (push (cons (car e) (or (car clist) alt)) new))))
4892 (nreverse new)))
4894 ;;; Some variables used in various places
4896 (defvar org-window-configuration nil
4897 "Used in various places to store a window configuration.")
4898 (defvar org-selected-window nil
4899 "Used in various places to store a window configuration.")
4900 (defvar org-finish-function nil
4901 "Function to be called when `C-c C-c' is used.
4902 This is for getting out of special buffers like capture.")
4905 ;; FIXME: Occasionally check by commenting these, to make sure
4906 ;; no other functions uses these, forgetting to let-bind them.
4907 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4908 (defvar org-last-state)
4909 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4911 ;; Defined somewhere in this file, but used before definition.
4912 (defvar org-entities) ;; defined in org-entities.el
4913 (defvar org-struct-menu)
4914 (defvar org-org-menu)
4915 (defvar org-tbl-menu)
4917 ;;;; Define the Org-mode
4919 ;; We use a before-change function to check if a table might need
4920 ;; an update.
4921 (defvar org-table-may-need-update t
4922 "Indicates that a table might need an update.
4923 This variable is set by `org-before-change-function'.
4924 `org-table-align' sets it back to nil.")
4925 (defun org-before-change-function (beg end)
4926 "Every change indicates that a table might need an update."
4927 (setq org-table-may-need-update t))
4928 (defvar org-mode-map)
4929 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4930 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4931 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4932 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4933 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4934 (defvar org-table-buffer-is-an nil)
4936 (defvar bidi-paragraph-direction)
4937 (defvar buffer-face-mode-face)
4939 (require 'outline)
4940 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4941 (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"))
4942 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4944 ;; Other stuff we need.
4945 (require 'time-date)
4946 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4947 (require 'easymenu)
4948 (require 'overlay)
4950 (require 'org-macs)
4951 (require 'org-entities)
4952 ;; (require 'org-compat) moved higher up in the file before it is first used
4953 (require 'org-faces)
4954 (require 'org-list)
4955 (require 'org-pcomplete)
4956 (require 'org-src)
4957 (require 'org-footnote)
4959 ;; babel
4960 (require 'ob)
4961 (require 'ob-table)
4962 (require 'ob-lob)
4963 (require 'ob-ref)
4964 (require 'ob-tangle)
4965 (require 'ob-comint)
4966 (require 'ob-keys)
4968 ;;;###autoload
4969 (define-derived-mode org-mode outline-mode "Org"
4970 "Outline-based notes management and organizer, alias
4971 \"Carsten's outline-mode for keeping track of everything.\"
4973 Org-mode develops organizational tasks around a NOTES file which
4974 contains information about projects as plain text. Org-mode is
4975 implemented on top of outline-mode, which is ideal to keep the content
4976 of large files well structured. It supports ToDo items, deadlines and
4977 time stamps, which magically appear in the diary listing of the Emacs
4978 calendar. Tables are easily created with a built-in table editor.
4979 Plain text URL-like links connect to websites, emails (VM), Usenet
4980 messages (Gnus), BBDB entries, and any files related to the project.
4981 For printing and sharing of notes, an Org-mode file (or a part of it)
4982 can be exported as a structured ASCII or HTML file.
4984 The following commands are available:
4986 \\{org-mode-map}"
4988 ;; Get rid of Outline menus, they are not needed
4989 ;; Need to do this here because define-derived-mode sets up
4990 ;; the keymap so late. Still, it is a waste to call this each time
4991 ;; we switch another buffer into org-mode.
4992 (if (featurep 'xemacs)
4993 (when (boundp 'outline-mode-menu-heading)
4994 ;; Assume this is Greg's port, it uses easymenu
4995 (easy-menu-remove outline-mode-menu-heading)
4996 (easy-menu-remove outline-mode-menu-show)
4997 (easy-menu-remove outline-mode-menu-hide))
4998 (define-key org-mode-map [menu-bar headings] 'undefined)
4999 (define-key org-mode-map [menu-bar hide] 'undefined)
5000 (define-key org-mode-map [menu-bar show] 'undefined))
5002 (org-load-modules-maybe)
5003 (easy-menu-add org-org-menu)
5004 (easy-menu-add org-tbl-menu)
5005 (org-install-agenda-files-menu)
5006 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5007 (add-to-invisibility-spec '(org-cwidth))
5008 (add-to-invisibility-spec '(org-hide-block . t))
5009 (when (featurep 'xemacs)
5010 (org-set-local 'line-move-ignore-invisible t))
5011 (org-set-local 'outline-regexp org-outline-regexp)
5012 (org-set-local 'outline-level 'org-outline-level)
5013 (setq bidi-paragraph-direction 'left-to-right)
5014 (when (and org-ellipsis
5015 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5016 (fboundp 'make-glyph-code))
5017 (unless org-display-table
5018 (setq org-display-table (make-display-table)))
5019 (set-display-table-slot
5020 org-display-table 4
5021 (vconcat (mapcar
5022 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5023 org-ellipsis)))
5024 (if (stringp org-ellipsis) org-ellipsis "..."))))
5025 (setq buffer-display-table org-display-table))
5026 (org-set-regexps-and-options)
5027 (when (and org-tag-faces (not org-tags-special-faces-re))
5028 ;; tag faces set outside customize.... force initialization.
5029 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5030 ;; Calc embedded
5031 (org-set-local 'calc-embedded-open-mode "# ")
5032 (modify-syntax-entry ?@ "w")
5033 (if org-startup-truncated (setq truncate-lines t))
5034 (org-set-local 'font-lock-unfontify-region-function
5035 'org-unfontify-region)
5036 ;; Activate before-change-function
5037 (org-set-local 'org-table-may-need-update t)
5038 (org-add-hook 'before-change-functions 'org-before-change-function nil
5039 'local)
5040 ;; Check for running clock before killing a buffer
5041 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5042 ;; Indentation.
5043 (org-set-local 'indent-line-function 'org-indent-line)
5044 (org-set-local 'indent-region-function 'org-indent-region)
5045 ;; Initialize radio targets.
5046 (org-update-radio-target-regexp)
5047 ;; Filling and auto-filling.
5048 (org-setup-filling)
5049 ;; Comments.
5050 (org-setup-comments-handling)
5051 ;; Beginning/end of defun
5052 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5053 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5054 ;; Next error for sparse trees
5055 (org-set-local 'next-error-function 'org-occur-next-match)
5056 ;; Make sure dependence stuff works reliably, even for users who set it
5057 ;; too late :-(
5058 (if org-enforce-todo-dependencies
5059 (add-hook 'org-blocker-hook
5060 'org-block-todo-from-children-or-siblings-or-parent)
5061 (remove-hook 'org-blocker-hook
5062 'org-block-todo-from-children-or-siblings-or-parent))
5063 (if org-enforce-todo-checkbox-dependencies
5064 (add-hook 'org-blocker-hook
5065 'org-block-todo-from-checkboxes)
5066 (remove-hook 'org-blocker-hook
5067 'org-block-todo-from-checkboxes))
5069 ;; Align options lines
5070 (org-set-local
5071 'align-mode-rules-list
5072 '((org-in-buffer-settings
5073 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5074 (modes . '(org-mode)))))
5076 ;; Imenu
5077 (org-set-local 'imenu-create-index-function
5078 'org-imenu-get-tree)
5080 ;; Make isearch reveal context
5081 (if (or (featurep 'xemacs)
5082 (not (boundp 'outline-isearch-open-invisible-function)))
5083 ;; Emacs 21 and XEmacs make use of the hook
5084 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5085 ;; Emacs 22 deals with this through a special variable
5086 (org-set-local 'outline-isearch-open-invisible-function
5087 (lambda (&rest ignore) (org-show-context 'isearch))))
5089 ;; Turn on org-beamer-mode?
5090 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5092 ;; Setup the pcomplete hooks
5093 (set (make-local-variable 'pcomplete-command-completion-function)
5094 'org-pcomplete-initial)
5095 (set (make-local-variable 'pcomplete-command-name-function)
5096 'org-command-at-point)
5097 (set (make-local-variable 'pcomplete-default-completion-function)
5098 'ignore)
5099 (set (make-local-variable 'pcomplete-parse-arguments-function)
5100 'org-parse-arguments)
5101 (set (make-local-variable 'pcomplete-termination-string) "")
5102 (when (>= emacs-major-version 23)
5103 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5105 ;; If empty file that did not turn on org-mode automatically, make it to.
5106 (if (and org-insert-mode-line-in-empty-file
5107 (org-called-interactively-p 'any)
5108 (= (point-min) (point-max)))
5109 (insert "# -*- mode: org -*-\n\n"))
5110 (unless org-inhibit-startup
5111 (when org-startup-align-all-tables
5112 (let ((bmp (buffer-modified-p)))
5113 (org-table-map-tables 'org-table-align 'quietly)
5114 (set-buffer-modified-p bmp)))
5115 (when org-startup-with-inline-images
5116 (org-display-inline-images))
5117 (when org-startup-indented
5118 (require 'org-indent)
5119 (org-indent-mode 1))
5120 (unless org-inhibit-startup-visibility-stuff
5121 (org-set-startup-visibility)))
5122 ;; Try to set org-hide correctly
5123 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5125 (when (fboundp 'abbrev-table-put)
5126 (abbrev-table-put org-mode-abbrev-table
5127 :parents (list text-mode-abbrev-table)))
5129 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5132 (defun org-find-invisible-foreground ()
5133 (let ((candidates (remove
5134 "unspecified-bg"
5135 (list
5136 (face-background 'default)
5137 (face-background 'org-default)
5138 (cdr (assoc 'background-color default-frame-alist))
5139 (cdr (assoc 'background-color initial-frame-alist))
5140 (cdr (assoc 'background-color window-system-default-frame-alist))
5141 (face-foreground 'org-hide)))))
5142 (car (remove nil candidates))))
5144 (defun org-current-time ()
5145 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5146 (if (> (car org-time-stamp-rounding-minutes) 1)
5147 (let ((r (car org-time-stamp-rounding-minutes))
5148 (time (decode-time)))
5149 (apply 'encode-time
5150 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5151 (nthcdr 2 time))))
5152 (current-time)))
5154 (defun org-today ()
5155 "Return today date, considering `org-extend-today-until'."
5156 (time-to-days
5157 (time-subtract (current-time)
5158 (list 0 (* 3600 org-extend-today-until) 0))))
5160 ;;;; Font-Lock stuff, including the activators
5162 (defvar org-mouse-map (make-sparse-keymap))
5163 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5164 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5165 (when org-mouse-1-follows-link
5166 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5167 (when org-tab-follows-link
5168 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5169 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5171 (require 'font-lock)
5173 (defconst org-non-link-chars "]\t\n\r<>")
5174 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5175 "shell" "elisp" "doi" "message"))
5176 (defvar org-link-types-re nil
5177 "Matches a link that has a url-like prefix like \"http:\"")
5178 (defvar org-link-re-with-space nil
5179 "Matches a link with spaces, optional angular brackets around it.")
5180 (defvar org-link-re-with-space2 nil
5181 "Matches a link with spaces, optional angular brackets around it.")
5182 (defvar org-link-re-with-space3 nil
5183 "Matches a link with spaces, only for internal part in bracket links.")
5184 (defvar org-angle-link-re nil
5185 "Matches link with angular brackets, spaces are allowed.")
5186 (defvar org-plain-link-re nil
5187 "Matches plain link, without spaces.")
5188 (defvar org-bracket-link-regexp nil
5189 "Matches a link in double brackets.")
5190 (defvar org-bracket-link-analytic-regexp nil
5191 "Regular expression used to analyze links.
5192 Here is what the match groups contain after a match:
5193 1: http:
5194 2: http
5195 3: path
5196 4: [desc]
5197 5: desc")
5198 (defvar org-bracket-link-analytic-regexp++ nil
5199 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5200 (defvar org-any-link-re nil
5201 "Regular expression matching any link.")
5203 (defcustom org-match-sexp-depth 3
5204 "Number of stacked braces for sub/superscript matching.
5205 This has to be set before loading org.el to be effective."
5206 :group 'org-export-translation ; ??????????????????????????/
5207 :type 'integer)
5209 (defun org-create-multibrace-regexp (left right n)
5210 "Create a regular expression which will match a balanced sexp.
5211 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5212 as single character strings.
5213 The regexp returned will match the entire expression including the
5214 delimiters. It will also define a single group which contains the
5215 match except for the outermost delimiters. The maximum depth of
5216 stacked delimiters is N. Escaping delimiters is not possible."
5217 (let* ((nothing (concat "[^" left right "]*?"))
5218 (or "\\|")
5219 (re nothing)
5220 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5221 (while (> n 1)
5222 (setq n (1- n)
5223 re (concat re or next)
5224 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5225 (concat left "\\(" re "\\)" right)))
5227 (defvar org-match-substring-regexp
5228 (concat
5229 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5230 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5231 "\\|"
5232 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5233 "\\|"
5234 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5235 "The regular expression matching a sub- or superscript.")
5237 (defvar org-match-substring-with-braces-regexp
5238 (concat
5239 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5240 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5241 "\\)")
5242 "The regular expression matching a sub- or superscript, forcing braces.")
5244 (defun org-make-link-regexps ()
5245 "Update the link regular expressions.
5246 This should be called after the variable `org-link-types' has changed."
5247 (setq org-link-types-re
5248 (concat
5249 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5250 org-link-re-with-space
5251 (concat
5252 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5253 "\\([^" org-non-link-chars " ]"
5254 "[^" org-non-link-chars "]*"
5255 "[^" org-non-link-chars " ]\\)>?")
5256 org-link-re-with-space2
5257 (concat
5258 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5259 "\\([^" org-non-link-chars " ]"
5260 "[^\t\n\r]*"
5261 "[^" org-non-link-chars " ]\\)>?")
5262 org-link-re-with-space3
5263 (concat
5264 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5265 "\\([^" org-non-link-chars " ]"
5266 "[^\t\n\r]*\\)")
5267 org-angle-link-re
5268 (concat
5269 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5270 "\\([^" org-non-link-chars " ]"
5271 "[^" org-non-link-chars "]*"
5272 "\\)>")
5273 org-plain-link-re
5274 (concat
5275 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5276 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5277 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5278 org-bracket-link-regexp
5279 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5280 org-bracket-link-analytic-regexp
5281 (concat
5282 "\\[\\["
5283 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5284 "\\([^]]+\\)"
5285 "\\]"
5286 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5287 "\\]")
5288 org-bracket-link-analytic-regexp++
5289 (concat
5290 "\\[\\["
5291 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5292 "\\([^]]+\\)"
5293 "\\]"
5294 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5295 "\\]")
5296 org-any-link-re
5297 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5298 org-angle-link-re "\\)\\|\\("
5299 org-plain-link-re "\\)")))
5301 (org-make-link-regexps)
5303 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5304 "Regular expression for fast time stamp matching.")
5305 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5306 "Regular expression for fast time stamp matching.")
5307 (defconst org-ts-regexp0
5308 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5309 "Regular expression matching time strings for analysis.
5310 This one does not require the space after the date, so it can be used
5311 on a string that terminates immediately after the date.")
5312 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5313 "Regular expression matching time strings for analysis.")
5314 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5315 "Regular expression matching time stamps, with groups.")
5316 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5317 "Regular expression matching time stamps (also [..]), with groups.")
5318 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5319 "Regular expression matching a time stamp range.")
5320 (defconst org-tr-regexp-both
5321 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5322 "Regular expression matching a time stamp range.")
5323 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5324 org-ts-regexp "\\)?")
5325 "Regular expression matching a time stamp or time stamp range.")
5326 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5327 org-ts-regexp-both "\\)?")
5328 "Regular expression matching a time stamp or time stamp range.
5329 The time stamps may be either active or inactive.")
5331 (defvar org-emph-face nil)
5333 (defun org-do-emphasis-faces (limit)
5334 "Run through the buffer and add overlays to emphasized strings."
5335 (let (rtn a)
5336 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5337 (if (not (= (char-after (match-beginning 3))
5338 (char-after (match-beginning 4))))
5339 (progn
5340 (setq rtn t)
5341 (setq a (assoc (match-string 3) org-emphasis-alist))
5342 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5343 'face
5344 (nth 1 a))
5345 (and (nth 4 a)
5346 (org-remove-flyspell-overlays-in
5347 (match-beginning 0) (match-end 0)))
5348 (add-text-properties (match-beginning 2) (match-end 2)
5349 '(font-lock-multiline t org-emphasis t))
5350 (when org-hide-emphasis-markers
5351 (add-text-properties (match-end 4) (match-beginning 5)
5352 '(invisible org-link))
5353 (add-text-properties (match-beginning 3) (match-end 3)
5354 '(invisible org-link)))))
5355 (backward-char 1))
5356 rtn))
5358 (defun org-emphasize (&optional char)
5359 "Insert or change an emphasis, i.e. a font like bold or italic.
5360 If there is an active region, change that region to a new emphasis.
5361 If there is no region, just insert the marker characters and position
5362 the cursor between them.
5363 CHAR should be either the marker character, or the first character of the
5364 HTML tag associated with that emphasis. If CHAR is a space, the means
5365 to remove the emphasis of the selected region.
5366 If char is not given (for example in an interactive call) it
5367 will be prompted for."
5368 (interactive)
5369 (let ((eal org-emphasis-alist) e det
5370 (erc org-emphasis-regexp-components)
5371 (prompt "")
5372 (string "") beg end move tag c s)
5373 (if (org-region-active-p)
5374 (setq beg (region-beginning) end (region-end)
5375 string (buffer-substring beg end))
5376 (setq move t))
5378 (while (setq e (pop eal))
5379 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5380 c (aref tag 0))
5381 (push (cons c (string-to-char (car e))) det)
5382 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5383 (substring tag 1)))))
5384 (setq det (nreverse det))
5385 (unless char
5386 (message "%s" (concat "Emphasis marker or tag:" prompt))
5387 (setq char (read-char-exclusive)))
5388 (setq char (or (cdr (assoc char det)) char))
5389 (if (equal char ?\ )
5390 (setq s "" move nil)
5391 (unless (assoc (char-to-string char) org-emphasis-alist)
5392 (error "No such emphasis marker: \"%c\"" char))
5393 (setq s (char-to-string char)))
5394 (while (and (> (length string) 1)
5395 (equal (substring string 0 1) (substring string -1))
5396 (assoc (substring string 0 1) org-emphasis-alist))
5397 (setq string (substring string 1 -1)))
5398 (setq string (concat s string s))
5399 (if beg (delete-region beg end))
5400 (unless (or (bolp)
5401 (string-match (concat "[" (nth 0 erc) "\n]")
5402 (char-to-string (char-before (point)))))
5403 (insert " "))
5404 (unless (or (eobp)
5405 (string-match (concat "[" (nth 1 erc) "\n]")
5406 (char-to-string (char-after (point)))))
5407 (insert " ") (backward-char 1))
5408 (insert string)
5409 (and move (backward-char 1))))
5411 (defconst org-nonsticky-props
5412 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5414 (defsubst org-rear-nonsticky-at (pos)
5415 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5417 (defun org-activate-plain-links (limit)
5418 "Run through the buffer and add overlays to links."
5419 (catch 'exit
5420 (let (f)
5421 (when (re-search-forward (concat org-plain-link-re) limit t)
5422 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5423 (setq f (get-text-property (match-beginning 0) 'face))
5424 (if (or (eq f 'org-tag)
5425 (and (listp f) (memq 'org-tag f)))
5427 (add-text-properties (match-beginning 0) (match-end 0)
5428 (list 'mouse-face 'highlight
5429 'face 'org-link
5430 'keymap org-mouse-map))
5431 (org-rear-nonsticky-at (match-end 0)))
5432 t))))
5434 (defun org-activate-code (limit)
5435 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5436 (progn
5437 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5438 (remove-text-properties (match-beginning 0) (match-end 0)
5439 '(display t invisible t intangible t))
5440 t)))
5442 (defcustom org-src-fontify-natively nil
5443 "When non-nil, fontify code in code blocks."
5444 :type 'boolean
5445 :version "24.1"
5446 :group 'org-appearance
5447 :group 'org-babel)
5449 (defcustom org-allow-promoting-top-level-subtree nil
5450 "When non-nil, allow promoting a top level subtree.
5451 The leading star of the top level headline will be replaced
5452 by a #."
5453 :type 'boolean
5454 :version "24.1"
5455 :group 'org-appearance)
5457 (defun org-fontify-meta-lines-and-blocks (limit)
5458 (condition-case nil
5459 (org-fontify-meta-lines-and-blocks-1 limit)
5460 (error (message "org-mode fontification error"))))
5462 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5463 "Fontify #+ lines and blocks, in the correct ways."
5464 (let ((case-fold-search t))
5465 (if (re-search-forward
5466 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5467 limit t)
5468 (let ((beg (match-beginning 0))
5469 (block-start (match-end 0))
5470 (block-end nil)
5471 (lang (match-string 7))
5472 (beg1 (line-beginning-position 2))
5473 (dc1 (downcase (match-string 2)))
5474 (dc3 (downcase (match-string 3)))
5475 end end1 quoting block-type ovl)
5476 (cond
5477 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5478 ;; a single line of backend-specific content
5479 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5480 (remove-text-properties (match-beginning 0) (match-end 0)
5481 '(display t invisible t intangible t))
5482 (add-text-properties (match-beginning 1) (match-end 3)
5483 '(font-lock-fontified t face org-meta-line))
5484 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5485 '(font-lock-fontified t face org-block))
5486 ; for backend-specific code
5488 ((and (match-end 4) (equal dc3 "+begin"))
5489 ;; Truly a block
5490 (setq block-type (downcase (match-string 5))
5491 quoting (member block-type org-protecting-blocks))
5492 (when (re-search-forward
5493 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5494 nil t) ;; on purpose, we look further than LIMIT
5495 (setq end (min (point-max) (match-end 0))
5496 end1 (min (point-max) (1- (match-beginning 0))))
5497 (setq block-end (match-beginning 0))
5498 (when quoting
5499 (remove-text-properties beg end
5500 '(display t invisible t intangible t)))
5501 (add-text-properties
5502 beg end
5503 '(font-lock-fontified t font-lock-multiline t))
5504 (add-text-properties beg beg1 '(face org-meta-line))
5505 (add-text-properties end1 (min (point-max) (1+ end))
5506 '(face org-meta-line)) ; for end_src
5507 (cond
5508 ((and lang (not (string= lang "")) org-src-fontify-natively)
5509 (org-src-font-lock-fontify-block lang block-start block-end)
5510 ;; remove old background overlays
5511 (mapc (lambda (ov)
5512 (if (eq (overlay-get ov 'face) 'org-block-background)
5513 (delete-overlay ov)))
5514 (overlays-at (/ (+ beg1 block-end) 2)))
5515 ;; add a background overlay
5516 (setq ovl (make-overlay beg1 block-end))
5517 (overlay-put ovl 'face 'org-block-background)
5518 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5519 (quoting
5520 (add-text-properties beg1 (min (point-max) (1+ end1))
5521 '(face org-block))) ; end of source block
5522 ((not org-fontify-quote-and-verse-blocks))
5523 ((string= block-type "quote")
5524 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5525 ((string= block-type "verse")
5526 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5527 (add-text-properties beg beg1 '(face org-block-begin-line))
5528 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5529 '(face org-block-end-line))
5531 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5532 (add-text-properties
5533 beg (match-end 3)
5534 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5535 '(font-lock-fontified t invisible t)
5536 '(font-lock-fontified t face org-document-info-keyword)))
5537 (add-text-properties
5538 (match-beginning 6) (match-end 6)
5539 (if (string-equal dc1 "+title:")
5540 '(font-lock-fontified t face org-document-title)
5541 '(font-lock-fontified t face org-document-info))))
5542 ((or (equal dc1 "+results")
5543 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5544 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5545 "+call:" "+header:" "+headers:" "+name:"))
5546 (and (match-end 4) (equal dc3 "+attr")))
5547 (add-text-properties
5548 beg (match-end 0)
5549 '(font-lock-fontified t face org-meta-line))
5551 ((member dc3 '(" " ""))
5552 (add-text-properties
5553 beg (match-end 0)
5554 '(font-lock-fontified t face font-lock-comment-face)))
5555 ((not (member (char-after beg) '(?\ ?\t)))
5556 ;; just any other in-buffer setting, but not indented
5557 (add-text-properties
5558 beg (match-end 0)
5559 '(font-lock-fontified t face org-meta-line))
5561 (t nil))))))
5563 (defun org-strip-protective-commas (beg end)
5564 "Strip protective commas between BEG and END in the current buffer."
5565 (interactive "r")
5566 (save-excursion
5567 (save-match-data
5568 (goto-char beg)
5569 (let ((front-line (save-excursion
5570 (re-search-forward
5571 "[^[:space:]]" end t)
5572 (goto-char (match-beginning 0))
5573 (current-column))))
5574 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5575 (goto-char (match-beginning 1))
5576 (when (= (current-column) front-line)
5577 (replace-match "" nil nil nil 1)))))))
5579 (defun org-activate-angle-links (limit)
5580 "Run through the buffer and add overlays to links."
5581 (if (re-search-forward org-angle-link-re limit t)
5582 (progn
5583 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5584 (add-text-properties (match-beginning 0) (match-end 0)
5585 (list 'mouse-face 'highlight
5586 'keymap org-mouse-map))
5587 (org-rear-nonsticky-at (match-end 0))
5588 t)))
5590 (defun org-activate-footnote-links (limit)
5591 "Run through the buffer and add overlays to footnotes."
5592 (let ((fn (org-footnote-next-reference-or-definition limit)))
5593 (when fn
5594 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5595 (org-remove-flyspell-overlays-in beg end)
5596 (add-text-properties beg end
5597 (list 'mouse-face 'highlight
5598 'keymap org-mouse-map
5599 'help-echo
5600 (if (= (point-at-bol) beg)
5601 "Footnote definition"
5602 "Footnote reference")
5603 'font-lock-fontified t
5604 'font-lock-multiline t
5605 'face 'org-footnote))))))
5607 (defun org-activate-bracket-links (limit)
5608 "Run through the buffer and add overlays to bracketed links."
5609 (if (re-search-forward org-bracket-link-regexp limit t)
5610 (let* ((help (concat "LINK: "
5611 (org-match-string-no-properties 1)))
5612 ;; FIXME: above we should remove the escapes.
5613 ;; but that requires another match, protecting match data,
5614 ;; a lot of overhead for font-lock.
5615 (ip (org-maybe-intangible
5616 (list 'invisible 'org-link
5617 'keymap org-mouse-map 'mouse-face 'highlight
5618 'font-lock-multiline t 'help-echo help)))
5619 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5620 'font-lock-multiline t 'help-echo help)))
5621 ;; We need to remove the invisible property here. Table narrowing
5622 ;; may have made some of this invisible.
5623 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5624 (remove-text-properties (match-beginning 0) (match-end 0)
5625 '(invisible nil))
5626 (if (match-end 3)
5627 (progn
5628 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5629 (org-rear-nonsticky-at (match-beginning 3))
5630 (add-text-properties (match-beginning 3) (match-end 3) vp)
5631 (org-rear-nonsticky-at (match-end 3))
5632 (add-text-properties (match-end 3) (match-end 0) ip)
5633 (org-rear-nonsticky-at (match-end 0)))
5634 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5635 (org-rear-nonsticky-at (match-beginning 1))
5636 (add-text-properties (match-beginning 1) (match-end 1) vp)
5637 (org-rear-nonsticky-at (match-end 1))
5638 (add-text-properties (match-end 1) (match-end 0) ip)
5639 (org-rear-nonsticky-at (match-end 0)))
5640 t)))
5642 (defun org-activate-dates (limit)
5643 "Run through the buffer and add overlays to dates."
5644 (if (re-search-forward org-tsr-regexp-both limit t)
5645 (progn
5646 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5647 (add-text-properties (match-beginning 0) (match-end 0)
5648 (list 'mouse-face 'highlight
5649 'keymap org-mouse-map))
5650 (org-rear-nonsticky-at (match-end 0))
5651 (when org-display-custom-times
5652 (if (match-end 3)
5653 (org-display-custom-time (match-beginning 3) (match-end 3)))
5654 (org-display-custom-time (match-beginning 1) (match-end 1)))
5655 t)))
5657 (defvar org-target-link-regexp nil
5658 "Regular expression matching radio targets in plain text.")
5659 (make-variable-buffer-local 'org-target-link-regexp)
5660 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5661 "Regular expression matching a link target.")
5662 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5663 "Regular expression matching a radio target.")
5664 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5665 "Regular expression matching any target.")
5667 (defun org-activate-target-links (limit)
5668 "Run through the buffer and add overlays to target matches."
5669 (when org-target-link-regexp
5670 (let ((case-fold-search t))
5671 (if (re-search-forward org-target-link-regexp limit t)
5672 (progn
5673 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5674 (add-text-properties (match-beginning 0) (match-end 0)
5675 (list 'mouse-face 'highlight
5676 'keymap org-mouse-map
5677 'help-echo "Radio target link"
5678 'org-linked-text t))
5679 (org-rear-nonsticky-at (match-end 0))
5680 t)))))
5682 (defun org-update-radio-target-regexp ()
5683 "Find all radio targets in this file and update the regular expression."
5684 (interactive)
5685 (when (memq 'radio org-activate-links)
5686 (setq org-target-link-regexp
5687 (org-make-target-link-regexp (org-all-targets 'radio)))
5688 (org-restart-font-lock)))
5690 (defun org-hide-wide-columns (limit)
5691 (let (s e)
5692 (setq s (text-property-any (point) (or limit (point-max))
5693 'org-cwidth t))
5694 (when s
5695 (setq e (next-single-property-change s 'org-cwidth))
5696 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5697 (goto-char e)
5698 t)))
5700 (defvar org-latex-and-specials-regexp nil
5701 "Regular expression for highlighting export special stuff.")
5702 (defvar org-match-substring-regexp)
5703 (defvar org-match-substring-with-braces-regexp)
5705 ;; This should be with the exporter code, but we also use if for font-locking
5706 (defconst org-export-html-special-string-regexps
5707 '(("\\\\-" . "&shy;")
5708 ("---\\([^-]\\)" . "&mdash;\\1")
5709 ("--\\([^-]\\)" . "&ndash;\\1")
5710 ("\\.\\.\\." . "&hellip;"))
5711 "Regular expressions for special string conversion.")
5714 (defun org-compute-latex-and-specials-regexp ()
5715 "Compute regular expression for stuff treated specially by exporters."
5716 (if (not org-highlight-latex-fragments-and-specials)
5717 (org-set-local 'org-latex-and-specials-regexp nil)
5718 (require 'org-exp)
5719 (let*
5720 ((matchers (plist-get org-format-latex-options :matchers))
5721 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5722 org-latex-regexps)))
5723 (org-export-allow-BIND nil)
5724 (options (org-combine-plists (org-default-export-plist)
5725 (org-infile-export-plist)))
5726 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5727 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5728 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5729 (org-export-html-expand (plist-get options :expand-quoted-html))
5730 (org-export-with-special-strings (plist-get options :special-strings))
5731 (re-sub
5732 (cond
5733 ((equal org-export-with-sub-superscripts '{})
5734 (list org-match-substring-with-braces-regexp))
5735 (org-export-with-sub-superscripts
5736 (list org-match-substring-regexp))))
5737 (re-latex
5738 (if org-export-with-LaTeX-fragments
5739 (mapcar (lambda (x) (nth 1 x)) latexs)))
5740 (re-macros
5741 (if org-export-with-TeX-macros
5742 (list (concat "\\\\"
5743 (regexp-opt
5744 (append
5746 (delq nil
5747 (mapcar 'car-safe
5748 (append org-entities-user
5749 org-entities)))
5750 (if (boundp 'org-latex-entities)
5751 (mapcar (lambda (x)
5752 (or (car-safe x) x))
5753 org-latex-entities)
5754 nil))
5755 'words))) ; FIXME
5757 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5758 (re-special (if org-export-with-special-strings
5759 (mapcar (lambda (x) (car x))
5760 org-export-html-special-string-regexps)))
5761 (re-rest
5762 (delq nil
5763 (list
5764 (if org-export-html-expand "@<[^>\n]+>")
5765 ))))
5766 (org-set-local
5767 'org-latex-and-specials-regexp
5768 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5769 re-rest) "\\|")))))
5771 (defun org-do-latex-and-special-faces (limit)
5772 "Run through the buffer and add overlays to links."
5773 (when org-latex-and-specials-regexp
5774 (let (rtn d)
5775 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5776 limit t))
5777 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5778 'face))
5779 '(org-code org-verbatim underline)))
5780 (progn
5781 (setq rtn t
5782 d (cond ((member (char-after (1+ (match-beginning 0)))
5783 '(?_ ?^)) 1)
5784 (t 0)))
5785 (font-lock-prepend-text-property
5786 (+ d (match-beginning 0)) (match-end 0)
5787 'face 'org-latex-and-export-specials)
5788 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5789 '(font-lock-multiline t)))))
5790 rtn)))
5792 (defun org-restart-font-lock ()
5793 "Restart `font-lock-mode', to force refontification."
5794 (when (and (boundp 'font-lock-mode) font-lock-mode)
5795 (font-lock-mode -1)
5796 (font-lock-mode 1)))
5798 (defun org-all-targets (&optional radio)
5799 "Return a list of all targets in this file.
5800 With optional argument RADIO, only find radio targets."
5801 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5802 rtn)
5803 (save-excursion
5804 (goto-char (point-min))
5805 (while (re-search-forward re nil t)
5806 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5807 rtn)))
5809 (defun org-make-target-link-regexp (targets)
5810 "Make regular expression matching all strings in TARGETS.
5811 The regular expression finds the targets also if there is a line break
5812 between words."
5813 (and targets
5814 (concat
5815 "\\<\\("
5816 (mapconcat
5817 (lambda (x)
5818 (setq x (regexp-quote x))
5819 (while (string-match " +" x)
5820 (setq x (replace-match "\\s-+" t t x)))
5822 targets
5823 "\\|")
5824 "\\)\\>")))
5826 (defun org-activate-tags (limit)
5827 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5828 (progn
5829 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5830 (add-text-properties (match-beginning 1) (match-end 1)
5831 (list 'mouse-face 'highlight
5832 'keymap org-mouse-map))
5833 (org-rear-nonsticky-at (match-end 1))
5834 t)))
5836 (defun org-outline-level ()
5837 "Compute the outline level of the heading at point.
5838 This function assumes that the cursor is at the beginning of a line matched
5839 by `outline-regexp'. Otherwise it returns garbage.
5840 If this is called at a normal headline, the level is the number of stars.
5841 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5842 (save-excursion
5843 (looking-at org-outline-regexp)
5844 (1- (- (match-end 0) (match-beginning 0)))))
5846 (defvar org-font-lock-keywords nil)
5848 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5849 "Regular expression matching a property line.")
5851 (defvar org-font-lock-hook nil
5852 "Functions to be called for special font lock stuff.")
5854 (defvar org-font-lock-set-keywords-hook nil
5855 "Functions that can manipulate `org-font-lock-extra-keywords'.
5856 This is called after `org-font-lock-extra-keywords' is defined, but before
5857 it is installed to be used by font lock. This can be useful if something
5858 needs to be inserted at a specific position in the font-lock sequence.")
5860 (defun org-font-lock-hook (limit)
5861 "Run `org-font-lock-hook' within LIMIT."
5862 (run-hook-with-args 'org-font-lock-hook limit))
5864 (defun org-set-font-lock-defaults ()
5865 "Set font lock defaults for the current buffer."
5866 (let* ((em org-fontify-emphasized-text)
5867 (lk org-activate-links)
5868 (org-font-lock-extra-keywords
5869 (list
5870 ;; Call the hook
5871 '(org-font-lock-hook)
5872 ;; Headlines
5873 `(,(if org-fontify-whole-heading-line
5874 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5875 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5876 (1 (org-get-level-face 1))
5877 (2 (org-get-level-face 2))
5878 (3 (org-get-level-face 3)))
5879 ;; Table lines
5880 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5881 (1 'org-table t))
5882 ;; Table internals
5883 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5884 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5885 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5886 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5887 ;; Drawers
5888 (list org-drawer-regexp '(0 'org-special-keyword t))
5889 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5890 ;; Properties
5891 (list org-property-re
5892 '(1 'org-special-keyword t)
5893 '(3 'org-property-value t))
5894 ;; Links
5895 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5896 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5897 (if (memq 'plain lk) '(org-activate-plain-links))
5898 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5899 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5900 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5901 (if (memq 'footnote lk) '(org-activate-footnote-links))
5902 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5903 '(org-hide-wide-columns (0 nil append))
5904 ;; TODO keyword
5905 (list (format org-heading-keyword-regexp-format
5906 org-todo-regexp)
5907 '(2 (org-get-todo-face 2) t))
5908 ;; DONE
5909 (if org-fontify-done-headline
5910 (list (format org-heading-keyword-regexp-format
5911 (concat
5912 "\\(?:"
5913 (mapconcat 'regexp-quote org-done-keywords "\\|")
5914 "\\)"))
5915 '(2 'org-headline-done t))
5916 nil)
5917 ;; Priorities
5918 '(org-font-lock-add-priority-faces)
5919 ;; Tags
5920 '(org-font-lock-add-tag-faces)
5921 ;; Special keywords
5922 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5923 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5924 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5925 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5926 ;; Emphasis
5927 (if em
5928 (if (featurep 'xemacs)
5929 '(org-do-emphasis-faces (0 nil append))
5930 '(org-do-emphasis-faces)))
5931 ;; Checkboxes
5932 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5933 1 'org-checkbox prepend)
5934 (if (cdr (assq 'checkbox org-list-automatic-rules))
5935 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5936 (0 (org-get-checkbox-statistics-face) t)))
5937 ;; Description list items
5938 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5939 1 'org-list-dt prepend)
5940 ;; ARCHIVEd headings
5941 (list (concat
5942 org-outline-regexp-bol
5943 "\\(.*:" org-archive-tag ":.*\\)")
5944 '(1 'org-archived prepend))
5945 ;; Specials
5946 '(org-do-latex-and-special-faces)
5947 '(org-fontify-entities)
5948 '(org-raise-scripts)
5949 ;; Code
5950 '(org-activate-code (1 'org-code t))
5951 ;; COMMENT
5952 (list (format org-heading-keyword-regexp-format
5953 (concat "\\("
5954 org-comment-string "\\|" org-quote-string
5955 "\\)"))
5956 '(2 'org-special-keyword t))
5957 ;; Blocks and meta lines
5958 '(org-fontify-meta-lines-and-blocks)
5960 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5961 (run-hooks 'org-font-lock-set-keywords-hook)
5962 ;; Now set the full font-lock-keywords
5963 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5964 (org-set-local 'font-lock-defaults
5965 '(org-font-lock-keywords t nil nil backward-paragraph))
5966 (kill-local-variable 'font-lock-keywords) nil))
5968 (defun org-toggle-pretty-entities ()
5969 "Toggle the composition display of entities as UTF8 characters."
5970 (interactive)
5971 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5972 (org-restart-font-lock)
5973 (if org-pretty-entities
5974 (message "Entities are displayed as UTF8 characters")
5975 (save-restriction
5976 (widen)
5977 (org-decompose-region (point-min) (point-max))
5978 (message "Entities are displayed plain"))))
5980 (defvar org-custom-properties-overlays nil
5981 "List of overlays used for custom properties.")
5982 (make-variable-buffer-local 'org-custom-properties-overlays)
5984 (defun org-toggle-custom-properties-visibility ()
5985 "Display or hide properties in `org-custom-properties'."
5986 (interactive)
5987 (if org-custom-properties-overlays
5988 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5989 (setq org-custom-properties-overlays nil))
5990 (unless (not org-custom-properties)
5991 (save-excursion
5992 (save-restriction
5993 (widen)
5994 (goto-char (point-min))
5995 (while (re-search-forward org-property-re nil t)
5996 (mapc (lambda(p)
5997 (when (equal p (substring (match-string 1) 1 -1))
5998 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5999 (overlay-put o 'invisible t)
6000 (overlay-put o 'org-custom-property t)
6001 (push o org-custom-properties-overlays))))
6002 org-custom-properties)))))))
6004 (defun org-fontify-entities (limit)
6005 "Find an entity to fontify."
6006 (let (ee)
6007 (when org-pretty-entities
6008 (catch 'match
6009 (while (re-search-forward
6010 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6011 limit t)
6012 (if (and (not (org-in-indented-comment-line))
6013 (setq ee (org-entity-get (match-string 1)))
6014 (= (length (nth 6 ee)) 1))
6015 (let*
6016 ((end (if (equal (match-string 2) "{}")
6017 (match-end 2)
6018 (match-end 1))))
6019 (add-text-properties
6020 (match-beginning 0) end
6021 (list 'font-lock-fontified t))
6022 (compose-region (match-beginning 0) end
6023 (nth 6 ee) nil)
6024 (backward-char 1)
6025 (throw 'match t))))
6026 nil))))
6028 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6029 "Fontify string S like in Org-mode."
6030 (with-temp-buffer
6031 (insert s)
6032 (let ((org-odd-levels-only odd-levels))
6033 (org-mode)
6034 (font-lock-fontify-buffer)
6035 (buffer-string))))
6037 (defvar org-m nil)
6038 (defvar org-l nil)
6039 (defvar org-f nil)
6040 (defun org-get-level-face (n)
6041 "Get the right face for match N in font-lock matching of headlines."
6042 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6043 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6044 (if org-cycle-level-faces
6045 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6046 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6047 (cond
6048 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6049 ((eq n 2) org-f)
6050 (t (if org-level-color-stars-only nil org-f))))
6053 (defun org-get-todo-face (kwd)
6054 "Get the right face for a TODO keyword KWD.
6055 If KWD is a number, get the corresponding match group."
6056 (if (numberp kwd) (setq kwd (match-string kwd)))
6057 (or (org-face-from-face-or-color
6058 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6059 (and (member kwd org-done-keywords) 'org-done)
6060 'org-todo))
6062 (defun org-face-from-face-or-color (context inherit face-or-color)
6063 "Create a face list that inherits INHERIT, but sets the foreground color.
6064 When FACE-OR-COLOR is not a string, just return it."
6065 (if (stringp face-or-color)
6066 (list :inherit inherit
6067 (cdr (assoc context org-faces-easy-properties))
6068 face-or-color)
6069 face-or-color))
6071 (defun org-font-lock-add-tag-faces (limit)
6072 "Add the special tag faces."
6073 (when (and org-tag-faces org-tags-special-faces-re)
6074 (while (re-search-forward org-tags-special-faces-re limit t)
6075 (add-text-properties (match-beginning 1) (match-end 1)
6076 (list 'face (org-get-tag-face 1)
6077 'font-lock-fontified t))
6078 (backward-char 1))))
6080 (defun org-font-lock-add-priority-faces (limit)
6081 "Add the special priority faces."
6082 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6083 (when (save-match-data (org-at-heading-p))
6084 (add-text-properties
6085 (match-beginning 0) (match-end 0)
6086 (list 'face (or (org-face-from-face-or-color
6087 'priority 'org-special-keyword
6088 (cdr (assoc (char-after (match-beginning 1))
6089 org-priority-faces)))
6090 'org-special-keyword)
6091 'font-lock-fontified t)))))
6093 (defun org-get-tag-face (kwd)
6094 "Get the right face for a TODO keyword KWD.
6095 If KWD is a number, get the corresponding match group."
6096 (if (numberp kwd) (setq kwd (match-string kwd)))
6097 (or (org-face-from-face-or-color
6098 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6099 'org-tag))
6101 (defun org-unfontify-region (beg end &optional maybe_loudly)
6102 "Remove fontification and activation overlays from links."
6103 (font-lock-default-unfontify-region beg end)
6104 (let* ((buffer-undo-list t)
6105 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6106 (inhibit-modification-hooks t)
6107 deactivate-mark buffer-file-name buffer-file-truename)
6108 (org-decompose-region beg end)
6109 (remove-text-properties beg end
6110 '(mouse-face t keymap t org-linked-text t
6111 invisible t intangible t
6112 org-no-flyspell t org-emphasis t))
6113 (org-remove-font-lock-display-properties beg end)))
6115 (defconst org-script-display '(((raise -0.3) (height 0.7))
6116 ((raise 0.3) (height 0.7))
6117 ((raise -0.5))
6118 ((raise 0.5)))
6119 "Display properties for showing superscripts and subscripts.")
6121 (defun org-remove-font-lock-display-properties (beg end)
6122 "Remove specific display properties that have been added by font lock.
6123 The will remove the raise properties that are used to show superscripts
6124 and subscripts."
6125 (let (next prop)
6126 (while (< beg end)
6127 (setq next (next-single-property-change beg 'display nil end)
6128 prop (get-text-property beg 'display))
6129 (if (member prop org-script-display)
6130 (put-text-property beg next 'display nil))
6131 (setq beg next))))
6133 (defun org-raise-scripts (limit)
6134 "Add raise properties to sub/superscripts."
6135 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6136 (if (re-search-forward
6137 (if (eq org-use-sub-superscripts t)
6138 org-match-substring-regexp
6139 org-match-substring-with-braces-regexp)
6140 limit t)
6141 (let* ((pos (point)) table-p comment-p
6142 (mpos (match-beginning 3))
6143 (emph-p (get-text-property mpos 'org-emphasis))
6144 (link-p (get-text-property mpos 'mouse-face))
6145 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6146 (goto-char (point-at-bol))
6147 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6148 comment-p (org-looking-at-p "[ \t]*#"))
6149 (goto-char pos)
6150 ;; FIXME: Should we go back one character here, for a_b^c
6151 ;; (goto-char (1- pos)) ;????????????????????
6152 (if (or comment-p emph-p link-p keyw-p)
6154 (put-text-property (match-beginning 3) (match-end 0)
6155 'display
6156 (if (equal (char-after (match-beginning 2)) ?^)
6157 (nth (if table-p 3 1) org-script-display)
6158 (nth (if table-p 2 0) org-script-display)))
6159 (add-text-properties (match-beginning 2) (match-end 2)
6160 (list 'invisible t
6161 'org-dwidth t 'org-dwidth-n 1))
6162 (if (and (eq (char-after (match-beginning 3)) ?{)
6163 (eq (char-before (match-end 3)) ?}))
6164 (progn
6165 (add-text-properties
6166 (match-beginning 3) (1+ (match-beginning 3))
6167 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6168 (add-text-properties
6169 (1- (match-end 3)) (match-end 3)
6170 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6171 t)))))
6173 ;;;; Visibility cycling, including org-goto and indirect buffer
6175 ;;; Cycling
6177 (defvar org-cycle-global-status nil)
6178 (make-variable-buffer-local 'org-cycle-global-status)
6179 (defvar org-cycle-subtree-status nil)
6180 (make-variable-buffer-local 'org-cycle-subtree-status)
6182 (defvar org-inlinetask-min-level)
6184 ;;;###autoload
6185 (defun org-cycle (&optional arg)
6186 "TAB-action and visibility cycling for Org-mode.
6188 This is the command invoked in Org-mode by the TAB key. Its main purpose
6189 is outline visibility cycling, but it also invokes other actions
6190 in special contexts.
6192 - When this function is called with a prefix argument, rotate the entire
6193 buffer through 3 states (global cycling)
6194 1. OVERVIEW: Show only top-level headlines.
6195 2. CONTENTS: Show all headlines of all levels, but no body text.
6196 3. SHOW ALL: Show everything.
6197 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6198 determined by the variable `org-startup-folded', and by any VISIBILITY
6199 properties in the buffer.
6200 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6201 including any drawers.
6203 - When inside a table, re-align the table and move to the next field.
6205 - When point is at the beginning of a headline, rotate the subtree started
6206 by this line through 3 different states (local cycling)
6207 1. FOLDED: Only the main headline is shown.
6208 2. CHILDREN: The main headline and the direct children are shown.
6209 From this state, you can move to one of the children
6210 and zoom in further.
6211 3. SUBTREE: Show the entire subtree, including body text.
6212 If there is no subtree, switch directly from CHILDREN to FOLDED.
6214 - When point is at the beginning of an empty headline and the variable
6215 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6216 of the headline by demoting and promoting it to likely levels. This
6217 speeds up creation document structure by pressing TAB once or several
6218 times right after creating a new headline.
6220 - When there is a numeric prefix, go up to a heading with level ARG, do
6221 a `show-subtree' and return to the previous cursor position. If ARG
6222 is negative, go up that many levels.
6224 - When point is not at the beginning of a headline, execute the global
6225 binding for TAB, which is re-indenting the line. See the option
6226 `org-cycle-emulate-tab' for details.
6228 - Special case: if point is at the beginning of the buffer and there is
6229 no headline in line 1, this function will act as if called with prefix arg
6230 (C-u TAB, same as S-TAB) also when called without prefix arg.
6231 But only if also the variable `org-cycle-global-at-bob' is t."
6232 (interactive "P")
6233 (org-load-modules-maybe)
6234 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6235 (and org-cycle-level-after-item/entry-creation
6236 (or (org-cycle-level)
6237 (org-cycle-item-indentation))))
6238 (let* ((limit-level
6239 (or org-cycle-max-level
6240 (and (boundp 'org-inlinetask-min-level)
6241 org-inlinetask-min-level
6242 (1- org-inlinetask-min-level))))
6243 (nstars (and limit-level
6244 (if org-odd-levels-only
6245 (and limit-level (1- (* limit-level 2)))
6246 limit-level)))
6247 (org-outline-regexp
6248 (if (not (derived-mode-p 'org-mode))
6249 outline-regexp
6250 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6251 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6252 (not (looking-at org-outline-regexp))))
6253 (org-cycle-hook
6254 (if bob-special
6255 (delq 'org-optimize-window-after-visibility-change
6256 (copy-sequence org-cycle-hook))
6257 org-cycle-hook))
6258 (pos (point)))
6260 (if (or bob-special (equal arg '(4)))
6261 ;; special case: use global cycling
6262 (setq arg t))
6264 (cond
6266 ((equal arg '(16))
6267 (setq last-command 'dummy)
6268 (org-set-startup-visibility)
6269 (message "Startup visibility, plus VISIBILITY properties"))
6271 ((equal arg '(64))
6272 (show-all)
6273 (message "Entire buffer visible, including drawers"))
6275 ;; Table: enter it or move to the next field.
6276 ((org-at-table-p 'any)
6277 (if (org-at-table.el-p)
6278 (message "Use C-c ' to edit table.el tables")
6279 (if arg (org-table-edit-field t)
6280 (org-table-justify-field-maybe)
6281 (call-interactively 'org-table-next-field))))
6283 ((run-hook-with-args-until-success
6284 'org-tab-after-check-for-table-hook))
6286 ;; Global cycling: delegate to `org-cycle-internal-global'.
6287 ((eq arg t) (org-cycle-internal-global))
6289 ;; Drawers: delegate to `org-flag-drawer'.
6290 ((and org-drawers org-drawer-regexp
6291 (save-excursion
6292 (beginning-of-line 1)
6293 (looking-at org-drawer-regexp)))
6294 (org-flag-drawer ; toggle block visibility
6295 (not (get-char-property (match-end 0) 'invisible))))
6297 ;; Show-subtree, ARG levels up from here.
6298 ((integerp arg)
6299 (save-excursion
6300 (org-back-to-heading)
6301 (outline-up-heading (if (< arg 0) (- arg)
6302 (- (funcall outline-level) arg)))
6303 (org-show-subtree)))
6305 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6306 ((and (featurep 'org-inlinetask)
6307 (org-inlinetask-at-task-p)
6308 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6309 (org-inlinetask-toggle-visibility))
6311 ((org-try-cdlatex-tab))
6313 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6314 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6315 (save-excursion (beginning-of-line 1)
6316 (looking-at org-outline-regexp)))
6317 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6318 (org-cycle-internal-local))
6320 ;; From there: TAB emulation and template completion.
6321 (buffer-read-only (org-back-to-heading))
6323 ((run-hook-with-args-until-success
6324 'org-tab-after-check-for-cycling-hook))
6326 ((org-try-structure-completion))
6328 ((run-hook-with-args-until-success
6329 'org-tab-before-tab-emulation-hook))
6331 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6332 (or (not (bolp))
6333 (not (looking-at org-outline-regexp))))
6334 (call-interactively (global-key-binding "\t")))
6336 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6337 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6338 (or (and (eq org-cycle-emulate-tab 'white)
6339 (= (match-end 0) (point-at-eol)))
6340 (and (eq org-cycle-emulate-tab 'whitestart)
6341 (>= (match-end 0) pos))))
6343 (eq org-cycle-emulate-tab t))
6344 (call-interactively (global-key-binding "\t")))
6346 (t (save-excursion
6347 (org-back-to-heading)
6348 (org-cycle)))))))
6350 (defun org-cycle-internal-global ()
6351 "Do the global cycling action."
6352 ;; Hack to avoid display of messages for .org attachments in Gnus
6353 (let ((ga (string-match "\\*fontification" (buffer-name))))
6354 (cond
6355 ((and (eq last-command this-command)
6356 (eq org-cycle-global-status 'overview))
6357 ;; We just created the overview - now do table of contents
6358 ;; This can be slow in very large buffers, so indicate action
6359 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6360 (unless ga (message "CONTENTS..."))
6361 (org-content)
6362 (unless ga (message "CONTENTS...done"))
6363 (setq org-cycle-global-status 'contents)
6364 (run-hook-with-args 'org-cycle-hook 'contents))
6366 ((and (eq last-command this-command)
6367 (eq org-cycle-global-status 'contents))
6368 ;; We just showed the table of contents - now show everything
6369 (run-hook-with-args 'org-pre-cycle-hook 'all)
6370 (show-all)
6371 (unless ga (message "SHOW ALL"))
6372 (setq org-cycle-global-status 'all)
6373 (run-hook-with-args 'org-cycle-hook 'all))
6376 ;; Default action: go to overview
6377 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6378 (org-overview)
6379 (unless ga (message "OVERVIEW"))
6380 (setq org-cycle-global-status 'overview)
6381 (run-hook-with-args 'org-cycle-hook 'overview)))))
6383 (defun org-cycle-internal-local ()
6384 "Do the local cycling action."
6385 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6386 ;; First, determine end of headline (EOH), end of subtree or item
6387 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6388 (save-excursion
6389 (if (org-at-item-p)
6390 (progn
6391 (beginning-of-line)
6392 (setq struct (org-list-struct))
6393 (setq eoh (point-at-eol))
6394 (setq eos (org-list-get-item-end-before-blank (point) struct))
6395 (setq has-children (org-list-has-child-p (point) struct)))
6396 (org-back-to-heading)
6397 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6398 (setq eos (save-excursion
6399 (org-end-of-subtree t)
6400 (unless (eobp)
6401 (skip-chars-forward " \t\n"))
6402 (if (eobp) (point) (1- (point)))))
6403 (setq has-children
6404 (or (save-excursion
6405 (let ((level (funcall outline-level)))
6406 (outline-next-heading)
6407 (and (org-at-heading-p t)
6408 (> (funcall outline-level) level))))
6409 (save-excursion
6410 (org-list-search-forward (org-item-beginning-re) eos t)))))
6411 ;; Determine end invisible part of buffer (EOL)
6412 (beginning-of-line 2)
6413 ;; XEmacs doesn't have `next-single-char-property-change'
6414 (if (featurep 'xemacs)
6415 (while (and (not (eobp)) ;; this is like `next-line'
6416 (get-char-property (1- (point)) 'invisible))
6417 (beginning-of-line 2))
6418 (while (and (not (eobp)) ;; this is like `next-line'
6419 (get-char-property (1- (point)) 'invisible))
6420 (goto-char (next-single-char-property-change (point) 'invisible))
6421 (and (eolp) (beginning-of-line 2))))
6422 (setq eol (point)))
6423 ;; Find out what to do next and set `this-command'
6424 (cond
6425 ((= eos eoh)
6426 ;; Nothing is hidden behind this heading
6427 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6428 (message "EMPTY ENTRY")
6429 (setq org-cycle-subtree-status nil)
6430 (save-excursion
6431 (goto-char eos)
6432 (outline-next-heading)
6433 (if (outline-invisible-p) (org-flag-heading nil))))
6434 ((and (or (>= eol eos)
6435 (not (string-match "\\S-" (buffer-substring eol eos))))
6436 (or has-children
6437 (not (setq children-skipped
6438 org-cycle-skip-children-state-if-no-children))))
6439 ;; Entire subtree is hidden in one line: children view
6440 (run-hook-with-args 'org-pre-cycle-hook 'children)
6441 (if (org-at-item-p)
6442 (org-list-set-item-visibility (point-at-bol) struct 'children)
6443 (org-show-entry)
6444 (org-with-limited-levels (show-children))
6445 ;; FIXME: This slows down the func way too much.
6446 ;; How keep drawers hidden in subtree anyway?
6447 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6448 ;; (org-cycle-hide-drawers 'subtree))
6450 ;; Fold every list in subtree to top-level items.
6451 (when (eq org-cycle-include-plain-lists 'integrate)
6452 (save-excursion
6453 (org-back-to-heading)
6454 (while (org-list-search-forward (org-item-beginning-re) eos t)
6455 (beginning-of-line 1)
6456 (let* ((struct (org-list-struct))
6457 (prevs (org-list-prevs-alist struct))
6458 (end (org-list-get-bottom-point struct)))
6459 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6460 (org-list-get-all-items (point) struct prevs))
6461 (goto-char end))))))
6462 (message "CHILDREN")
6463 (save-excursion
6464 (goto-char eos)
6465 (outline-next-heading)
6466 (if (outline-invisible-p) (org-flag-heading nil)))
6467 (setq org-cycle-subtree-status 'children)
6468 (run-hook-with-args 'org-cycle-hook 'children))
6469 ((or children-skipped
6470 (and (eq last-command this-command)
6471 (eq org-cycle-subtree-status 'children)))
6472 ;; We just showed the children, or no children are there,
6473 ;; now show everything.
6474 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6475 (outline-flag-region eoh eos nil)
6476 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6477 (setq org-cycle-subtree-status 'subtree)
6478 (run-hook-with-args 'org-cycle-hook 'subtree))
6480 ;; Default action: hide the subtree.
6481 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6482 (outline-flag-region eoh eos t)
6483 (message "FOLDED")
6484 (setq org-cycle-subtree-status 'folded)
6485 (run-hook-with-args 'org-cycle-hook 'folded)))))
6487 ;;;###autoload
6488 (defun org-global-cycle (&optional arg)
6489 "Cycle the global visibility. For details see `org-cycle'.
6490 With \\[universal-argument] prefix arg, switch to startup visibility.
6491 With a numeric prefix, show all headlines up to that level."
6492 (interactive "P")
6493 (let ((org-cycle-include-plain-lists
6494 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6495 (cond
6496 ((integerp arg)
6497 (show-all)
6498 (hide-sublevels arg)
6499 (setq org-cycle-global-status 'contents))
6500 ((equal arg '(4))
6501 (org-set-startup-visibility)
6502 (message "Startup visibility, plus VISIBILITY properties."))
6504 (org-cycle '(4))))))
6506 (defun org-set-startup-visibility ()
6507 "Set the visibility required by startup options and properties."
6508 (cond
6509 ((eq org-startup-folded t)
6510 (org-cycle '(4)))
6511 ((eq org-startup-folded 'content)
6512 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6513 (org-cycle '(4)) (org-cycle '(4)))))
6514 (unless (eq org-startup-folded 'showeverything)
6515 (if org-hide-block-startup (org-hide-block-all))
6516 (org-set-visibility-according-to-property 'no-cleanup)
6517 (org-cycle-hide-archived-subtrees 'all)
6518 (org-cycle-hide-drawers 'all)
6519 (org-cycle-show-empty-lines t)))
6521 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6522 "Switch subtree visibilities according to :VISIBILITY: property."
6523 (interactive)
6524 (let (org-show-entry-below state)
6525 (save-excursion
6526 (goto-char (point-min))
6527 (while (re-search-forward
6528 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6529 nil t)
6530 (setq state (match-string 1))
6531 (save-excursion
6532 (org-back-to-heading t)
6533 (hide-subtree)
6534 (org-reveal)
6535 (cond
6536 ((equal state '("fold" "folded"))
6537 (hide-subtree))
6538 ((equal state "children")
6539 (org-show-hidden-entry)
6540 (show-children))
6541 ((equal state "content")
6542 (save-excursion
6543 (save-restriction
6544 (org-narrow-to-subtree)
6545 (org-content))))
6546 ((member state '("all" "showall"))
6547 (show-subtree)))))
6548 (unless no-cleanup
6549 (org-cycle-hide-archived-subtrees 'all)
6550 (org-cycle-hide-drawers 'all)
6551 (org-cycle-show-empty-lines 'all)))))
6553 ;; This function uses outline-regexp instead of the more fundamental
6554 ;; org-outline-regexp so that org-cycle-global works outside of Org
6555 ;; buffers, where outline-regexp is needed.
6556 (defun org-overview ()
6557 "Switch to overview mode, showing only top-level headlines.
6558 Really, this shows all headlines with level equal or greater than the level
6559 of the first headline in the buffer. This is important, because if the
6560 first headline is not level one, then (hide-sublevels 1) gives confusing
6561 results."
6562 (interactive)
6563 (let ((level (save-excursion
6564 (goto-char (point-min))
6565 (if (re-search-forward (concat "^" outline-regexp) nil t)
6566 (progn
6567 (goto-char (match-beginning 0))
6568 (funcall outline-level))))))
6569 (and level (hide-sublevels level))))
6571 (defun org-content (&optional arg)
6572 "Show all headlines in the buffer, like a table of contents.
6573 With numerical argument N, show content up to level N."
6574 (interactive "P")
6575 (save-excursion
6576 ;; Visit all headings and show their offspring
6577 (and (integerp arg) (org-overview))
6578 (goto-char (point-max))
6579 (catch 'exit
6580 (while (and (progn (condition-case nil
6581 (outline-previous-visible-heading 1)
6582 (error (goto-char (point-min))))
6584 (looking-at org-outline-regexp))
6585 (if (integerp arg)
6586 (show-children (1- arg))
6587 (show-branches))
6588 (if (bobp) (throw 'exit nil))))))
6591 (defun org-optimize-window-after-visibility-change (state)
6592 "Adjust the window after a change in outline visibility.
6593 This function is the default value of the hook `org-cycle-hook'."
6594 (when (get-buffer-window (current-buffer))
6595 (cond
6596 ((eq state 'content) nil)
6597 ((eq state 'all) nil)
6598 ((eq state 'folded) nil)
6599 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6600 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6602 (defun org-remove-empty-overlays-at (pos)
6603 "Remove outline overlays that do not contain non-white stuff."
6604 (mapc
6605 (lambda (o)
6606 (and (eq 'outline (overlay-get o 'invisible))
6607 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6608 (overlay-end o))))
6609 (delete-overlay o)))
6610 (overlays-at pos)))
6612 (defun org-clean-visibility-after-subtree-move ()
6613 "Fix visibility issues after moving a subtree."
6614 ;; First, find a reasonable region to look at:
6615 ;; Start two siblings above, end three below
6616 (let* ((beg (save-excursion
6617 (and (org-get-last-sibling)
6618 (org-get-last-sibling))
6619 (point)))
6620 (end (save-excursion
6621 (and (org-get-next-sibling)
6622 (org-get-next-sibling)
6623 (org-get-next-sibling))
6624 (if (org-at-heading-p)
6625 (point-at-eol)
6626 (point))))
6627 (level (looking-at "\\*+"))
6628 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6629 (save-excursion
6630 (save-restriction
6631 (narrow-to-region beg end)
6632 (when re
6633 ;; Properly fold already folded siblings
6634 (goto-char (point-min))
6635 (while (re-search-forward re nil t)
6636 (if (and (not (outline-invisible-p))
6637 (save-excursion
6638 (goto-char (point-at-eol)) (outline-invisible-p)))
6639 (hide-entry))))
6640 (org-cycle-show-empty-lines 'overview)
6641 (org-cycle-hide-drawers 'overview)))))
6643 (defun org-cycle-show-empty-lines (state)
6644 "Show empty lines above all visible headlines.
6645 The region to be covered depends on STATE when called through
6646 `org-cycle-hook'. Lisp program can use t for STATE to get the
6647 entire buffer covered. Note that an empty line is only shown if there
6648 are at least `org-cycle-separator-lines' empty lines before the headline."
6649 (when (not (= org-cycle-separator-lines 0))
6650 (save-excursion
6651 (let* ((n (abs org-cycle-separator-lines))
6652 (re (cond
6653 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6654 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6655 (t (let ((ns (number-to-string (- n 2))))
6656 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6657 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6658 beg end b e)
6659 (cond
6660 ((memq state '(overview contents t))
6661 (setq beg (point-min) end (point-max)))
6662 ((memq state '(children folded))
6663 (setq beg (point) end (progn (org-end-of-subtree t t)
6664 (beginning-of-line 2)
6665 (point)))))
6666 (when beg
6667 (goto-char beg)
6668 (while (re-search-forward re end t)
6669 (unless (get-char-property (match-end 1) 'invisible)
6670 (setq e (match-end 1))
6671 (if (< org-cycle-separator-lines 0)
6672 (setq b (save-excursion
6673 (goto-char (match-beginning 0))
6674 (org-back-over-empty-lines)
6675 (if (save-excursion
6676 (goto-char (max (point-min) (1- (point))))
6677 (org-at-heading-p))
6678 (1- (point))
6679 (point))))
6680 (setq b (match-beginning 1)))
6681 (outline-flag-region b e nil)))))))
6682 ;; Never hide empty lines at the end of the file.
6683 (save-excursion
6684 (goto-char (point-max))
6685 (outline-previous-heading)
6686 (outline-end-of-heading)
6687 (if (and (looking-at "[ \t\n]+")
6688 (= (match-end 0) (point-max)))
6689 (outline-flag-region (point) (match-end 0) nil))))
6691 (defun org-show-empty-lines-in-parent ()
6692 "Move to the parent and re-show empty lines before visible headlines."
6693 (save-excursion
6694 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6695 (org-cycle-show-empty-lines context))))
6697 (defun org-files-list ()
6698 "Return `org-agenda-files' list, plus all open org-mode files.
6699 This is useful for operations that need to scan all of a user's
6700 open and agenda-wise Org files."
6701 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6702 (dolist (buf (buffer-list))
6703 (with-current-buffer buf
6704 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6705 (let ((file (expand-file-name (buffer-file-name))))
6706 (unless (member file files)
6707 (push file files))))))
6708 files))
6710 (defsubst org-entry-beginning-position ()
6711 "Return the beginning position of the current entry."
6712 (save-excursion (outline-back-to-heading t) (point)))
6714 (defsubst org-entry-end-position ()
6715 "Return the end position of the current entry."
6716 (save-excursion (outline-next-heading) (point)))
6718 (defun org-cycle-hide-drawers (state)
6719 "Re-hide all drawers after a visibility state change."
6720 (when (and (derived-mode-p 'org-mode)
6721 (not (memq state '(overview folded contents))))
6722 (save-excursion
6723 (let* ((globalp (memq state '(contents all)))
6724 (beg (if globalp (point-min) (point)))
6725 (end (if globalp (point-max)
6726 (if (eq state 'children)
6727 (save-excursion (outline-next-heading) (point))
6728 (org-end-of-subtree t)))))
6729 (goto-char beg)
6730 (while (re-search-forward org-drawer-regexp end t)
6731 (org-flag-drawer t))))))
6733 (defun org-flag-drawer (flag)
6734 "When FLAG is non-nil, hide the drawer we are within.
6735 Otherwise make it visible."
6736 (save-excursion
6737 (beginning-of-line 1)
6738 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6739 (let ((b (match-end 0)))
6740 (if (re-search-forward
6741 "^[ \t]*:END:"
6742 (save-excursion (outline-next-heading) (point)) t)
6743 (outline-flag-region b (point-at-eol) flag)
6744 (error ":END: line missing at position %s" b))))))
6746 (defun org-subtree-end-visible-p ()
6747 "Is the end of the current subtree visible?"
6748 (pos-visible-in-window-p
6749 (save-excursion (org-end-of-subtree t) (point))))
6751 (defun org-first-headline-recenter (&optional N)
6752 "Move cursor to the first headline and recenter the headline.
6753 Optional argument N means put the headline into the Nth line of the window."
6754 (goto-char (point-min))
6755 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6756 (beginning-of-line)
6757 (recenter (prefix-numeric-value N))))
6759 ;;; Saving and restoring visibility
6761 (defun org-outline-overlay-data (&optional use-markers)
6762 "Return a list of the locations of all outline overlays.
6763 These are overlays with the `invisible' property value `outline'.
6764 The return value is a list of cons cells, with start and stop
6765 positions for each overlay.
6766 If USE-MARKERS is set, return the positions as markers."
6767 (let (beg end)
6768 (save-excursion
6769 (save-restriction
6770 (widen)
6771 (delq nil
6772 (mapcar (lambda (o)
6773 (when (eq (overlay-get o 'invisible) 'outline)
6774 (setq beg (overlay-start o)
6775 end (overlay-end o))
6776 (and beg end (> end beg)
6777 (if use-markers
6778 (cons (move-marker (make-marker) beg)
6779 (move-marker (make-marker) end))
6780 (cons beg end)))))
6781 (overlays-in (point-min) (point-max))))))))
6783 (defun org-set-outline-overlay-data (data)
6784 "Create visibility overlays for all positions in DATA.
6785 DATA should have been made by `org-outline-overlay-data'."
6786 (let (o)
6787 (save-excursion
6788 (save-restriction
6789 (widen)
6790 (show-all)
6791 (mapc (lambda (c)
6792 (outline-flag-region (car c) (cdr c) t))
6793 data)))))
6795 ;;; Folding of blocks
6797 (defvar org-hide-block-overlays nil
6798 "Overlays hiding blocks.")
6799 (make-variable-buffer-local 'org-hide-block-overlays)
6801 (defun org-block-map (function &optional start end)
6802 "Call FUNCTION at the head of all source blocks in the current buffer.
6803 Optional arguments START and END can be used to limit the range."
6804 (let ((start (or start (point-min)))
6805 (end (or end (point-max))))
6806 (save-excursion
6807 (goto-char start)
6808 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6809 (save-excursion
6810 (save-match-data
6811 (goto-char (match-beginning 0))
6812 (funcall function)))))))
6814 (defun org-hide-block-toggle-all ()
6815 "Toggle the visibility of all blocks in the current buffer."
6816 (org-block-map #'org-hide-block-toggle))
6818 (defun org-hide-block-all ()
6819 "Fold all blocks in the current buffer."
6820 (interactive)
6821 (org-show-block-all)
6822 (org-block-map #'org-hide-block-toggle-maybe))
6824 (defun org-show-block-all ()
6825 "Unfold all blocks in the current buffer."
6826 (interactive)
6827 (mapc 'delete-overlay org-hide-block-overlays)
6828 (setq org-hide-block-overlays nil))
6830 (defun org-hide-block-toggle-maybe ()
6831 "Toggle visibility of block at point."
6832 (interactive)
6833 (let ((case-fold-search t))
6834 (if (save-excursion
6835 (beginning-of-line 1)
6836 (looking-at org-block-regexp))
6837 (progn (org-hide-block-toggle)
6838 t) ;; to signal that we took action
6839 nil))) ;; to signal that we did not
6841 (defun org-hide-block-toggle (&optional force)
6842 "Toggle the visibility of the current block."
6843 (interactive)
6844 (save-excursion
6845 (beginning-of-line)
6846 (if (re-search-forward org-block-regexp nil t)
6847 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6848 (end (match-end 0)) ;; end of entire body
6850 (if (memq t (mapcar (lambda (overlay)
6851 (eq (overlay-get overlay 'invisible)
6852 'org-hide-block))
6853 (overlays-at start)))
6854 (if (or (not force) (eq force 'off))
6855 (mapc (lambda (ov)
6856 (when (member ov org-hide-block-overlays)
6857 (setq org-hide-block-overlays
6858 (delq ov org-hide-block-overlays)))
6859 (when (eq (overlay-get ov 'invisible)
6860 'org-hide-block)
6861 (delete-overlay ov)))
6862 (overlays-at start)))
6863 (setq ov (make-overlay start end))
6864 (overlay-put ov 'invisible 'org-hide-block)
6865 ;; make the block accessible to isearch
6866 (overlay-put
6867 ov 'isearch-open-invisible
6868 (lambda (ov)
6869 (when (member ov org-hide-block-overlays)
6870 (setq org-hide-block-overlays
6871 (delq ov org-hide-block-overlays)))
6872 (when (eq (overlay-get ov 'invisible)
6873 'org-hide-block)
6874 (delete-overlay ov))))
6875 (push ov org-hide-block-overlays)))
6876 (error "Not looking at a source block"))))
6878 ;; org-tab-after-check-for-cycling-hook
6879 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6880 ;; Remove overlays when changing major mode
6881 (add-hook 'org-mode-hook
6882 (lambda () (org-add-hook 'change-major-mode-hook
6883 'org-show-block-all 'append 'local)))
6885 ;;; Org-goto
6887 (defvar org-goto-window-configuration nil)
6888 (defvar org-goto-marker nil)
6889 (defvar org-goto-map
6890 (let ((map (make-sparse-keymap)))
6891 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6892 (while (setq cmd (pop cmds))
6893 (substitute-key-definition cmd cmd map global-map)))
6894 (suppress-keymap map)
6895 (org-defkey map "\C-m" 'org-goto-ret)
6896 (org-defkey map [(return)] 'org-goto-ret)
6897 (org-defkey map [(left)] 'org-goto-left)
6898 (org-defkey map [(right)] 'org-goto-right)
6899 (org-defkey map [(control ?g)] 'org-goto-quit)
6900 (org-defkey map "\C-i" 'org-cycle)
6901 (org-defkey map [(tab)] 'org-cycle)
6902 (org-defkey map [(down)] 'outline-next-visible-heading)
6903 (org-defkey map [(up)] 'outline-previous-visible-heading)
6904 (if org-goto-auto-isearch
6905 (if (fboundp 'define-key-after)
6906 (define-key-after map [t] 'org-goto-local-auto-isearch)
6907 nil)
6908 (org-defkey map "q" 'org-goto-quit)
6909 (org-defkey map "n" 'outline-next-visible-heading)
6910 (org-defkey map "p" 'outline-previous-visible-heading)
6911 (org-defkey map "f" 'outline-forward-same-level)
6912 (org-defkey map "b" 'outline-backward-same-level)
6913 (org-defkey map "u" 'outline-up-heading))
6914 (org-defkey map "/" 'org-occur)
6915 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6916 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6917 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6918 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6919 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6920 map))
6922 (defconst org-goto-help
6923 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6924 RET=jump to location [Q]uit and return to previous location
6925 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6927 (defvar org-goto-start-pos) ; dynamically scoped parameter
6929 ;; FIXME: Docstring does not mention both interfaces
6930 (defun org-goto (&optional alternative-interface)
6931 "Look up a different location in the current file, keeping current visibility.
6933 When you want look-up or go to a different location in a
6934 document, the fastest way is often to fold the entire buffer and
6935 then dive into the tree. This method has the disadvantage, that
6936 the previous location will be folded, which may not be what you
6937 want.
6939 This command works around this by showing a copy of the current
6940 buffer in an indirect buffer, in overview mode. You can dive
6941 into the tree in that copy, use org-occur and incremental search
6942 to find a location. When pressing RET or `Q', the command
6943 returns to the original buffer in which the visibility is still
6944 unchanged. After RET it will also jump to the location selected
6945 in the indirect buffer and expose the headline hierarchy above.
6947 With a prefix argument, use the alternative interface: e.g. if
6948 `org-goto-interface' is 'outline use 'outline-path-completion."
6949 (interactive "P")
6950 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6951 (org-refile-use-outline-path t)
6952 (org-refile-target-verify-function nil)
6953 (interface
6954 (if (not alternative-interface)
6955 org-goto-interface
6956 (if (eq org-goto-interface 'outline)
6957 'outline-path-completion
6958 'outline)))
6959 (org-goto-start-pos (point))
6960 (selected-point
6961 (if (eq interface 'outline)
6962 (car (org-get-location (current-buffer) org-goto-help))
6963 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6964 (org-refile-check-position pa)
6965 (nth 3 pa)))))
6966 (if selected-point
6967 (progn
6968 (org-mark-ring-push org-goto-start-pos)
6969 (goto-char selected-point)
6970 (if (or (outline-invisible-p) (org-invisible-p2))
6971 (org-show-context 'org-goto)))
6972 (message "Quit"))))
6974 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6975 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6976 (defvar org-goto-local-auto-isearch-map) ; defined below
6978 (defun org-get-location (buf help)
6979 "Let the user select a location in the Org-mode buffer BUF.
6980 This function uses a recursive edit. It returns the selected position
6981 or nil."
6982 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6983 (isearch-hide-immediately nil)
6984 (isearch-search-fun-function
6985 (lambda () 'org-goto-local-search-headings))
6986 (org-goto-selected-point org-goto-exit-command)
6987 (pop-up-frames nil)
6988 (special-display-buffer-names nil)
6989 (special-display-regexps nil)
6990 (special-display-function nil))
6991 (save-excursion
6992 (save-window-excursion
6993 (delete-other-windows)
6994 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6995 (org-pop-to-buffer-same-window
6996 (condition-case nil
6997 (make-indirect-buffer (current-buffer) "*org-goto*")
6998 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6999 (with-output-to-temp-buffer "*Help*"
7000 (princ help))
7001 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7002 (setq buffer-read-only nil)
7003 (let ((org-startup-truncated t)
7004 (org-startup-folded nil)
7005 (org-startup-align-all-tables nil))
7006 (org-mode)
7007 (org-overview))
7008 (setq buffer-read-only t)
7009 (if (and (boundp 'org-goto-start-pos)
7010 (integer-or-marker-p org-goto-start-pos))
7011 (let ((org-show-hierarchy-above t)
7012 (org-show-siblings t)
7013 (org-show-following-heading t))
7014 (goto-char org-goto-start-pos)
7015 (and (outline-invisible-p) (org-show-context)))
7016 (goto-char (point-min)))
7017 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7018 (message "Select location and press RET")
7019 (use-local-map org-goto-map)
7020 (recursive-edit)
7022 (kill-buffer "*org-goto*")
7023 (cons org-goto-selected-point org-goto-exit-command)))
7025 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7026 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7027 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7028 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7030 (defun org-goto-local-search-headings (string bound noerror)
7031 "Search and make sure that any matches are in headlines."
7032 (catch 'return
7033 (while (if isearch-forward
7034 (search-forward string bound noerror)
7035 (search-backward string bound noerror))
7036 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7037 (and (member :headline context)
7038 (not (member :tags context))))
7039 (throw 'return (point))))))
7041 (defun org-goto-local-auto-isearch ()
7042 "Start isearch."
7043 (interactive)
7044 (goto-char (point-min))
7045 (let ((keys (this-command-keys)))
7046 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7047 (isearch-mode t)
7048 (isearch-process-search-char (string-to-char keys)))))
7050 (defun org-goto-ret (&optional arg)
7051 "Finish `org-goto' by going to the new location."
7052 (interactive "P")
7053 (setq org-goto-selected-point (point)
7054 org-goto-exit-command 'return)
7055 (throw 'exit nil))
7057 (defun org-goto-left ()
7058 "Finish `org-goto' by going to the new location."
7059 (interactive)
7060 (if (org-at-heading-p)
7061 (progn
7062 (beginning-of-line 1)
7063 (setq org-goto-selected-point (point)
7064 org-goto-exit-command 'left)
7065 (throw 'exit nil))
7066 (error "Not on a heading")))
7068 (defun org-goto-right ()
7069 "Finish `org-goto' by going to the new location."
7070 (interactive)
7071 (if (org-at-heading-p)
7072 (progn
7073 (setq org-goto-selected-point (point)
7074 org-goto-exit-command 'right)
7075 (throw 'exit nil))
7076 (error "Not on a heading")))
7078 (defun org-goto-quit ()
7079 "Finish `org-goto' without cursor motion."
7080 (interactive)
7081 (setq org-goto-selected-point nil)
7082 (setq org-goto-exit-command 'quit)
7083 (throw 'exit nil))
7085 ;;; Indirect buffer display of subtrees
7087 (defvar org-indirect-dedicated-frame nil
7088 "This is the frame being used for indirect tree display.")
7089 (defvar org-last-indirect-buffer nil)
7091 (defun org-tree-to-indirect-buffer (&optional arg)
7092 "Create indirect buffer and narrow it to current subtree.
7093 With a numerical prefix ARG, go up to this level and then take that tree.
7094 If ARG is negative, go up that many levels.
7096 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7097 indirect buffer previously made with this command, to avoid proliferation of
7098 indirect buffers. However, when you call the command with a \
7099 \\[universal-argument] prefix, or
7100 when `org-indirect-buffer-display' is `new-frame', the last buffer
7101 is kept so that you can work with several indirect buffers at the same time.
7102 If `org-indirect-buffer-display' is `dedicated-frame', the \
7103 \\[universal-argument] prefix also
7104 requests that a new frame be made for the new buffer, so that the dedicated
7105 frame is not changed."
7106 (interactive "P")
7107 (let ((cbuf (current-buffer))
7108 (cwin (selected-window))
7109 (pos (point))
7110 beg end level heading ibuf)
7111 (save-excursion
7112 (org-back-to-heading t)
7113 (when (numberp arg)
7114 (setq level (org-outline-level))
7115 (if (< arg 0) (setq arg (+ level arg)))
7116 (while (> (setq level (org-outline-level)) arg)
7117 (org-up-heading-safe)))
7118 (setq beg (point)
7119 heading (org-get-heading))
7120 (org-end-of-subtree t t)
7121 (if (org-at-heading-p) (backward-char 1))
7122 (setq end (point)))
7123 (if (and (buffer-live-p org-last-indirect-buffer)
7124 (not (eq org-indirect-buffer-display 'new-frame))
7125 (not arg))
7126 (kill-buffer org-last-indirect-buffer))
7127 (setq ibuf (org-get-indirect-buffer cbuf)
7128 org-last-indirect-buffer ibuf)
7129 (cond
7130 ((or (eq org-indirect-buffer-display 'new-frame)
7131 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7132 (select-frame (make-frame))
7133 (delete-other-windows)
7134 (org-pop-to-buffer-same-window ibuf)
7135 (org-set-frame-title heading))
7136 ((eq org-indirect-buffer-display 'dedicated-frame)
7137 (raise-frame
7138 (select-frame (or (and org-indirect-dedicated-frame
7139 (frame-live-p org-indirect-dedicated-frame)
7140 org-indirect-dedicated-frame)
7141 (setq org-indirect-dedicated-frame (make-frame)))))
7142 (delete-other-windows)
7143 (org-pop-to-buffer-same-window ibuf)
7144 (org-set-frame-title (concat "Indirect: " heading)))
7145 ((eq org-indirect-buffer-display 'current-window)
7146 (org-pop-to-buffer-same-window ibuf))
7147 ((eq org-indirect-buffer-display 'other-window)
7148 (pop-to-buffer ibuf))
7149 (t (error "Invalid value")))
7150 (if (featurep 'xemacs)
7151 (save-excursion (org-mode) (turn-on-font-lock)))
7152 (narrow-to-region beg end)
7153 (show-all)
7154 (goto-char pos)
7155 (run-hook-with-args 'org-cycle-hook 'all)
7156 (and (window-live-p cwin) (select-window cwin))))
7158 (defun org-get-indirect-buffer (&optional buffer)
7159 (setq buffer (or buffer (current-buffer)))
7160 (let ((n 1) (base (buffer-name buffer)) bname)
7161 (while (buffer-live-p
7162 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7163 (setq n (1+ n)))
7164 (condition-case nil
7165 (make-indirect-buffer buffer bname 'clone)
7166 (error (make-indirect-buffer buffer bname)))))
7168 (defun org-set-frame-title (title)
7169 "Set the title of the current frame to the string TITLE."
7170 ;; FIXME: how to name a single frame in XEmacs???
7171 (unless (featurep 'xemacs)
7172 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7174 ;;;; Structure editing
7176 ;;; Inserting headlines
7178 (defun org-previous-line-empty-p ()
7179 (save-excursion
7180 (and (not (bobp))
7181 (or (beginning-of-line 0) t)
7182 (save-match-data
7183 (looking-at "[ \t]*$")))))
7185 (defun org-insert-heading (&optional force-heading invisible-ok)
7186 "Insert a new heading or item with same depth at point.
7187 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7188 If point is at the beginning of a headline, insert a sibling before the
7189 current headline. If point is not at the beginning, split the line,
7190 create the new headline with the text in the current line after point
7191 \(but see also the variable `org-M-RET-may-split-line').
7193 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7194 This is important for non-interactive uses of the command."
7195 (interactive "P")
7196 (if (or (= (buffer-size) 0)
7197 (and (not (save-excursion
7198 (and (ignore-errors (org-back-to-heading invisible-ok))
7199 (org-at-heading-p))))
7200 (or force-heading (not (org-in-item-p)))))
7201 (progn
7202 (insert "\n* ")
7203 (run-hooks 'org-insert-heading-hook))
7204 (when (or force-heading (not (org-insert-item)))
7205 (let* ((empty-line-p nil)
7206 (level nil)
7207 (on-heading (org-at-heading-p))
7208 (head (save-excursion
7209 (condition-case nil
7210 (progn
7211 (org-back-to-heading invisible-ok)
7212 (when (and (not on-heading)
7213 (featurep 'org-inlinetask)
7214 (integerp org-inlinetask-min-level)
7215 (>= (length (match-string 0))
7216 org-inlinetask-min-level))
7217 ;; Find a heading level before the inline task
7218 (while (and (setq level (org-up-heading-safe))
7219 (>= level org-inlinetask-min-level)))
7220 (if (org-at-heading-p)
7221 (org-back-to-heading invisible-ok)
7222 (error "This should not happen")))
7223 (setq empty-line-p (org-previous-line-empty-p))
7224 (match-string 0))
7225 (error "*"))))
7226 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7227 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7228 pos hide-previous previous-pos)
7229 (cond
7230 ((and (org-at-heading-p) (bolp)
7231 (or (bobp)
7232 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7233 ;; insert before the current line
7234 (open-line (if blank 2 1)))
7235 ((and (bolp)
7236 (not org-insert-heading-respect-content)
7237 (or (bobp)
7238 (save-excursion
7239 (backward-char 1) (not (outline-invisible-p)))))
7240 ;; insert right here
7241 nil)
7243 ;; somewhere in the line
7244 (save-excursion
7245 (setq previous-pos (point-at-bol))
7246 (end-of-line)
7247 (setq hide-previous (outline-invisible-p)))
7248 (and org-insert-heading-respect-content (org-show-subtree))
7249 (let ((split
7250 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7251 (save-excursion
7252 (let ((p (point)))
7253 (goto-char (point-at-bol))
7254 (and (looking-at org-complex-heading-regexp)
7255 (match-beginning 4)
7256 (> p (match-beginning 4)))))))
7257 tags pos)
7258 (cond
7259 (org-insert-heading-respect-content
7260 (org-end-of-subtree nil t)
7261 (when (featurep 'org-inlinetask)
7262 (while (and (not (eobp))
7263 (looking-at "\\(\\*+\\)[ \t]+")
7264 (>= (length (match-string 1))
7265 org-inlinetask-min-level))
7266 (org-end-of-subtree nil t)))
7267 (or (bolp) (newline))
7268 (or (org-previous-line-empty-p)
7269 (and blank (newline)))
7270 (open-line 1))
7271 ((org-at-heading-p)
7272 (when hide-previous
7273 (show-children)
7274 (org-show-entry))
7275 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7276 (setq tags (and (match-end 2) (match-string 2)))
7277 (and (match-end 1)
7278 (delete-region (match-beginning 1) (match-end 1)))
7279 (setq pos (point-at-bol))
7280 (or split (end-of-line 1))
7281 (delete-horizontal-space)
7282 (if (string-match "\\`\\*+\\'"
7283 (buffer-substring (point-at-bol) (point)))
7284 (insert " "))
7285 (newline (if blank 2 1))
7286 (when tags
7287 (save-excursion
7288 (goto-char pos)
7289 (end-of-line 1)
7290 (insert " " tags)
7291 (org-set-tags nil 'align))))
7293 (or split (end-of-line 1))
7294 (newline (if blank 2 1)))))))
7295 (insert head) (just-one-space)
7296 (setq pos (point))
7297 (end-of-line 1)
7298 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7299 (when (and org-insert-heading-respect-content hide-previous)
7300 (save-excursion
7301 (goto-char previous-pos)
7302 (hide-subtree)))
7303 (run-hooks 'org-insert-heading-hook)))))
7305 (defun org-get-heading (&optional no-tags no-todo)
7306 "Return the heading of the current entry, without the stars.
7307 When NO-TAGS is non-nil, don't include tags.
7308 When NO-TODO is non-nil, don't include TODO keywords."
7309 (save-excursion
7310 (org-back-to-heading t)
7311 (cond
7312 ((and no-tags no-todo)
7313 (looking-at org-complex-heading-regexp)
7314 (match-string 4))
7315 (no-tags
7316 (looking-at (concat org-outline-regexp
7317 "\\(.*?\\)"
7318 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7319 (match-string 1))
7320 (no-todo
7321 (looking-at org-todo-line-regexp)
7322 (match-string 3))
7323 (t (looking-at org-heading-regexp)
7324 (match-string 2)))))
7326 (defun org-heading-components ()
7327 "Return the components of the current heading.
7328 This is a list with the following elements:
7329 - the level as an integer
7330 - the reduced level, different if `org-odd-levels-only' is set.
7331 - the TODO keyword, or nil
7332 - the priority character, like ?A, or nil if no priority is given
7333 - the headline text itself, or the tags string if no headline text
7334 - the tags string, or nil."
7335 (save-excursion
7336 (org-back-to-heading t)
7337 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7338 (list (length (match-string 1))
7339 (org-reduced-level (length (match-string 1)))
7340 (org-match-string-no-properties 2)
7341 (and (match-end 3) (aref (match-string 3) 2))
7342 (org-match-string-no-properties 4)
7343 (org-match-string-no-properties 5)))))
7345 (defun org-get-entry ()
7346 "Get the entry text, after heading, entire subtree."
7347 (save-excursion
7348 (org-back-to-heading t)
7349 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7351 (defun org-insert-heading-after-current ()
7352 "Insert a new heading with same level as current, after current subtree."
7353 (interactive)
7354 (org-back-to-heading)
7355 (org-insert-heading)
7356 (org-move-subtree-down)
7357 (end-of-line 1))
7359 (defun org-insert-heading-respect-content ()
7360 (interactive)
7361 (let ((org-insert-heading-respect-content t))
7362 (org-insert-heading t)))
7364 (defun org-insert-todo-heading-respect-content (&optional force-state)
7365 (interactive "P")
7366 (let ((org-insert-heading-respect-content t))
7367 (org-insert-todo-heading force-state t)))
7369 (defun org-insert-todo-heading (arg &optional force-heading)
7370 "Insert a new heading with the same level and TODO state as current heading.
7371 If the heading has no TODO state, or if the state is DONE, use the first
7372 state (TODO by default). Also with prefix arg, force first state."
7373 (interactive "P")
7374 (when (or force-heading (not (org-insert-item 'checkbox)))
7375 (org-insert-heading force-heading)
7376 (save-excursion
7377 (org-back-to-heading)
7378 (outline-previous-heading)
7379 (looking-at org-todo-line-regexp))
7380 (let*
7381 ((new-mark-x
7382 (if (or arg
7383 (not (match-beginning 2))
7384 (member (match-string 2) org-done-keywords))
7385 (car org-todo-keywords-1)
7386 (match-string 2)))
7387 (new-mark
7389 (run-hook-with-args-until-success
7390 'org-todo-get-default-hook new-mark-x nil)
7391 new-mark-x)))
7392 (beginning-of-line 1)
7393 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7394 (if org-treat-insert-todo-heading-as-state-change
7395 (org-todo new-mark)
7396 (insert new-mark " "))))
7397 (when org-provide-todo-statistics
7398 (org-update-parent-todo-statistics))))
7400 (defun org-insert-subheading (arg)
7401 "Insert a new subheading and demote it.
7402 Works for outline headings and for plain lists alike."
7403 (interactive "P")
7404 (org-insert-heading arg)
7405 (cond
7406 ((org-at-heading-p) (org-do-demote))
7407 ((org-at-item-p) (org-indent-item))))
7409 (defun org-insert-todo-subheading (arg)
7410 "Insert a new subheading with TODO keyword or checkbox and demote it.
7411 Works for outline headings and for plain lists alike."
7412 (interactive "P")
7413 (org-insert-todo-heading arg)
7414 (cond
7415 ((org-at-heading-p) (org-do-demote))
7416 ((org-at-item-p) (org-indent-item))))
7418 ;;; Promotion and Demotion
7420 (defvar org-after-demote-entry-hook nil
7421 "Hook run after an entry has been demoted.
7422 The cursor will be at the beginning of the entry.
7423 When a subtree is being demoted, the hook will be called for each node.")
7425 (defvar org-after-promote-entry-hook nil
7426 "Hook run after an entry has been promoted.
7427 The cursor will be at the beginning of the entry.
7428 When a subtree is being promoted, the hook will be called for each node.")
7430 (defun org-promote-subtree ()
7431 "Promote the entire subtree.
7432 See also `org-promote'."
7433 (interactive)
7434 (save-excursion
7435 (org-with-limited-levels (org-map-tree 'org-promote)))
7436 (org-fix-position-after-promote))
7438 (defun org-demote-subtree ()
7439 "Demote the entire subtree. See `org-demote'.
7440 See also `org-promote'."
7441 (interactive)
7442 (save-excursion
7443 (org-with-limited-levels (org-map-tree 'org-demote)))
7444 (org-fix-position-after-promote))
7447 (defun org-do-promote ()
7448 "Promote the current heading higher up the tree.
7449 If the region is active in `transient-mark-mode', promote all headings
7450 in the region."
7451 (interactive)
7452 (save-excursion
7453 (if (org-region-active-p)
7454 (org-map-region 'org-promote (region-beginning) (region-end))
7455 (org-promote)))
7456 (org-fix-position-after-promote))
7458 (defun org-do-demote ()
7459 "Demote the current heading lower down the tree.
7460 If the region is active in `transient-mark-mode', demote all headings
7461 in the region."
7462 (interactive)
7463 (save-excursion
7464 (if (org-region-active-p)
7465 (org-map-region 'org-demote (region-beginning) (region-end))
7466 (org-demote)))
7467 (org-fix-position-after-promote))
7469 (defun org-fix-position-after-promote ()
7470 "Make sure that after pro/demotion cursor position is right."
7471 (let ((pos (point)))
7472 (when (save-excursion
7473 (beginning-of-line 1)
7474 (looking-at org-todo-line-regexp)
7475 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7476 (cond ((eobp) (insert " "))
7477 ((eolp) (insert " "))
7478 ((equal (char-after) ?\ ) (forward-char 1))))))
7480 (defun org-current-level ()
7481 "Return the level of the current entry, or nil if before the first headline.
7482 The level is the number of stars at the beginning of the headline."
7483 (save-excursion
7484 (org-with-limited-levels
7485 (if (ignore-errors (org-back-to-heading t))
7486 (funcall outline-level)))))
7488 (defun org-get-previous-line-level ()
7489 "Return the outline depth of the last headline before the current line.
7490 Returns 0 for the first headline in the buffer, and nil if before the
7491 first headline."
7492 (let ((current-level (org-current-level))
7493 (prev-level (when (> (line-number-at-pos) 1)
7494 (save-excursion
7495 (beginning-of-line 0)
7496 (org-current-level)))))
7497 (cond ((null current-level) nil) ; Before first headline
7498 ((null prev-level) 0) ; At first headline
7499 (prev-level))))
7501 (defun org-reduced-level (l)
7502 "Compute the effective level of a heading.
7503 This takes into account the setting of `org-odd-levels-only'."
7504 (cond
7505 ((zerop l) 0)
7506 (org-odd-levels-only (1+ (floor (/ l 2))))
7507 (t l)))
7509 (defun org-level-increment ()
7510 "Return the number of stars that will be added or removed at a
7511 time to headlines when structure editing, based on the value of
7512 `org-odd-levels-only'."
7513 (if org-odd-levels-only 2 1))
7515 (defun org-get-valid-level (level &optional change)
7516 "Rectify a level change under the influence of `org-odd-levels-only'
7517 LEVEL is a current level, CHANGE is by how much the level should be
7518 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7519 even level numbers will become the next higher odd number."
7520 (if org-odd-levels-only
7521 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7522 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7523 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7524 (max 1 (+ level (or change 0)))))
7526 (if (boundp 'define-obsolete-function-alias)
7527 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7528 (define-obsolete-function-alias 'org-get-legal-level
7529 'org-get-valid-level)
7530 (define-obsolete-function-alias 'org-get-legal-level
7531 'org-get-valid-level "23.1")))
7533 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7534 ;; ̀org-with-limited-levels'
7535 (defun org-promote ()
7536 "Promote the current heading higher up the tree.
7537 If the region is active in `transient-mark-mode', promote all headings
7538 in the region."
7539 (org-back-to-heading t)
7540 (let* ((level (save-match-data (funcall outline-level)))
7541 (after-change-functions (remove 'flyspell-after-change-function
7542 after-change-functions))
7543 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7544 (diff (abs (- level (length up-head) -1))))
7545 (cond ((and (= level 1) org-called-with-limited-levels
7546 org-allow-promoting-top-level-subtree)
7547 (replace-match "# " nil t))
7548 ((= level 1)
7549 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7550 (t (replace-match up-head nil t)))
7551 ;; Fixup tag positioning
7552 (unless (= level 1)
7553 (and org-auto-align-tags (org-set-tags nil t))
7554 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7555 (run-hooks 'org-after-promote-entry-hook)))
7557 (defun org-demote ()
7558 "Demote the current heading lower down the tree.
7559 If the region is active in `transient-mark-mode', demote all headings
7560 in the region."
7561 (org-back-to-heading t)
7562 (let* ((level (save-match-data (funcall outline-level)))
7563 (after-change-functions (remove 'flyspell-after-change-function
7564 after-change-functions))
7565 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7566 (diff (abs (- level (length down-head) -1))))
7567 (replace-match down-head nil t)
7568 ;; Fixup tag positioning
7569 (and org-auto-align-tags (org-set-tags nil t))
7570 (if org-adapt-indentation (org-fixup-indentation diff))
7571 (run-hooks 'org-after-demote-entry-hook)))
7573 (defun org-cycle-level ()
7574 "Cycle the level of an empty headline through possible states.
7575 This goes first to child, then to parent, level, then up the hierarchy.
7576 After top level, it switches back to sibling level."
7577 (interactive)
7578 (let ((org-adapt-indentation nil))
7579 (when (org-point-at-end-of-empty-headline)
7580 (setq this-command 'org-cycle-level) ; Only needed for caching
7581 (let ((cur-level (org-current-level))
7582 (prev-level (org-get-previous-line-level)))
7583 (cond
7584 ;; If first headline in file, promote to top-level.
7585 ((= prev-level 0)
7586 (loop repeat (/ (- cur-level 1) (org-level-increment))
7587 do (org-do-promote)))
7588 ;; If same level as prev, demote one.
7589 ((= prev-level cur-level)
7590 (org-do-demote))
7591 ;; If parent is top-level, promote to top level if not already.
7592 ((= prev-level 1)
7593 (loop repeat (/ (- cur-level 1) (org-level-increment))
7594 do (org-do-promote)))
7595 ;; If top-level, return to prev-level.
7596 ((= cur-level 1)
7597 (loop repeat (/ (- prev-level 1) (org-level-increment))
7598 do (org-do-demote)))
7599 ;; If less than prev-level, promote one.
7600 ((< cur-level prev-level)
7601 (org-do-promote))
7602 ;; If deeper than prev-level, promote until higher than
7603 ;; prev-level.
7604 ((> cur-level prev-level)
7605 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7606 do (org-do-promote))))
7607 t))))
7609 (defun org-map-tree (fun)
7610 "Call FUN for every heading underneath the current one."
7611 (org-back-to-heading)
7612 (let ((level (funcall outline-level)))
7613 (save-excursion
7614 (funcall fun)
7615 (while (and (progn
7616 (outline-next-heading)
7617 (> (funcall outline-level) level))
7618 (not (eobp)))
7619 (funcall fun)))))
7621 (defun org-map-region (fun beg end)
7622 "Call FUN for every heading between BEG and END."
7623 (let ((org-ignore-region t))
7624 (save-excursion
7625 (setq end (copy-marker end))
7626 (goto-char beg)
7627 (if (and (re-search-forward org-outline-regexp-bol nil t)
7628 (< (point) end))
7629 (funcall fun))
7630 (while (and (progn
7631 (outline-next-heading)
7632 (< (point) end))
7633 (not (eobp)))
7634 (funcall fun)))))
7636 (defvar org-property-end-re) ; silence byte-compiler
7637 (defun org-fixup-indentation (diff)
7638 "Change the indentation in the current entry by DIFF.
7639 However, if any line in the current entry has no indentation, or if it
7640 would end up with no indentation after the change, nothing at all is done."
7641 (save-excursion
7642 (let ((end (save-excursion (outline-next-heading)
7643 (point-marker)))
7644 (prohibit (if (> diff 0)
7645 "^\\S-"
7646 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7647 col)
7648 (unless (save-excursion (end-of-line 1)
7649 (re-search-forward prohibit end t))
7650 (while (and (< (point) end)
7651 (re-search-forward "^[ \t]+" end t))
7652 (goto-char (match-end 0))
7653 (setq col (current-column))
7654 (if (< diff 0) (replace-match ""))
7655 (org-indent-to-column (+ diff col))))
7656 (move-marker end nil))))
7658 (defun org-convert-to-odd-levels ()
7659 "Convert an org-mode file with all levels allowed to one with odd levels.
7660 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7661 level 5 etc."
7662 (interactive)
7663 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7664 (let ((outline-level 'org-outline-level)
7665 (org-odd-levels-only nil) n)
7666 (save-excursion
7667 (goto-char (point-min))
7668 (while (re-search-forward "^\\*\\*+ " nil t)
7669 (setq n (- (length (match-string 0)) 2))
7670 (while (>= (setq n (1- n)) 0)
7671 (org-demote))
7672 (end-of-line 1))))))
7674 (defun org-convert-to-oddeven-levels ()
7675 "Convert an org-mode file with only odd levels to one with odd/even levels.
7676 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7677 file contains a section with an even level, conversion would
7678 destroy the structure of the file. An error is signaled in this
7679 case."
7680 (interactive)
7681 (goto-char (point-min))
7682 ;; First check if there are no even levels
7683 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7684 (org-show-context t)
7685 (error "Not all levels are odd in this file. Conversion not possible"))
7686 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7687 (let ((outline-regexp org-outline-regexp)
7688 (outline-level 'org-outline-level)
7689 (org-odd-levels-only nil) n)
7690 (save-excursion
7691 (goto-char (point-min))
7692 (while (re-search-forward "^\\*\\*+ " nil t)
7693 (setq n (/ (1- (length (match-string 0))) 2))
7694 (while (>= (setq n (1- n)) 0)
7695 (org-promote))
7696 (end-of-line 1))))))
7698 (defun org-tr-level (n)
7699 "Make N odd if required."
7700 (if org-odd-levels-only (1+ (/ n 2)) n))
7702 ;;; Vertical tree motion, cutting and pasting of subtrees
7704 (defun org-move-subtree-up (&optional arg)
7705 "Move the current subtree up past ARG headlines of the same level."
7706 (interactive "p")
7707 (org-move-subtree-down (- (prefix-numeric-value arg))))
7709 (defun org-move-subtree-down (&optional arg)
7710 "Move the current subtree down past ARG headlines of the same level."
7711 (interactive "p")
7712 (setq arg (prefix-numeric-value arg))
7713 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7714 'org-get-last-sibling))
7715 (ins-point (make-marker))
7716 (cnt (abs arg))
7717 (col (current-column))
7718 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7719 ;; Select the tree
7720 (org-back-to-heading)
7721 (setq beg0 (point))
7722 (save-excursion
7723 (setq ne-beg (org-back-over-empty-lines))
7724 (setq beg (point)))
7725 (save-match-data
7726 (save-excursion (outline-end-of-heading)
7727 (setq folded (outline-invisible-p)))
7728 (outline-end-of-subtree))
7729 (outline-next-heading)
7730 (setq ne-end (org-back-over-empty-lines))
7731 (setq end (point))
7732 (goto-char beg0)
7733 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7734 ;; include less whitespace
7735 (save-excursion
7736 (goto-char beg)
7737 (forward-line (- ne-beg ne-end))
7738 (setq beg (point))))
7739 ;; Find insertion point, with error handling
7740 (while (> cnt 0)
7741 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7742 (progn (goto-char beg0)
7743 (error "Cannot move past superior level or buffer limit")))
7744 (setq cnt (1- cnt)))
7745 (if (> arg 0)
7746 ;; Moving forward - still need to move over subtree
7747 (progn (org-end-of-subtree t t)
7748 (save-excursion
7749 (org-back-over-empty-lines)
7750 (or (bolp) (newline)))))
7751 (setq ne-ins (org-back-over-empty-lines))
7752 (move-marker ins-point (point))
7753 (setq txt (buffer-substring beg end))
7754 (org-save-markers-in-region beg end)
7755 (delete-region beg end)
7756 (org-remove-empty-overlays-at beg)
7757 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7758 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7759 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7760 (let ((bbb (point)))
7761 (insert-before-markers txt)
7762 (org-reinstall-markers-in-region bbb)
7763 (move-marker ins-point bbb))
7764 (or (bolp) (insert "\n"))
7765 (setq ins-end (point))
7766 (goto-char ins-point)
7767 (org-skip-whitespace)
7768 (when (and (< arg 0)
7769 (org-first-sibling-p)
7770 (> ne-ins ne-beg))
7771 ;; Move whitespace back to beginning
7772 (save-excursion
7773 (goto-char ins-end)
7774 (let ((kill-whole-line t))
7775 (kill-line (- ne-ins ne-beg)) (point)))
7776 (insert (make-string (- ne-ins ne-beg) ?\n)))
7777 (move-marker ins-point nil)
7778 (if folded
7779 (hide-subtree)
7780 (org-show-entry)
7781 (show-children)
7782 (org-cycle-hide-drawers 'children))
7783 (org-clean-visibility-after-subtree-move)
7784 ;; move back to the initial column we were at
7785 (move-to-column col)))
7787 (defvar org-subtree-clip ""
7788 "Clipboard for cut and paste of subtrees.
7789 This is actually only a copy of the kill, because we use the normal kill
7790 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7792 (defvar org-subtree-clip-folded nil
7793 "Was the last copied subtree folded?
7794 This is used to fold the tree back after pasting.")
7796 (defun org-cut-subtree (&optional n)
7797 "Cut the current subtree into the clipboard.
7798 With prefix arg N, cut this many sequential subtrees.
7799 This is a short-hand for marking the subtree and then cutting it."
7800 (interactive "p")
7801 (org-copy-subtree n 'cut))
7803 (defun org-copy-subtree (&optional n cut force-store-markers)
7804 "Cut the current subtree into the clipboard.
7805 With prefix arg N, cut this many sequential subtrees.
7806 This is a short-hand for marking the subtree and then copying it.
7807 If CUT is non-nil, actually cut the subtree.
7808 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7809 of some markers in the region, even if CUT is non-nil. This is
7810 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7811 (interactive "p")
7812 (let (beg end folded (beg0 (point)))
7813 (if (org-called-interactively-p 'any)
7814 (org-back-to-heading nil) ; take what looks like a subtree
7815 (org-back-to-heading t)) ; take what is really there
7816 (org-back-over-empty-lines)
7817 (setq beg (point))
7818 (skip-chars-forward " \t\r\n")
7819 (save-match-data
7820 (save-excursion (outline-end-of-heading)
7821 (setq folded (outline-invisible-p)))
7822 (condition-case nil
7823 (org-forward-heading-same-level (1- n) t)
7824 (error nil))
7825 (org-end-of-subtree t t))
7826 (org-back-over-empty-lines)
7827 (setq end (point))
7828 (goto-char beg0)
7829 (when (> end beg)
7830 (setq org-subtree-clip-folded folded)
7831 (when (or cut force-store-markers)
7832 (org-save-markers-in-region beg end))
7833 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7834 (setq org-subtree-clip (current-kill 0))
7835 (message "%s: Subtree(s) with %d characters"
7836 (if cut "Cut" "Copied")
7837 (length org-subtree-clip)))))
7839 (defun org-paste-subtree (&optional level tree for-yank)
7840 "Paste the clipboard as a subtree, with modification of headline level.
7841 The entire subtree is promoted or demoted in order to match a new headline
7842 level.
7844 If the cursor is at the beginning of a headline, the same level as
7845 that headline is used to paste the tree
7847 If not, the new level is derived from the *visible* headings
7848 before and after the insertion point, and taken to be the inferior headline
7849 level of the two. So if the previous visible heading is level 3 and the
7850 next is level 4 (or vice versa), level 4 will be used for insertion.
7851 This makes sure that the subtree remains an independent subtree and does
7852 not swallow low level entries.
7854 You can also force a different level, either by using a numeric prefix
7855 argument, or by inserting the heading marker by hand. For example, if the
7856 cursor is after \"*****\", then the tree will be shifted to level 5.
7858 If optional TREE is given, use this text instead of the kill ring.
7860 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7861 move back over whitespace before inserting, and move point to the end of
7862 the inserted text when done."
7863 (interactive "P")
7864 (setq tree (or tree (and kill-ring (current-kill 0))))
7865 (unless (org-kill-is-subtree-p tree)
7866 (error "%s"
7867 (substitute-command-keys
7868 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7869 (org-with-limited-levels
7870 (let* ((visp (not (outline-invisible-p)))
7871 (txt tree)
7872 (^re_ "\\(\\*+\\)[ \t]*")
7873 (old-level (if (string-match org-outline-regexp-bol txt)
7874 (- (match-end 0) (match-beginning 0) 1)
7875 -1))
7876 (force-level (cond (level (prefix-numeric-value level))
7877 ((and (looking-at "[ \t]*$")
7878 (string-match
7879 "^\\*+$" (buffer-substring
7880 (point-at-bol) (point))))
7881 (- (match-end 1) (match-beginning 1)))
7882 ((and (bolp)
7883 (looking-at org-outline-regexp))
7884 (- (match-end 0) (point) 1))))
7885 (previous-level (save-excursion
7886 (condition-case nil
7887 (progn
7888 (outline-previous-visible-heading 1)
7889 (if (looking-at ^re_)
7890 (- (match-end 0) (match-beginning 0) 1)
7892 (error 1))))
7893 (next-level (save-excursion
7894 (condition-case nil
7895 (progn
7896 (or (looking-at org-outline-regexp)
7897 (outline-next-visible-heading 1))
7898 (if (looking-at ^re_)
7899 (- (match-end 0) (match-beginning 0) 1)
7901 (error 1))))
7902 (new-level (or force-level (max previous-level next-level)))
7903 (shift (if (or (= old-level -1)
7904 (= new-level -1)
7905 (= old-level new-level))
7907 (- new-level old-level)))
7908 (delta (if (> shift 0) -1 1))
7909 (func (if (> shift 0) 'org-demote 'org-promote))
7910 (org-odd-levels-only nil)
7911 beg end newend)
7912 ;; Remove the forced level indicator
7913 (if force-level
7914 (delete-region (point-at-bol) (point)))
7915 ;; Paste
7916 (beginning-of-line (if (bolp) 1 2))
7917 (unless for-yank (org-back-over-empty-lines))
7918 (setq beg (point))
7919 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7920 (insert-before-markers txt)
7921 (unless (string-match "\n\\'" txt) (insert "\n"))
7922 (setq newend (point))
7923 (org-reinstall-markers-in-region beg)
7924 (setq end (point))
7925 (goto-char beg)
7926 (skip-chars-forward " \t\n\r")
7927 (setq beg (point))
7928 (if (and (outline-invisible-p) visp)
7929 (save-excursion (outline-show-heading)))
7930 ;; Shift if necessary
7931 (unless (= shift 0)
7932 (save-restriction
7933 (narrow-to-region beg end)
7934 (while (not (= shift 0))
7935 (org-map-region func (point-min) (point-max))
7936 (setq shift (+ delta shift)))
7937 (goto-char (point-min))
7938 (setq newend (point-max))))
7939 (when (or (org-called-interactively-p 'interactive) for-yank)
7940 (message "Clipboard pasted as level %d subtree" new-level))
7941 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7942 kill-ring
7943 (eq org-subtree-clip (current-kill 0))
7944 org-subtree-clip-folded)
7945 ;; The tree was folded before it was killed/copied
7946 (hide-subtree))
7947 (and for-yank (goto-char newend)))))
7949 (defun org-kill-is-subtree-p (&optional txt)
7950 "Check if the current kill is an outline subtree, or a set of trees.
7951 Returns nil if kill does not start with a headline, or if the first
7952 headline level is not the largest headline level in the tree.
7953 So this will actually accept several entries of equal levels as well,
7954 which is OK for `org-paste-subtree'.
7955 If optional TXT is given, check this string instead of the current kill."
7956 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7957 (re (org-get-limited-outline-regexp))
7958 (^re (concat "^" re))
7959 (start-level (and kill
7960 (string-match
7961 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7962 kill)
7963 (- (match-end 2) (match-beginning 2) 1)))
7964 (start (1+ (or (match-beginning 2) -1))))
7965 (if (not start-level)
7966 (progn
7967 nil) ;; does not even start with a heading
7968 (catch 'exit
7969 (while (setq start (string-match ^re kill (1+ start)))
7970 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7971 (throw 'exit nil)))
7972 t))))
7974 (defvar org-markers-to-move nil
7975 "Markers that should be moved with a cut-and-paste operation.
7976 Those markers are stored together with their positions relative to
7977 the start of the region.")
7979 (defun org-save-markers-in-region (beg end)
7980 "Check markers in region.
7981 If these markers are between BEG and END, record their position relative
7982 to BEG, so that after moving the block of text, we can put the markers back
7983 into place.
7984 This function gets called just before an entry or tree gets cut from the
7985 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7986 called immediately, to move the markers with the entries."
7987 (setq org-markers-to-move nil)
7988 (when (featurep 'org-clock)
7989 (org-clock-save-markers-for-cut-and-paste beg end))
7990 (when (featurep 'org-agenda)
7991 (org-agenda-save-markers-for-cut-and-paste beg end)))
7993 (defun org-check-and-save-marker (marker beg end)
7994 "Check if MARKER is between BEG and END.
7995 If yes, remember the marker and the distance to BEG."
7996 (when (and (marker-buffer marker)
7997 (equal (marker-buffer marker) (current-buffer)))
7998 (if (and (>= marker beg) (< marker end))
7999 (push (cons marker (- marker beg)) org-markers-to-move))))
8001 (defun org-reinstall-markers-in-region (beg)
8002 "Move all remembered markers to their position relative to BEG."
8003 (mapc (lambda (x)
8004 (move-marker (car x) (+ beg (cdr x))))
8005 org-markers-to-move)
8006 (setq org-markers-to-move nil))
8008 (defun org-narrow-to-subtree ()
8009 "Narrow buffer to the current subtree."
8010 (interactive)
8011 (save-excursion
8012 (save-match-data
8013 (org-with-limited-levels
8014 (narrow-to-region
8015 (progn (org-back-to-heading t) (point))
8016 (progn (org-end-of-subtree t t)
8017 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8018 (point)))))))
8020 (defun org-narrow-to-block ()
8021 "Narrow buffer to the current block."
8022 (interactive)
8023 (let* ((case-fold-search t)
8024 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8025 "^[ \t]*#\\+end_.*")))
8026 (if blockp
8027 (narrow-to-region (car blockp) (cdr blockp))
8028 (error "Not in a block"))))
8030 (eval-when-compile
8031 (defvar org-property-drawer-re))
8033 (defvar org-property-start-re) ;; defined below
8034 (defun org-clone-subtree-with-time-shift (n &optional shift)
8035 "Clone the task (subtree) at point N times.
8036 The clones will be inserted as siblings.
8038 In interactive use, the user will be prompted for the number of
8039 clones to be produced, and for a time SHIFT, which may be a
8040 repeater as used in time stamps, for example `+3d'.
8042 When a valid repeater is given and the entry contains any time
8043 stamps, the clones will become a sequence in time, with time
8044 stamps in the subtree shifted for each clone produced. If SHIFT
8045 is nil or the empty string, time stamps will be left alone. The
8046 ID property of the original subtree is removed.
8048 If the original subtree did contain time stamps with a repeater,
8049 the following will happen:
8050 - the repeater will be removed in each clone
8051 - an additional clone will be produced, with the current, unshifted
8052 date(s) in the entry.
8053 - the original entry will be placed *after* all the clones, with
8054 repeater intact.
8055 - the start days in the repeater in the original entry will be shifted
8056 to past the last clone.
8057 In this way you can spell out a number of instances of a repeating task,
8058 and still retain the repeater to cover future instances of the task."
8059 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8060 (let (beg end template task idprop
8061 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8062 (drawer-re org-drawer-regexp))
8063 (if (not (and (integerp n) (> n 0)))
8064 (error "Invalid number of replications %s" n))
8065 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8066 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8067 shift)))
8068 (error "Invalid shift specification %s" shift))
8069 (when doshift
8070 (setq shift-n (string-to-number (match-string 1 shift))
8071 shift-what (cdr (assoc (match-string 2 shift)
8072 '(("d" . day) ("w" . week)
8073 ("m" . month) ("y" . year))))))
8074 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8075 (setq nmin 1 nmax n)
8076 (org-back-to-heading t)
8077 (setq beg (point))
8078 (setq idprop (org-entry-get nil "ID"))
8079 (org-end-of-subtree t t)
8080 (or (bolp) (insert "\n"))
8081 (setq end (point))
8082 (setq template (buffer-substring beg end))
8083 (when (and doshift
8084 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8085 (delete-region beg end)
8086 (setq end beg)
8087 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8088 (goto-char end)
8089 (loop for n from nmin to nmax do
8090 ;; prepare clone
8091 (with-temp-buffer
8092 (insert template)
8093 (org-mode)
8094 (goto-char (point-min))
8095 (org-show-subtree)
8096 (and idprop (if org-clone-delete-id
8097 (org-entry-delete nil "ID")
8098 (org-id-get-create t)))
8099 (unless (= n 0)
8100 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8101 (kill-whole-line))
8102 (goto-char (point-min))
8103 (while (re-search-forward drawer-re nil t)
8104 (mapc (lambda (d)
8105 (org-remove-empty-drawer-at d (point))) org-drawers)))
8106 (goto-char (point-min))
8107 (when doshift
8108 (while (re-search-forward org-ts-regexp-both nil t)
8109 (org-timestamp-change (* n shift-n) shift-what))
8110 (unless (= n n-no-remove)
8111 (goto-char (point-min))
8112 (while (re-search-forward org-ts-regexp nil t)
8113 (save-excursion
8114 (goto-char (match-beginning 0))
8115 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8116 (delete-region (match-beginning 1) (match-end 1)))))))
8117 (setq task (buffer-string)))
8118 (insert task))
8119 (goto-char beg)))
8121 ;;; Outline Sorting
8123 (defun org-sort (with-case)
8124 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8125 Optional argument WITH-CASE means sort case-sensitively."
8126 (interactive "P")
8127 (cond
8128 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8129 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8131 (org-call-with-arg 'org-sort-entries with-case))))
8133 (defun org-sort-remove-invisible (s)
8134 (remove-text-properties 0 (length s) org-rm-props s)
8135 (while (string-match org-bracket-link-regexp s)
8136 (setq s (replace-match (if (match-end 2)
8137 (match-string 3 s)
8138 (match-string 1 s)) t t s)))
8141 (defvar org-priority-regexp) ; defined later in the file
8143 (defvar org-after-sorting-entries-or-items-hook nil
8144 "Hook that is run after a bunch of entries or items have been sorted.
8145 When children are sorted, the cursor is in the parent line when this
8146 hook gets called. When a region or a plain list is sorted, the cursor
8147 will be in the first entry of the sorted region/list.")
8149 (defun org-sort-entries
8150 (&optional with-case sorting-type getkey-func compare-func property)
8151 "Sort entries on a certain level of an outline tree.
8152 If there is an active region, the entries in the region are sorted.
8153 Else, if the cursor is before the first entry, sort the top-level items.
8154 Else, the children of the entry at point are sorted.
8156 Sorting can be alphabetically, numerically, by date/time as given by
8157 a time stamp, by a property or by priority.
8159 The command prompts for the sorting type unless it has been given to the
8160 function through the SORTING-TYPE argument, which needs to be a character,
8161 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8162 precise meaning of each character:
8164 n Numerically, by converting the beginning of the entry/item to a number.
8165 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8166 t By date/time, either the first active time stamp in the entry, or, if
8167 none exist, by the first inactive one.
8168 s By the scheduled date/time.
8169 d By deadline date/time.
8170 c By creation time, which is assumed to be the first inactive time stamp
8171 at the beginning of a line.
8172 p By priority according to the cookie.
8173 r By the value of a property.
8175 Capital letters will reverse the sort order.
8177 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8178 called with point at the beginning of the record. It must return either
8179 a string or a number that should serve as the sorting key for that record.
8181 Comparing entries ignores case by default. However, with an optional argument
8182 WITH-CASE, the sorting considers case as well."
8183 (interactive "P")
8184 (let ((case-func (if with-case 'identity 'downcase))
8185 start beg end stars re re2
8186 txt what tmp)
8187 ;; Find beginning and end of region to sort
8188 (cond
8189 ((org-region-active-p)
8190 ;; we will sort the region
8191 (setq end (region-end)
8192 what "region")
8193 (goto-char (region-beginning))
8194 (if (not (org-at-heading-p)) (outline-next-heading))
8195 (setq start (point)))
8196 ((or (org-at-heading-p)
8197 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8198 ;; we will sort the children of the current headline
8199 (org-back-to-heading)
8200 (setq start (point)
8201 end (progn (org-end-of-subtree t t)
8202 (or (bolp) (insert "\n"))
8203 (org-back-over-empty-lines)
8204 (point))
8205 what "children")
8206 (goto-char start)
8207 (show-subtree)
8208 (outline-next-heading))
8210 ;; we will sort the top-level entries in this file
8211 (goto-char (point-min))
8212 (or (org-at-heading-p) (outline-next-heading))
8213 (setq start (point))
8214 (goto-char (point-max))
8215 (beginning-of-line 1)
8216 (when (looking-at ".*?\\S-")
8217 ;; File ends in a non-white line
8218 (end-of-line 1)
8219 (insert "\n"))
8220 (setq end (point-max))
8221 (setq what "top-level")
8222 (goto-char start)
8223 (show-all)))
8225 (setq beg (point))
8226 (if (>= beg end) (error "Nothing to sort"))
8228 (looking-at "\\(\\*+\\)")
8229 (setq stars (match-string 1)
8230 re (concat "^" (regexp-quote stars) " +")
8231 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8232 txt (buffer-substring beg end))
8233 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8234 (if (and (not (equal stars "*")) (string-match re2 txt))
8235 (error "Region to sort contains a level above the first entry"))
8237 (unless sorting-type
8238 (message
8239 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8240 [t]ime [s]cheduled [d]eadline [c]reated
8241 A/N/T/S/D/C/P/O/F means reversed:"
8242 what)
8243 (setq sorting-type (read-char-exclusive))
8245 (and (= (downcase sorting-type) ?f)
8246 (setq getkey-func
8247 (org-icompleting-read "Sort using function: "
8248 obarray 'fboundp t nil nil))
8249 (setq getkey-func (intern getkey-func)))
8251 (and (= (downcase sorting-type) ?r)
8252 (setq property
8253 (org-icompleting-read "Property: "
8254 (mapcar 'list (org-buffer-property-keys t))
8255 nil t))))
8257 (message "Sorting entries...")
8259 (save-restriction
8260 (narrow-to-region start end)
8261 (let ((dcst (downcase sorting-type))
8262 (case-fold-search nil)
8263 (now (current-time)))
8264 (sort-subr
8265 (/= dcst sorting-type)
8266 ;; This function moves to the beginning character of the "record" to
8267 ;; be sorted.
8268 (lambda nil
8269 (if (re-search-forward re nil t)
8270 (goto-char (match-beginning 0))
8271 (goto-char (point-max))))
8272 ;; This function moves to the last character of the "record" being
8273 ;; sorted.
8274 (lambda nil
8275 (save-match-data
8276 (condition-case nil
8277 (outline-forward-same-level 1)
8278 (error
8279 (goto-char (point-max))))))
8280 ;; This function returns the value that gets sorted against.
8281 (lambda nil
8282 (cond
8283 ((= dcst ?n)
8284 (if (looking-at org-complex-heading-regexp)
8285 (string-to-number (match-string 4))
8286 nil))
8287 ((= dcst ?a)
8288 (if (looking-at org-complex-heading-regexp)
8289 (funcall case-func (match-string 4))
8290 nil))
8291 ((= dcst ?t)
8292 (let ((end (save-excursion (outline-next-heading) (point))))
8293 (if (or (re-search-forward org-ts-regexp end t)
8294 (re-search-forward org-ts-regexp-both end t))
8295 (org-time-string-to-seconds (match-string 0))
8296 (org-float-time now))))
8297 ((= dcst ?c)
8298 (let ((end (save-excursion (outline-next-heading) (point))))
8299 (if (re-search-forward
8300 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8301 end t)
8302 (org-time-string-to-seconds (match-string 0))
8303 (org-float-time now))))
8304 ((= dcst ?s)
8305 (let ((end (save-excursion (outline-next-heading) (point))))
8306 (if (re-search-forward org-scheduled-time-regexp end t)
8307 (org-time-string-to-seconds (match-string 1))
8308 (org-float-time now))))
8309 ((= dcst ?d)
8310 (let ((end (save-excursion (outline-next-heading) (point))))
8311 (if (re-search-forward org-deadline-time-regexp end t)
8312 (org-time-string-to-seconds (match-string 1))
8313 (org-float-time now))))
8314 ((= dcst ?p)
8315 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8316 (string-to-char (match-string 2))
8317 org-default-priority))
8318 ((= dcst ?r)
8319 (or (org-entry-get nil property) ""))
8320 ((= dcst ?o)
8321 (if (looking-at org-complex-heading-regexp)
8322 (- 9999 (length (member (match-string 2)
8323 org-todo-keywords-1)))))
8324 ((= dcst ?f)
8325 (if getkey-func
8326 (progn
8327 (setq tmp (funcall getkey-func))
8328 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8329 tmp)
8330 (error "Invalid key function `%s'" getkey-func)))
8331 (t (error "Invalid sorting type `%c'" sorting-type))))
8333 (cond
8334 ((= dcst ?a) 'string<)
8335 ((= dcst ?f) compare-func)
8336 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8337 (run-hooks 'org-after-sorting-entries-or-items-hook)
8338 (message "Sorting entries...done")))
8340 (defun org-do-sort (table what &optional with-case sorting-type)
8341 "Sort TABLE of WHAT according to SORTING-TYPE.
8342 The user will be prompted for the SORTING-TYPE if the call to this
8343 function does not specify it. WHAT is only for the prompt, to indicate
8344 what is being sorted. The sorting key will be extracted from
8345 the car of the elements of the table.
8346 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8347 (unless sorting-type
8348 (message
8349 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8350 what)
8351 (setq sorting-type (read-char-exclusive)))
8352 (let ((dcst (downcase sorting-type))
8353 extractfun comparefun)
8354 ;; Define the appropriate functions
8355 (cond
8356 ((= dcst ?n)
8357 (setq extractfun 'string-to-number
8358 comparefun (if (= dcst sorting-type) '< '>)))
8359 ((= dcst ?a)
8360 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8361 (lambda(x) (downcase (org-sort-remove-invisible x))))
8362 comparefun (if (= dcst sorting-type)
8363 'string<
8364 (lambda (a b) (and (not (string< a b))
8365 (not (string= a b)))))))
8366 ((= dcst ?t)
8367 (setq extractfun
8368 (lambda (x)
8369 (if (or (string-match org-ts-regexp x)
8370 (string-match org-ts-regexp-both x))
8371 (org-float-time
8372 (org-time-string-to-time (match-string 0 x)))
8374 comparefun (if (= dcst sorting-type) '< '>)))
8375 (t (error "Invalid sorting type `%c'" sorting-type)))
8377 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8378 table)
8379 (lambda (a b) (funcall comparefun (car a) (car b))))))
8382 ;;; The orgstruct minor mode
8384 ;; Define a minor mode which can be used in other modes in order to
8385 ;; integrate the org-mode structure editing commands.
8387 ;; This is really a hack, because the org-mode structure commands use
8388 ;; keys which normally belong to the major mode. Here is how it
8389 ;; works: The minor mode defines all the keys necessary to operate the
8390 ;; structure commands, but wraps the commands into a function which
8391 ;; tests if the cursor is currently at a headline or a plain list
8392 ;; item. If that is the case, the structure command is used,
8393 ;; temporarily setting many Org-mode variables like regular
8394 ;; expressions for filling etc. However, when any of those keys is
8395 ;; used at a different location, function uses `key-binding' to look
8396 ;; up if the key has an associated command in another currently active
8397 ;; keymap (minor modes, major mode, global), and executes that
8398 ;; command. There might be problems if any of the keys is otherwise
8399 ;; used as a prefix key.
8401 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8402 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8403 ;; addresses this by checking explicitly for both bindings.
8405 (defvar orgstruct-mode-map (make-sparse-keymap)
8406 "Keymap for the minor `orgstruct-mode'.")
8408 (defvar org-local-vars nil
8409 "List of local variables, for use by `orgstruct-mode'.")
8411 ;;;###autoload
8412 (define-minor-mode orgstruct-mode
8413 "Toggle the minor mode `orgstruct-mode'.
8414 This mode is for using Org-mode structure commands in other
8415 modes. The following keys behave as if Org-mode were active, if
8416 the cursor is on a headline, or on a plain list item (both as
8417 defined by Org-mode).
8419 M-up Move entry/item up
8420 M-down Move entry/item down
8421 M-left Promote
8422 M-right Demote
8423 M-S-up Move entry/item up
8424 M-S-down Move entry/item down
8425 M-S-left Promote subtree
8426 M-S-right Demote subtree
8427 M-q Fill paragraph and items like in Org-mode
8428 C-c ^ Sort entries
8429 C-c - Cycle list bullet
8430 TAB Cycle item visibility
8431 M-RET Insert new heading/item
8432 S-M-RET Insert new TODO heading / Checkbox item
8433 C-c C-c Set tags / toggle checkbox"
8434 nil " OrgStruct" nil
8435 (org-load-modules-maybe)
8436 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8438 ;;;###autoload
8439 (defun turn-on-orgstruct ()
8440 "Unconditionally turn on `orgstruct-mode'."
8441 (orgstruct-mode 1))
8443 (defvar org-fb-vars nil)
8444 (make-variable-buffer-local 'org-fb-vars)
8445 (defun orgstruct++-mode (&optional arg)
8446 "Toggle `orgstruct-mode', the enhanced version of it.
8447 In addition to setting orgstruct-mode, this also exports all
8448 indentation and autofilling variables from org-mode into the
8449 buffer. It will also recognize item context in multiline items."
8450 (interactive "P")
8451 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8452 (if (< arg 1)
8453 (progn (orgstruct-mode -1)
8454 (mapc (lambda(v)
8455 (org-set-local (car v)
8456 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8457 org-fb-vars))
8458 (orgstruct-mode 1)
8459 (setq org-fb-vars nil)
8460 (let (var val)
8461 (mapc
8462 (lambda (x)
8463 (when (string-match
8464 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8465 (symbol-name (car x)))
8466 (setq var (car x) val (nth 1 x))
8467 (push (list var `(quote ,(eval var))) org-fb-vars)
8468 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8469 org-local-vars)
8470 (org-set-local 'orgstruct-is-++ t))))
8472 (defvar orgstruct-is-++ nil
8473 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8474 (make-variable-buffer-local 'orgstruct-is-++)
8476 ;;;###autoload
8477 (defun turn-on-orgstruct++ ()
8478 "Unconditionally turn on `orgstruct++-mode'."
8479 (orgstruct++-mode 1))
8481 (defun orgstruct-error ()
8482 "Error when there is no default binding for a structure key."
8483 (interactive)
8484 (error "This key has no function outside structure elements"))
8486 (defun orgstruct-setup ()
8487 "Setup orgstruct keymaps."
8488 (let ((nfunc 0)
8489 (bindings
8490 (list
8491 '([(meta up)] org-metaup)
8492 '([(meta down)] org-metadown)
8493 '([(meta left)] org-metaleft)
8494 '([(meta right)] org-metaright)
8495 '([(meta shift up)] org-shiftmetaup)
8496 '([(meta shift down)] org-shiftmetadown)
8497 '([(meta shift left)] org-shiftmetaleft)
8498 '([(meta shift right)] org-shiftmetaright)
8499 '([?\e (up)] org-metaup)
8500 '([?\e (down)] org-metadown)
8501 '([?\e (left)] org-metaleft)
8502 '([?\e (right)] org-metaright)
8503 '([?\e (shift up)] org-shiftmetaup)
8504 '([?\e (shift down)] org-shiftmetadown)
8505 '([?\e (shift left)] org-shiftmetaleft)
8506 '([?\e (shift right)] org-shiftmetaright)
8507 '([(shift up)] org-shiftup)
8508 '([(shift down)] org-shiftdown)
8509 '([(shift left)] org-shiftleft)
8510 '([(shift right)] org-shiftright)
8511 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8512 '("\M-q" fill-paragraph)
8513 '("\C-c^" org-sort)
8514 '("\C-c-" org-cycle-list-bullet)))
8515 elt key fun cmd)
8516 (while (setq elt (pop bindings))
8517 (setq nfunc (1+ nfunc))
8518 (setq key (org-key (car elt))
8519 fun (nth 1 elt)
8520 cmd (orgstruct-make-binding fun nfunc key))
8521 (org-defkey orgstruct-mode-map key cmd))
8523 ;; Prevent an error for users who forgot to make autoloads
8524 (require 'org-element)
8526 ;; Special treatment needed for TAB and RET
8527 (org-defkey orgstruct-mode-map [(tab)]
8528 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8529 (org-defkey orgstruct-mode-map "\C-i"
8530 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8532 (org-defkey orgstruct-mode-map "\M-\C-m"
8533 (orgstruct-make-binding 'org-insert-heading 105
8534 "\M-\C-m" [(meta return)]))
8535 (org-defkey orgstruct-mode-map [(meta return)]
8536 (orgstruct-make-binding 'org-insert-heading 106
8537 [(meta return)] "\M-\C-m"))
8539 (org-defkey orgstruct-mode-map [(shift meta return)]
8540 (orgstruct-make-binding 'org-insert-todo-heading 107
8541 [(meta return)] "\M-\C-m"))
8543 (org-defkey orgstruct-mode-map "\e\C-m"
8544 (orgstruct-make-binding 'org-insert-heading 108
8545 "\e\C-m" [?\e (return)]))
8546 (org-defkey orgstruct-mode-map [?\e (return)]
8547 (orgstruct-make-binding 'org-insert-heading 109
8548 [?\e (return)] "\e\C-m"))
8549 (org-defkey orgstruct-mode-map [?\e (shift return)]
8550 (orgstruct-make-binding 'org-insert-todo-heading 110
8551 [?\e (return)] "\e\C-m"))
8553 (unless org-local-vars
8554 (setq org-local-vars (org-get-local-variables)))
8558 (defun orgstruct-make-binding (fun n &rest keys)
8559 "Create a function for binding in the structure minor mode.
8560 FUN is the command to call inside a table. N is used to create a unique
8561 command name. KEYS are keys that should be checked in for a command
8562 to execute outside of tables."
8563 (eval
8564 (list 'defun
8565 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8566 '(arg)
8567 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8568 "Outside of structure, run the binding of `"
8569 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8570 "'.")
8571 '(interactive "p")
8572 (list 'if
8573 `(org-context-p 'headline 'item
8574 (and orgstruct-is-++
8575 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8576 'item-body))
8577 (list 'org-run-like-in-org-mode (list 'quote fun))
8578 (list 'let '(orgstruct-mode)
8579 (list 'call-interactively
8580 (append '(or)
8581 (mapcar (lambda (k)
8582 (list 'key-binding k))
8583 keys)
8584 '('orgstruct-error))))))))
8586 (defun org-contextualize-keys (alist contexts)
8587 "Return valid elements in ALIST depending on CONTEXTS.
8589 `org-agenda-custom-commands' or `org-capture-templates' are the
8590 values used for ALIST, and `org-agenda-custom-commands-contexts'
8591 or `org-capture-templates-contexts' are the associated contexts
8592 definitions."
8593 (let ((contexts
8594 ;; normalize contexts
8595 (mapcar
8596 (lambda(c) (cond ((listp (cadr c))
8597 (list (car c) (car c) (cadr c)))
8598 ((string= "" (cadr c))
8599 (list (car c) (car c) (caddr c)))
8600 (t c))) contexts))
8601 (a alist) c r s)
8602 ;; loop over all commands or templates
8603 (while (setq c (pop a))
8604 (let (vrules repl)
8605 (cond
8606 ((not (assoc (car c) contexts))
8607 (push c r))
8608 ((and (assoc (car c) contexts)
8609 (setq vrules (org-contextualize-validate-key
8610 (car c) contexts)))
8611 (mapc (lambda (vr)
8612 (when (not (equal (car vr) (cadr vr)))
8613 (setq repl vr))) vrules)
8614 (if (not repl) (push c r)
8615 (push (cadr repl) s)
8616 (push
8617 (cons (car c)
8618 (cdr (or (assoc (cadr repl) alist)
8619 (error "Undefined key `%s' as contextual replacement for `%s'"
8620 (cadr repl) (car c)))))
8621 r))))))
8622 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8623 (delq
8625 (delete-dups
8626 (mapcar (lambda (x)
8627 (let ((tpl (car x)))
8628 (when (not (delq
8630 (mapcar (lambda(y)
8631 (equal y tpl)) s))) x)))
8632 (reverse r))))))
8634 (defun org-contextualize-validate-key (key contexts)
8635 "Check CONTEXTS for agenda or capture KEY."
8636 (let (r rr res)
8637 (while (setq r (pop contexts))
8638 (mapc
8639 (lambda (rr)
8640 (when
8641 (and (equal key (car r))
8642 (if (functionp rr) (funcall rr)
8643 (or (and (eq (car rr) 'in-file)
8644 (buffer-file-name)
8645 (string-match (cdr rr) (buffer-file-name)))
8646 (and (eq (car rr) 'in-mode)
8647 (string-match (cdr rr) (symbol-name major-mode)))
8648 (when (and (eq (car rr) 'not-in-file)
8649 (buffer-file-name))
8650 (not (string-match (cdr rr) (buffer-file-name))))
8651 (when (eq (car rr) 'not-in-mode)
8652 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8653 (push r res)))
8654 (car (last r))))
8655 (delete-dups (delq nil res))))
8657 (defun org-context-p (&rest contexts)
8658 "Check if local context is any of CONTEXTS.
8659 Possible values in the list of contexts are `table', `headline', and `item'."
8660 (let ((pos (point)))
8661 (goto-char (point-at-bol))
8662 (prog1 (or (and (memq 'table contexts)
8663 (looking-at "[ \t]*|"))
8664 (and (memq 'headline contexts)
8665 (looking-at org-outline-regexp))
8666 (and (memq 'item contexts)
8667 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8668 (and (memq 'item-body contexts)
8669 (org-in-item-p)))
8670 (goto-char pos))))
8672 (defun org-get-local-variables ()
8673 "Return a list of all local variables in an Org mode buffer."
8674 (let (varlist)
8675 (with-current-buffer (get-buffer-create "*Org tmp*")
8676 (erase-buffer)
8677 (org-mode)
8678 (setq varlist (buffer-local-variables)))
8679 (kill-buffer "*Org tmp*")
8680 (delq nil
8681 (mapcar
8682 (lambda (x)
8683 (setq x
8684 (if (symbolp x)
8685 (list x)
8686 (list (car x) (list 'quote (cdr x)))))
8687 (if (string-match
8688 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8689 (symbol-name (car x)))
8690 x nil))
8691 varlist))))
8693 (defun org-clone-local-variables (from-buffer &optional regexp)
8694 "Clone local variables from FROM-BUFFER.
8695 Optional argument REGEXP selects variables to clone."
8696 (mapc
8697 (lambda (pair)
8698 (and (symbolp (car pair))
8699 (or (null regexp)
8700 (string-match regexp (symbol-name (car pair))))
8701 (set (make-local-variable (car pair))
8702 (cdr pair))))
8703 (buffer-local-variables from-buffer)))
8705 ;;;###autoload
8706 (defun org-run-like-in-org-mode (cmd)
8707 "Run a command, pretending that the current buffer is in Org-mode.
8708 This will temporarily bind local variables that are typically bound in
8709 Org-mode to the values they have in Org-mode, and then interactively
8710 call CMD."
8711 (org-load-modules-maybe)
8712 (unless org-local-vars
8713 (setq org-local-vars (org-get-local-variables)))
8714 (eval (list 'let org-local-vars
8715 (list 'call-interactively (list 'quote cmd)))))
8717 ;;;; Archiving
8719 (defun org-get-category (&optional pos force-refresh)
8720 "Get the category applying to position POS."
8721 (save-match-data
8722 (if force-refresh (org-refresh-category-properties))
8723 (let ((pos (or pos (point))))
8724 (or (get-text-property pos 'org-category)
8725 (progn (org-refresh-category-properties)
8726 (get-text-property pos 'org-category))))))
8728 (defun org-refresh-category-properties ()
8729 "Refresh category text properties in the buffer."
8730 (let ((case-fold-search t)
8731 (inhibit-read-only t)
8732 (def-cat (cond
8733 ((null org-category)
8734 (if buffer-file-name
8735 (file-name-sans-extension
8736 (file-name-nondirectory buffer-file-name))
8737 "???"))
8738 ((symbolp org-category) (symbol-name org-category))
8739 (t org-category)))
8740 beg end cat pos optionp)
8741 (org-unmodified
8742 (save-excursion
8743 (save-restriction
8744 (widen)
8745 (goto-char (point-min))
8746 (put-text-property (point) (point-max) 'org-category def-cat)
8747 (while (re-search-forward
8748 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8749 (setq pos (match-end 0)
8750 optionp (equal (char-after (match-beginning 0)) ?#)
8751 cat (org-trim (match-string 2)))
8752 (if optionp
8753 (setq beg (point-at-bol) end (point-max))
8754 (org-back-to-heading t)
8755 (setq beg (point) end (org-end-of-subtree t t)))
8756 (put-text-property beg end 'org-category cat)
8757 (put-text-property beg end 'org-category-position beg)
8758 (goto-char pos)))))))
8761 ;;;; Link Stuff
8763 ;;; Link abbreviations
8765 (defun org-link-expand-abbrev (link)
8766 "Apply replacements as defined in `org-link-abbrev-alist'."
8767 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8768 (let* ((key (match-string 1 link))
8769 (as (or (assoc key org-link-abbrev-alist-local)
8770 (assoc key org-link-abbrev-alist)))
8771 (tag (and (match-end 2) (match-string 3 link)))
8772 rpl)
8773 (if (not as)
8774 link
8775 (setq rpl (cdr as))
8776 (cond
8777 ((symbolp rpl) (funcall rpl tag))
8778 ((string-match "%(\\([^)]+\\))" rpl)
8779 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8780 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8781 ((string-match "%h" rpl)
8782 (replace-match (url-hexify-string (or tag "")) t t rpl))
8783 (t (concat rpl tag)))))
8784 link))
8786 ;;; Storing and inserting links
8788 (defvar org-insert-link-history nil
8789 "Minibuffer history for links inserted with `org-insert-link'.")
8791 (defvar org-stored-links nil
8792 "Contains the links stored with `org-store-link'.")
8794 (defvar org-store-link-plist nil
8795 "Plist with info about the most recently link created with `org-store-link'.")
8797 (defvar org-link-protocols nil
8798 "Link protocols added to Org-mode using `org-add-link-type'.")
8800 (defvar org-store-link-functions nil
8801 "List of functions that are called to create and store a link.
8802 Each function will be called in turn until one returns a non-nil
8803 value. Each function should check if it is responsible for creating
8804 this link (for example by looking at the major mode).
8805 If not, it must exit and return nil.
8806 If yes, it should return a non-nil value after a calling
8807 `org-store-link-props' with a list of properties and values.
8808 Special properties are:
8810 :type The link prefix, like \"http\". This must be given.
8811 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8812 This is obligatory as well.
8813 :description Optional default description for the second pair
8814 of brackets in an Org-mode link. The user can still change
8815 this when inserting this link into an Org-mode buffer.
8817 In addition to these, any additional properties can be specified
8818 and then used in capture templates.")
8820 (defun org-add-link-type (type &optional follow export)
8821 "Add TYPE to the list of `org-link-types'.
8822 Re-compute all regular expressions depending on `org-link-types'
8824 FOLLOW and EXPORT are two functions.
8826 FOLLOW should take the link path as the single argument and do whatever
8827 is necessary to follow the link, for example find a file or display
8828 a mail message.
8830 EXPORT should format the link path for export to one of the export formats.
8831 It should be a function accepting three arguments:
8833 path the path of the link, the text after the prefix (like \"http:\")
8834 desc the description of the link, if any, or a description added by
8835 org-export-normalize-links if there is none
8836 format the export format, a symbol like `html' or `latex' or `ascii'..
8838 The function may use the FORMAT information to return different values
8839 depending on the format. The return value will be put literally into
8840 the exported file. If the return value is nil, this means Org should
8841 do what it normally does with links which do not have EXPORT defined.
8843 Org-mode has a built-in default for exporting links. If you are happy with
8844 this default, there is no need to define an export function for the link
8845 type. For a simple example of an export function, see `org-bbdb.el'."
8846 (add-to-list 'org-link-types type t)
8847 (org-make-link-regexps)
8848 (if (assoc type org-link-protocols)
8849 (setcdr (assoc type org-link-protocols) (list follow export))
8850 (push (list type follow export) org-link-protocols)))
8852 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8853 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8855 ;;;###autoload
8856 (defun org-store-link (arg)
8857 "\\<org-mode-map>Store an org-link to the current location.
8858 This link is added to `org-stored-links' and can later be inserted
8859 into an org-buffer with \\[org-insert-link].
8861 For some link types, a prefix arg is interpreted:
8862 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8863 For file links, arg negates `org-context-in-file-links'."
8864 (interactive "P")
8865 (org-load-modules-maybe)
8866 (setq org-store-link-plist nil) ; reset
8867 (org-with-limited-levels
8868 (let (link cpltxt desc description search txt custom-id agenda-link)
8869 (cond
8871 ((run-hook-with-args-until-success 'org-store-link-functions)
8872 (setq link (plist-get org-store-link-plist :link)
8873 desc (or (plist-get org-store-link-plist :description) link)))
8875 ((org-src-edit-buffer-p)
8876 (let (label gc)
8877 (while (or (not label)
8878 (save-excursion
8879 (save-restriction
8880 (widen)
8881 (goto-char (point-min))
8882 (re-search-forward
8883 (regexp-quote (format org-coderef-label-format label))
8884 nil t))))
8885 (when label (message "Label exists already") (sit-for 2))
8886 (setq label (read-string "Code line label: " label)))
8887 (end-of-line 1)
8888 (setq link (format org-coderef-label-format label))
8889 (setq gc (- 79 (length link)))
8890 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8891 (insert link)
8892 (setq link (concat "(" label ")") desc nil)))
8894 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8895 ;; We are in the agenda, link to referenced location
8896 (let ((m (or (get-text-property (point) 'org-hd-marker)
8897 (get-text-property (point) 'org-marker))))
8898 (when m
8899 (org-with-point-at m
8900 (setq agenda-link
8901 (if (org-called-interactively-p 'any)
8902 (call-interactively 'org-store-link)
8903 (org-store-link nil)))))))
8905 ((eq major-mode 'calendar-mode)
8906 (let ((cd (calendar-cursor-to-date)))
8907 (setq link
8908 (format-time-string
8909 (car org-time-stamp-formats)
8910 (apply 'encode-time
8911 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8912 nil nil nil))))
8913 (org-store-link-props :type "calendar" :date cd)))
8915 ((eq major-mode 'help-mode)
8916 (setq link (concat "help:" (save-excursion
8917 (goto-char (point-min))
8918 (looking-at "^[^ ]+")
8919 (match-string 0))))
8920 (org-store-link-props :type "help"))
8922 ((eq major-mode 'w3-mode)
8923 (setq cpltxt (if (and (buffer-name)
8924 (not (string-match "Untitled" (buffer-name))))
8925 (buffer-name)
8926 (url-view-url t))
8927 link (url-view-url t))
8928 (org-store-link-props :type "w3" :url (url-view-url t)))
8930 ((eq major-mode 'w3m-mode)
8931 (setq cpltxt (or w3m-current-title w3m-current-url)
8932 link w3m-current-url)
8933 (org-store-link-props :type "w3m" :url (url-view-url t)))
8935 ((setq search (run-hook-with-args-until-success
8936 'org-create-file-search-functions))
8937 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8938 "::" search))
8939 (setq cpltxt (or description link)))
8941 ((eq major-mode 'image-mode)
8942 (setq cpltxt (concat "file:"
8943 (abbreviate-file-name buffer-file-name))
8944 link cpltxt)
8945 (org-store-link-props :type "image" :file buffer-file-name))
8947 ((eq major-mode 'dired-mode)
8948 ;; link to the file in the current line
8949 (let ((file (dired-get-filename nil t)))
8950 (setq file (if file
8951 (abbreviate-file-name
8952 (expand-file-name (dired-get-filename nil t)))
8953 ;; otherwise, no file so use current directory.
8954 default-directory))
8955 (setq cpltxt (concat "file:" file)
8956 link cpltxt)))
8958 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8959 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8960 (cond
8961 ((org-in-regexp "<<\\(.*?\\)>>")
8962 (setq cpltxt
8963 (concat "file:"
8964 (abbreviate-file-name
8965 (buffer-file-name (buffer-base-buffer)))
8966 "::" (match-string 1))
8967 link cpltxt))
8968 ((and (featurep 'org-id)
8969 (or (eq org-link-to-org-use-id t)
8970 (and (org-called-interactively-p 'any)
8971 (or (eq org-link-to-org-use-id 'create-if-interactive)
8972 (and (eq org-link-to-org-use-id
8973 'create-if-interactive-and-no-custom-id)
8974 (not custom-id))))
8975 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8976 ;; We can make a link using the ID.
8977 (setq link (condition-case nil
8978 (prog1 (org-id-store-link)
8979 (setq desc (plist-get org-store-link-plist :description)))
8980 (error
8981 ;; probably before first headline, link to file only
8982 (concat "file:"
8983 (abbreviate-file-name
8984 (buffer-file-name (buffer-base-buffer))))))))
8986 ;; Just link to current headline
8987 (setq cpltxt (concat "file:"
8988 (abbreviate-file-name
8989 (buffer-file-name (buffer-base-buffer)))))
8990 ;; Add a context search string
8991 (when (org-xor org-context-in-file-links arg)
8992 (setq txt (cond
8993 ((org-at-heading-p) nil)
8994 ((org-region-active-p)
8995 (buffer-substring (region-beginning) (region-end)))))
8996 (when (or (null txt) (string-match "\\S-" txt))
8997 (setq cpltxt
8998 (concat cpltxt "::"
8999 (condition-case nil
9000 (org-make-org-heading-search-string txt)
9001 (error "")))
9002 desc (or (nth 4 (ignore-errors
9003 (org-heading-components))) "NONE"))))
9004 (if (string-match "::\\'" cpltxt)
9005 (setq cpltxt (substring cpltxt 0 -2)))
9006 (setq link cpltxt))))
9008 ((buffer-file-name (buffer-base-buffer))
9009 ;; Just link to this file here.
9010 (setq cpltxt (concat "file:"
9011 (abbreviate-file-name
9012 (buffer-file-name (buffer-base-buffer)))))
9013 ;; Add a context string
9014 (when (org-xor org-context-in-file-links arg)
9015 (setq txt (if (org-region-active-p)
9016 (buffer-substring (region-beginning) (region-end))
9017 (buffer-substring (point-at-bol) (point-at-eol))))
9018 ;; Only use search option if there is some text.
9019 (when (string-match "\\S-" txt)
9020 (setq cpltxt
9021 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9022 desc "NONE")))
9023 (setq link cpltxt))
9025 ((org-called-interactively-p 'interactive)
9026 (error "Cannot link to a buffer which is not visiting a file"))
9028 (t (setq link nil)))
9030 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9031 (setq link (or link cpltxt)
9032 desc (or desc cpltxt))
9033 (if (equal desc "NONE") (setq desc nil))
9035 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9036 (progn
9037 (setq org-stored-links
9038 (cons (list link desc) org-stored-links))
9039 (message "Stored: %s" (or desc link))
9040 (when custom-id
9041 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9042 "::#" custom-id))
9043 (setq org-stored-links
9044 (cons (list link desc) org-stored-links))))
9045 (or agenda-link (and link (org-make-link-string link desc)))))))
9047 (defun org-store-link-props (&rest plist)
9048 "Store link properties, extract names and addresses."
9049 (let (x adr)
9050 (when (setq x (plist-get plist :from))
9051 (setq adr (mail-extract-address-components x))
9052 (setq plist (plist-put plist :fromname (car adr)))
9053 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9054 (when (setq x (plist-get plist :to))
9055 (setq adr (mail-extract-address-components x))
9056 (setq plist (plist-put plist :toname (car adr)))
9057 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9058 (let ((from (plist-get plist :from))
9059 (to (plist-get plist :to)))
9060 (when (and from to org-from-is-user-regexp)
9061 (setq plist
9062 (plist-put plist :fromto
9063 (if (string-match org-from-is-user-regexp from)
9064 (concat "to %t")
9065 (concat "from %f"))))))
9066 (setq org-store-link-plist plist))
9068 (defun org-add-link-props (&rest plist)
9069 "Add these properties to the link property list."
9070 (let (key value)
9071 (while plist
9072 (setq key (pop plist) value (pop plist))
9073 (setq org-store-link-plist
9074 (plist-put org-store-link-plist key value)))))
9076 (defun org-email-link-description (&optional fmt)
9077 "Return the description part of an email link.
9078 This takes information from `org-store-link-plist' and formats it
9079 according to FMT (default from `org-email-link-description-format')."
9080 (setq fmt (or fmt org-email-link-description-format))
9081 (let* ((p org-store-link-plist)
9082 (to (plist-get p :toaddress))
9083 (from (plist-get p :fromaddress))
9084 (table
9085 (list
9086 (cons "%c" (plist-get p :fromto))
9087 (cons "%F" (plist-get p :from))
9088 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9089 (cons "%T" (plist-get p :to))
9090 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9091 (cons "%s" (plist-get p :subject))
9092 (cons "%d" (plist-get p :date))
9093 (cons "%m" (plist-get p :message-id)))))
9094 (when (string-match "%c" fmt)
9095 ;; Check if the user wrote this message
9096 (if (and org-from-is-user-regexp from to
9097 (save-match-data (string-match org-from-is-user-regexp from)))
9098 (setq fmt (replace-match "to %t" t t fmt))
9099 (setq fmt (replace-match "from %f" t t fmt))))
9100 (org-replace-escapes fmt table)))
9102 (defun org-make-org-heading-search-string (&optional string heading)
9103 "Make search string for STRING or current headline."
9104 (interactive)
9105 (let ((s (or string (org-get-heading)))
9106 (lines org-context-in-file-links))
9107 (unless (and string (not heading))
9108 ;; We are using a headline, clean up garbage in there.
9109 (if (string-match org-todo-regexp s)
9110 (setq s (replace-match "" t t s)))
9111 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9112 (setq s (replace-match "" t t s)))
9113 (setq s (org-trim s))
9114 (if (string-match (concat "^\\(" org-quote-string "\\|"
9115 org-comment-string "\\)") s)
9116 (setq s (replace-match "" t t s)))
9117 (while (string-match org-ts-regexp s)
9118 (setq s (replace-match "" t t s))))
9119 (or string (setq s (concat "*" s))) ; Add * for headlines
9120 (when (and string (integerp lines) (> lines 0))
9121 (let ((slines (org-split-string s "\n")))
9122 (when (< lines (length slines))
9123 (setq s (mapconcat
9124 'identity
9125 (reverse (nthcdr (- (length slines) lines)
9126 (reverse slines))) "\n")))))
9127 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9129 (defun org-make-link-string (link &optional description)
9130 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9131 (unless (string-match "\\S-" link)
9132 (error "Empty link"))
9133 (when (and description
9134 (stringp description)
9135 (not (string-match "\\S-" description)))
9136 (setq description nil))
9137 (when (stringp description)
9138 ;; Remove brackets from the description, they are fatal.
9139 (while (string-match "\\[" description)
9140 (setq description (replace-match "{" t t description)))
9141 (while (string-match "\\]" description)
9142 (setq description (replace-match "}" t t description))))
9143 (when (equal link description)
9144 ;; No description needed, it is identical
9145 (setq description nil))
9146 (when (and (not description)
9147 (not (string-match (org-image-file-name-regexp) link))
9148 (not (equal link (org-link-escape link))))
9149 (setq description (org-extract-attributes link)))
9150 (setq link
9151 (cond ((string-match (org-image-file-name-regexp) link) link)
9152 ((string-match org-link-types-re link)
9153 (concat (match-string 1 link)
9154 (org-link-escape (substring link (match-end 1)))))
9155 (t (org-link-escape link))))
9156 (concat "[[" link "]"
9157 (if description (concat "[" description "]") "")
9158 "]"))
9160 (defconst org-link-escape-chars
9161 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9162 "List of characters that should be escaped in link.
9163 This is the list that is used for internal purposes.")
9165 (defconst org-link-escape-chars-browser
9166 '(?\ )
9167 "List of escapes for characters that are problematic in links.
9168 This is the list that is used before handing over to the browser.")
9170 (defun org-link-escape (text &optional table merge)
9171 "Return percent escaped representation of TEXT.
9172 TEXT is a string with the text to escape.
9173 Optional argument TABLE is a list with characters that should be
9174 escaped. When nil, `org-link-escape-chars' is used.
9175 If optional argument MERGE is set, merge TABLE into
9176 `org-link-escape-chars'."
9177 (cond
9178 ((and table merge)
9179 (mapc (lambda (defchr)
9180 (unless (member defchr table)
9181 (setq table (cons defchr table)))) org-link-escape-chars))
9182 ((null table)
9183 (setq table org-link-escape-chars)))
9184 (mapconcat
9185 (lambda (char)
9186 (if (or (member char table)
9187 (and (or (< char 32) (= char 37) (> char 126))
9188 org-url-hexify-p))
9189 (mapconcat (lambda (sequence-element)
9190 (format "%%%.2X" sequence-element))
9191 (or (encode-coding-char char 'utf-8)
9192 (error "Unable to percent escape character: %s"
9193 (char-to-string char))) "")
9194 (char-to-string char))) text ""))
9196 (defun org-link-unescape (str)
9197 "Unhex hexified Unicode strings as returned from the JavaScript function
9198 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9199 (unless (and (null str) (string= "" str))
9200 (let ((pos 0) (case-fold-search t) unhexed)
9201 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9202 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9203 (setq str (replace-match unhexed t t str))
9204 (setq pos (+ pos (length unhexed))))))
9205 str)
9207 (defun org-link-unescape-compound (hex)
9208 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9209 Note: this function also decodes single byte encodings like
9210 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9211 (save-match-data
9212 (let* ((bytes (cdr (split-string hex "%")))
9213 (ret "")
9214 (eat 0)
9215 (sum 0))
9216 (while bytes
9217 (let* ((val (string-to-number (pop bytes) 16))
9218 (shift-xor
9219 (if (= 0 eat)
9220 (cond
9221 ((>= val 252) (cons 6 252))
9222 ((>= val 248) (cons 5 248))
9223 ((>= val 240) (cons 4 240))
9224 ((>= val 224) (cons 3 224))
9225 ((>= val 192) (cons 2 192))
9226 (t (cons 0 0)))
9227 (cons 6 128))))
9228 (if (>= val 192) (setq eat (car shift-xor)))
9229 (setq val (logxor val (cdr shift-xor)))
9230 (setq sum (+ (lsh sum (car shift-xor)) val))
9231 (if (> eat 0) (setq eat (- eat 1)))
9232 (cond
9233 ((= 0 eat) ;multi byte
9234 (setq ret (concat ret (org-char-to-string sum)))
9235 (setq sum 0))
9236 ((not bytes) ; single byte(s)
9237 (setq ret (org-link-unescape-single-byte-sequence hex))))
9238 )) ;; end (while bytes
9239 ret )))
9241 (defun org-link-unescape-single-byte-sequence (hex)
9242 "Unhexify hex-encoded single byte character sequences."
9243 (mapconcat (lambda (byte)
9244 (char-to-string (string-to-number byte 16)))
9245 (cdr (split-string hex "%")) ""))
9247 (defun org-xor (a b)
9248 "Exclusive or."
9249 (if a (not b) b))
9251 (defun org-fixup-message-id-for-http (s)
9252 "Replace special characters in a message id, so it can be used in an http query."
9253 (when (string-match "%" s)
9254 (setq s (mapconcat (lambda (c)
9255 (if (eq c ?%)
9256 "%25"
9257 (char-to-string c)))
9258 s "")))
9259 (while (string-match "<" s)
9260 (setq s (replace-match "%3C" t t s)))
9261 (while (string-match ">" s)
9262 (setq s (replace-match "%3E" t t s)))
9263 (while (string-match "@" s)
9264 (setq s (replace-match "%40" t t s)))
9267 (defun org-link-prettify (link)
9268 "Return a human-readable representation of LINK.
9269 The car of LINK must be a raw link the cdr of LINK must be either
9270 a link description or nil."
9271 (let ((desc (or (cadr link) "<no description>")))
9272 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9273 "<" (car link) ">")))
9275 ;;;###autoload
9276 (defun org-insert-link-global ()
9277 "Insert a link like Org-mode does.
9278 This command can be called in any mode to insert a link in Org-mode syntax."
9279 (interactive)
9280 (org-load-modules-maybe)
9281 (org-run-like-in-org-mode 'org-insert-link))
9283 (defun org-insert-all-links (&optional keep)
9284 "Insert all links in `org-stored-links'."
9285 (interactive "P")
9286 (let ((links (copy-sequence org-stored-links)) l)
9287 (while (setq l (if keep (pop links) (pop org-stored-links)))
9288 (insert "- ")
9289 (org-insert-link nil (car l) (cadr l))
9290 (insert "\n"))))
9292 (defun org-link-fontify-links-to-this-file ()
9293 "Fontify links to the current file in `org-stored-links'."
9294 (let ((f (buffer-file-name)) a b)
9295 (setq a (mapcar (lambda(l)
9296 (let ((ll (car l)))
9297 (when (and (string-match "^file:\\(.+\\)::" ll)
9298 (equal f (expand-file-name (match-string 1 ll))))
9299 ll)))
9300 org-stored-links))
9301 (when (featurep 'org-id)
9302 (setq b (mapcar (lambda(l)
9303 (let ((ll (car l)))
9304 (when (and (string-match "^id:\\(.+\\)$" ll)
9305 (equal f (expand-file-name
9306 (or (org-id-find-id-file
9307 (match-string 1 ll)) ""))))
9308 ll)))
9309 org-stored-links)))
9310 (mapcar (lambda(l)
9311 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9312 (delq nil (append a b)))))
9314 (defvar org-link-links-in-this-file nil)
9315 (defun org-insert-link (&optional complete-file link-location default-description)
9316 "Insert a link. At the prompt, enter the link.
9318 Completion can be used to insert any of the link protocol prefixes like
9319 http or ftp in use.
9321 The history can be used to select a link previously stored with
9322 `org-store-link'. When the empty string is entered (i.e. if you just
9323 press RET at the prompt), the link defaults to the most recently
9324 stored link. As SPC triggers completion in the minibuffer, you need to
9325 use M-SPC or C-q SPC to force the insertion of a space character.
9327 You will also be prompted for a description, and if one is given, it will
9328 be displayed in the buffer instead of the link.
9330 If there is already a link at point, this command will allow you to edit link
9331 and description parts.
9333 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9334 be selected using completion. The path to the file will be relative to the
9335 current directory if the file is in the current directory or a subdirectory.
9336 Otherwise, the link will be the absolute path as completed in the minibuffer
9337 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9338 option `org-link-file-path-type'.
9340 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9341 the current directory or below.
9343 With three \\[universal-argument] prefixes, negate the meaning of
9344 `org-keep-stored-link-after-insertion'.
9346 If `org-make-link-description-function' is non-nil, this function will be
9347 called with the link target, and the result will be the default
9348 link description.
9350 If the LINK-LOCATION parameter is non-nil, this value will be
9351 used as the link location instead of reading one interactively.
9353 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9354 be used as the default description."
9355 (interactive "P")
9356 (let* ((wcf (current-window-configuration))
9357 (region (if (org-region-active-p)
9358 (buffer-substring (region-beginning) (region-end))))
9359 (remove (and region (list (region-beginning) (region-end))))
9360 (desc region)
9361 tmphist ; byte-compile incorrectly complains about this
9362 (link link-location)
9363 (abbrevs org-link-abbrev-alist-local)
9364 entry file all-prefixes auto-desc)
9365 (cond
9366 (link-location) ; specified by arg, just use it.
9367 ((org-in-regexp org-bracket-link-regexp 1)
9368 ;; We do have a link at point, and we are going to edit it.
9369 (setq remove (list (match-beginning 0) (match-end 0)))
9370 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9371 (setq link (read-string "Link: "
9372 (org-link-unescape
9373 (org-match-string-no-properties 1)))))
9374 ((or (org-in-regexp org-angle-link-re)
9375 (org-in-regexp org-plain-link-re))
9376 ;; Convert to bracket link
9377 (setq remove (list (match-beginning 0) (match-end 0))
9378 link (read-string "Link: "
9379 (org-remove-angle-brackets (match-string 0)))))
9380 ((member complete-file '((4) (16)))
9381 ;; Completing read for file names.
9382 (setq link (org-file-complete-link complete-file)))
9384 ;; Read link, with completion for stored links.
9385 (org-link-fontify-links-to-this-file)
9386 (org-switch-to-buffer-other-window "*Org Links*")
9387 (with-current-buffer "*Org Links*"
9388 (erase-buffer)
9389 (insert "Insert a link.
9390 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9391 (when org-stored-links
9392 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9393 (insert (mapconcat 'org-link-prettify
9394 (reverse org-stored-links) "\n")))
9395 (goto-char (point-min)))
9396 (let ((cw (selected-window)))
9397 (select-window (get-buffer-window "*Org Links*" 'visible))
9398 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9399 (unless (pos-visible-in-window-p (point-max))
9400 (org-fit-window-to-buffer))
9401 (and (window-live-p cw) (select-window cw)))
9402 ;; Fake a link history, containing the stored links.
9403 (setq tmphist (append (mapcar 'car org-stored-links)
9404 org-insert-link-history))
9405 (setq all-prefixes (append (mapcar 'car abbrevs)
9406 (mapcar 'car org-link-abbrev-alist)
9407 org-link-types))
9408 (unwind-protect
9409 (progn
9410 (setq link
9411 (let ((org-completion-use-ido nil)
9412 (org-completion-use-iswitchb nil))
9413 (org-completing-read
9414 "Link: "
9415 (append
9416 (mapcar (lambda (x) (list (concat x ":")))
9417 all-prefixes)
9418 (mapcar 'car org-stored-links)
9419 (mapcar 'cadr org-stored-links))
9420 nil nil nil
9421 'tmphist
9422 (caar org-stored-links))))
9423 (if (not (string-match "\\S-" link))
9424 (error "No link selected"))
9425 (mapc (lambda(l)
9426 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9427 org-stored-links)
9428 (if (or (member link all-prefixes)
9429 (and (equal ":" (substring link -1))
9430 (member (substring link 0 -1) all-prefixes)
9431 (setq link (substring link 0 -1))))
9432 (setq link (org-link-try-special-completion link))))
9433 (set-window-configuration wcf)
9434 (kill-buffer "*Org Links*"))
9435 (setq entry (assoc link org-stored-links))
9436 (or entry (push link org-insert-link-history))
9437 (setq desc (or desc (nth 1 entry)))))
9439 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9440 (not org-keep-stored-link-after-insertion))
9441 (setq org-stored-links (delq (assoc link org-stored-links)
9442 org-stored-links)))
9444 (if (string-match org-plain-link-re link)
9445 ;; URL-like link, normalize the use of angular brackets.
9446 (setq link (org-remove-angle-brackets link)))
9448 ;; Check if we are linking to the current file with a search option
9449 ;; If yes, simplify the link by using only the search option.
9450 (when (and buffer-file-name
9451 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9452 (let* ((path (match-string 1 link))
9453 (case-fold-search nil)
9454 (search (match-string 2 link)))
9455 (save-match-data
9456 (if (equal (file-truename buffer-file-name) (file-truename path))
9457 ;; We are linking to this same file, with a search option
9458 (setq link search)))))
9460 ;; Check if we can/should use a relative path. If yes, simplify the link
9461 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9462 (let* ((type (match-string 1 link))
9463 (path (match-string 2 link))
9464 (origpath path)
9465 (case-fold-search nil))
9466 (cond
9467 ((or (eq org-link-file-path-type 'absolute)
9468 (equal complete-file '(16)))
9469 (setq path (abbreviate-file-name (expand-file-name path))))
9470 ((eq org-link-file-path-type 'noabbrev)
9471 (setq path (expand-file-name path)))
9472 ((eq org-link-file-path-type 'relative)
9473 (setq path (file-relative-name path)))
9475 (save-match-data
9476 (if (string-match (concat "^" (regexp-quote
9477 (expand-file-name
9478 (file-name-as-directory
9479 default-directory))))
9480 (expand-file-name path))
9481 ;; We are linking a file with relative path name.
9482 (setq path (substring (expand-file-name path)
9483 (match-end 0)))
9484 (setq path (abbreviate-file-name (expand-file-name path)))))))
9485 (setq link (concat type path))
9486 (if (equal desc origpath)
9487 (setq desc path))))
9489 (if org-make-link-description-function
9490 (setq desc
9491 (or (condition-case nil
9492 (funcall org-make-link-description-function link desc)
9493 (error (progn (message "Can't get link description from `%s'"
9494 (symbol-name org-make-link-description-function))
9495 (sit-for 2) nil)))
9496 (read-string "Description: " default-description)))
9497 (if default-description (setq desc default-description)
9498 (setq desc (or (and auto-desc desc)
9499 (read-string "Description: " desc)))))
9501 (unless (string-match "\\S-" desc) (setq desc nil))
9502 (if remove (apply 'delete-region remove))
9503 (insert (org-make-link-string link desc))))
9505 (defun org-link-try-special-completion (type)
9506 "If there is completion support for link type TYPE, offer it."
9507 (let ((fun (intern (concat "org-" type "-complete-link"))))
9508 (if (functionp fun)
9509 (funcall fun)
9510 (read-string "Link (no completion support): " (concat type ":")))))
9512 (defun org-file-complete-link (&optional arg)
9513 "Create a file link using completion."
9514 (let (file link)
9515 (setq file (read-file-name "File: "))
9516 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9517 (pwd1 (file-name-as-directory (abbreviate-file-name
9518 (expand-file-name ".")))))
9519 (cond
9520 ((equal arg '(16))
9521 (setq link (concat
9522 "file:"
9523 (abbreviate-file-name (expand-file-name file)))))
9524 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9525 (setq link (concat "file:" (match-string 1 file))))
9526 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9527 (expand-file-name file))
9528 (setq link (concat
9529 "file:" (match-string 1 (expand-file-name file)))))
9530 (t (setq link (concat "file:" file)))))
9531 link))
9533 (defun org-completing-read (&rest args)
9534 "Completing-read with SPACE being a normal character."
9535 (let ((enable-recursive-minibuffers t)
9536 (minibuffer-local-completion-map
9537 (copy-keymap minibuffer-local-completion-map)))
9538 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9539 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9540 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9541 (apply 'org-icompleting-read args)))
9543 (defun org-completing-read-no-i (&rest args)
9544 (let (org-completion-use-ido org-completion-use-iswitchb)
9545 (apply 'org-completing-read args)))
9547 (defun org-iswitchb-completing-read (prompt choices &rest args)
9548 "Use iswitch as a completing-read replacement to choose from choices.
9549 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9550 from."
9551 (let* ((iswitchb-use-virtual-buffers nil)
9552 (iswitchb-make-buflist-hook
9553 (lambda ()
9554 (setq iswitchb-temp-buflist choices))))
9555 (iswitchb-read-buffer prompt)))
9557 (defun org-icompleting-read (&rest args)
9558 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9559 (org-without-partial-completion
9560 (if (and org-completion-use-ido
9561 (fboundp 'ido-completing-read)
9562 (boundp 'ido-mode) ido-mode
9563 (listp (second args)))
9564 (let ((ido-enter-matching-directory nil))
9565 (apply 'ido-completing-read (concat (car args))
9566 (if (consp (car (nth 1 args)))
9567 (mapcar 'car (nth 1 args))
9568 (nth 1 args))
9569 (cddr args)))
9570 (if (and org-completion-use-iswitchb
9571 (boundp 'iswitchb-mode) iswitchb-mode
9572 (listp (second args)))
9573 (apply 'org-iswitchb-completing-read (concat (car args))
9574 (if (consp (car (nth 1 args)))
9575 (mapcar 'car (nth 1 args))
9576 (nth 1 args))
9577 (cddr args))
9578 (apply 'completing-read args)))))
9580 (defun org-extract-attributes (s)
9581 "Extract the attributes cookie from a string and set as text property."
9582 (let (a attr (start 0) key value)
9583 (save-match-data
9584 (when (string-match "{{\\([^}]+\\)}}$" s)
9585 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9586 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9587 (setq key (match-string 1 a) value (match-string 2 a)
9588 start (match-end 0)
9589 attr (plist-put attr (intern key) value))))
9590 (org-add-props s nil 'org-attr attr))
9593 (defun org-extract-attributes-from-string (tag)
9594 (let (key value attr)
9595 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9596 (setq key (match-string 1 tag) value (match-string 2 tag)
9597 tag (replace-match "" t t tag)
9598 attr (plist-put attr (intern key) value)))
9599 (cons tag attr)))
9601 (defun org-attributes-to-string (plist)
9602 "Format a property list into an HTML attribute list."
9603 (let ((s "") key value)
9604 (while plist
9605 (setq key (pop plist) value (pop plist))
9606 (and value
9607 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9610 ;;; Opening/following a link
9612 (defvar org-link-search-failed nil)
9614 (defvar org-open-link-functions nil
9615 "Hook for functions finding a plain text link.
9616 These functions must take a single argument, the link content.
9617 They will be called for links that look like [[link text][description]]
9618 when LINK TEXT does not have a protocol like \"http:\" and does not look
9619 like a filename (e.g. \"./blue.png\").
9621 These functions will be called *before* Org attempts to resolve the
9622 link by doing text searches in the current buffer - so if you want a
9623 link \"[[target]]\" to still find \"<<target>>\", your function should
9624 handle this as a special case.
9626 When the function does handle the link, it must return a non-nil value.
9627 If it decides that it is not responsible for this link, it must return
9628 nil to indicate that that Org-mode can continue with other options
9629 like exact and fuzzy text search.")
9631 (defun org-next-link ()
9632 "Move forward to the next link.
9633 If the link is in hidden text, expose it."
9634 (interactive)
9635 (when (and org-link-search-failed (eq this-command last-command))
9636 (goto-char (point-min))
9637 (message "Link search wrapped back to beginning of buffer"))
9638 (setq org-link-search-failed nil)
9639 (let* ((pos (point))
9640 (ct (org-context))
9641 (a (assoc :link ct)))
9642 (if a (goto-char (nth 2 a)))
9643 (if (re-search-forward org-any-link-re nil t)
9644 (progn
9645 (goto-char (match-beginning 0))
9646 (if (outline-invisible-p) (org-show-context)))
9647 (goto-char pos)
9648 (setq org-link-search-failed t)
9649 (error "No further link found"))))
9651 (defun org-previous-link ()
9652 "Move backward to the previous link.
9653 If the link is in hidden text, expose it."
9654 (interactive)
9655 (when (and org-link-search-failed (eq this-command last-command))
9656 (goto-char (point-max))
9657 (message "Link search wrapped back to end of buffer"))
9658 (setq org-link-search-failed nil)
9659 (let* ((pos (point))
9660 (ct (org-context))
9661 (a (assoc :link ct)))
9662 (if a (goto-char (nth 1 a)))
9663 (if (re-search-backward org-any-link-re nil t)
9664 (progn
9665 (goto-char (match-beginning 0))
9666 (if (outline-invisible-p) (org-show-context)))
9667 (goto-char pos)
9668 (setq org-link-search-failed t)
9669 (error "No further link found"))))
9671 (defun org-translate-link (s)
9672 "Translate a link string if a translation function has been defined."
9673 (if (and org-link-translation-function
9674 (fboundp org-link-translation-function)
9675 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9676 (progn
9677 (setq s (funcall org-link-translation-function
9678 (match-string 1 s) (match-string 2 s)))
9679 (concat (car s) ":" (cdr s)))
9682 (defun org-translate-link-from-planner (type path)
9683 "Translate a link from Emacs Planner syntax so that Org can follow it.
9684 This is still an experimental function, your mileage may vary."
9685 (cond
9686 ((member type '("http" "https" "news" "ftp"))
9687 ;; standard Internet links are the same.
9688 nil)
9689 ((and (equal type "irc") (string-match "^//" path))
9690 ;; Planner has two / at the beginning of an irc link, we have 1.
9691 ;; We should have zero, actually....
9692 (setq path (substring path 1)))
9693 ((and (equal type "lisp") (string-match "^/" path))
9694 ;; Planner has a slash, we do not.
9695 (setq type "elisp" path (substring path 1)))
9696 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9697 ;; A typical message link. Planner has the id after the final slash,
9698 ;; we separate it with a hash mark
9699 (setq path (concat (match-string 1 path) "#"
9700 (org-remove-angle-brackets (match-string 2 path)))))
9702 (cons type path))
9704 (defun org-find-file-at-mouse (ev)
9705 "Open file link or URL at mouse."
9706 (interactive "e")
9707 (mouse-set-point ev)
9708 (org-open-at-point 'in-emacs))
9710 (defun org-open-at-mouse (ev)
9711 "Open file link or URL at mouse.
9712 See the docstring of `org-open-file' for details."
9713 (interactive "e")
9714 (mouse-set-point ev)
9715 (if (eq major-mode 'org-agenda-mode)
9716 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9717 (org-open-at-point))
9719 (defvar org-window-config-before-follow-link nil
9720 "The window configuration before following a link.
9721 This is saved in case the need arises to restore it.")
9723 (defvar org-open-link-marker (make-marker)
9724 "Marker pointing to the location where `org-open-at-point; was called.")
9726 ;;;###autoload
9727 (defun org-open-at-point-global ()
9728 "Follow a link like Org-mode does.
9729 This command can be called in any mode to follow a link that has
9730 Org-mode syntax."
9731 (interactive)
9732 (org-run-like-in-org-mode 'org-open-at-point))
9734 ;;;###autoload
9735 (defun org-open-link-from-string (s &optional arg reference-buffer)
9736 "Open a link in the string S, as if it was in Org-mode."
9737 (interactive "sLink: \nP")
9738 (let ((reference-buffer (or reference-buffer (current-buffer))))
9739 (with-temp-buffer
9740 (let ((org-inhibit-startup (not reference-buffer)))
9741 (org-mode)
9742 (insert s)
9743 (goto-char (point-min))
9744 (when reference-buffer
9745 (setq org-link-abbrev-alist-local
9746 (with-current-buffer reference-buffer
9747 org-link-abbrev-alist-local)))
9748 (org-open-at-point arg reference-buffer)))))
9750 (defvar org-open-at-point-functions nil
9751 "Hook that is run when following a link at point.
9753 Functions in this hook must return t if they identify and follow
9754 a link at point. If they don't find anything interesting at point,
9755 they must return nil.")
9757 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9758 (defun org-open-at-point (&optional arg reference-buffer)
9759 "Open link at or after point.
9760 If there is no link at point, this function will search forward up to
9761 the end of the current line.
9762 Normally, files will be opened by an appropriate application. If the
9763 optional prefix argument ARG is non-nil, Emacs will visit the file.
9764 With a double prefix argument, try to open outside of Emacs, in the
9765 application the system uses for this file type."
9766 (interactive "P")
9767 ;; if in a code block, then open the block's results
9768 (unless (call-interactively #'org-babel-open-src-block-result)
9769 (org-load-modules-maybe)
9770 (move-marker org-open-link-marker (point))
9771 (setq org-window-config-before-follow-link (current-window-configuration))
9772 (org-remove-occur-highlights nil nil t)
9773 (cond
9774 ((and (org-at-heading-p)
9775 (not (org-at-timestamp-p t))
9776 (not (org-in-regexp
9777 (concat org-plain-link-re "\\|"
9778 org-bracket-link-regexp "\\|"
9779 org-angle-link-re "\\|"
9780 "[ \t]:[^ \t\n]+:[ \t]*$")))
9781 (not (get-text-property (point) 'org-linked-text)))
9782 (or (org-offer-links-in-entry arg)
9783 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9784 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9785 ((and (org-at-timestamp-p t)
9786 (not (org-in-regexp org-bracket-link-regexp)))
9787 (org-follow-timestamp-link))
9788 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9789 (not (org-in-regexp org-bracket-link-regexp)))
9790 (org-footnote-action))
9792 (let (type path link line search (pos (point)))
9793 (catch 'match
9794 (save-excursion
9795 (skip-chars-forward "^]\n\r")
9796 (when (org-in-regexp org-bracket-link-regexp 1)
9797 (setq link (org-extract-attributes
9798 (org-link-unescape (org-match-string-no-properties 1))))
9799 (while (string-match " *\n *" link)
9800 (setq link (replace-match " " t t link)))
9801 (setq link (org-link-expand-abbrev link))
9802 (cond
9803 ((or (file-name-absolute-p link)
9804 (string-match "^\\.\\.?/" link))
9805 (setq type "file" path link))
9806 ((string-match org-link-re-with-space3 link)
9807 (setq type (match-string 1 link) path (match-string 2 link)))
9808 ((string-match "^help:+\\(.+\\)" link)
9809 (setq type "help" path (match-string 1 link)))
9810 (t (setq type "thisfile" path link)))
9811 (throw 'match t)))
9813 (when (get-text-property (point) 'org-linked-text)
9814 (setq type "thisfile"
9815 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9816 (1+ (point)) (point))
9817 path (buffer-substring
9818 (or (previous-single-property-change pos 'org-linked-text)
9819 (point-min))
9820 (or (next-single-property-change pos 'org-linked-text)
9821 (point-max))))
9822 (throw 'match t))
9824 (save-excursion
9825 (when (or (org-in-regexp org-angle-link-re)
9826 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9827 (save-match-data (not (looking-back "\\[\\[")))))
9828 (setq type (match-string 1)
9829 path (org-link-unescape (match-string 2)))
9830 (throw 'match t)))
9831 (save-excursion
9832 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9833 (setq type "tags"
9834 path (match-string 1))
9835 (while (string-match ":" path)
9836 (setq path (replace-match "+" t t path)))
9837 (throw 'match t)))
9838 (when (org-in-regexp "<\\([^><\n]+\\)>")
9839 (setq type "tree-match"
9840 path (match-string 1))
9841 (throw 'match t)))
9842 (unless path
9843 (error "No link found"))
9845 ;; switch back to reference buffer
9846 ;; needed when if called in a temporary buffer through
9847 ;; org-open-link-from-string
9848 (with-current-buffer (or reference-buffer (current-buffer))
9850 ;; Remove any trailing spaces in path
9851 (if (string-match " +\\'" path)
9852 (setq path (replace-match "" t t path)))
9853 (if (and org-link-translation-function
9854 (fboundp org-link-translation-function))
9855 ;; Check if we need to translate the link
9856 (let ((tmp (funcall org-link-translation-function type path)))
9857 (setq type (car tmp) path (cdr tmp))))
9859 (cond
9861 ((assoc type org-link-protocols)
9862 (funcall (nth 1 (assoc type org-link-protocols)) path))
9864 ((equal type "help")
9865 (let ((f-or-v (intern path)))
9866 (cond ((fboundp f-or-v)
9867 (describe-function f-or-v))
9868 ((boundp f-or-v)
9869 (describe-variable f-or-v))
9870 (t (error "Not a known function or variable")))))
9872 ((equal type "mailto")
9873 (let ((cmd (car org-link-mailto-program))
9874 (args (cdr org-link-mailto-program)) args1
9875 (address path) (subject "") a)
9876 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9877 (setq address (match-string 1 path)
9878 subject (org-link-escape (match-string 2 path))))
9879 (while args
9880 (cond
9881 ((not (stringp (car args))) (push (pop args) args1))
9882 (t (setq a (pop args))
9883 (if (string-match "%a" a)
9884 (setq a (replace-match address t t a)))
9885 (if (string-match "%s" a)
9886 (setq a (replace-match subject t t a)))
9887 (push a args1))))
9888 (apply cmd (nreverse args1))))
9890 ((member type '("http" "https" "ftp" "news"))
9891 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9892 (org-link-escape
9893 path org-link-escape-chars-browser)
9894 path))))
9896 ((string= type "doi")
9897 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9898 (org-link-escape
9899 path org-link-escape-chars-browser)
9900 path))))
9902 ((member type '("message"))
9903 (browse-url (concat type ":" path)))
9905 ((string= type "tags")
9906 (org-tags-view arg path))
9908 ((string= type "tree-match")
9909 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9911 ((string= type "file")
9912 (if (string-match "::\\([0-9]+\\)\\'" path)
9913 (setq line (string-to-number (match-string 1 path))
9914 path (substring path 0 (match-beginning 0)))
9915 (if (string-match "::\\(.+\\)\\'" path)
9916 (setq search (match-string 1 path)
9917 path (substring path 0 (match-beginning 0)))))
9918 (if (string-match "[*?{]" (file-name-nondirectory path))
9919 (dired path)
9920 (org-open-file path arg line search)))
9922 ((string= type "shell")
9923 (let ((buf (generate-new-buffer "*Org Shell Output"))
9924 (cmd path))
9925 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9926 (string-match org-confirm-shell-link-not-regexp cmd))
9927 (not org-confirm-shell-link-function)
9928 (funcall org-confirm-shell-link-function
9929 (format "Execute \"%s\" in shell? "
9930 (org-add-props cmd nil
9931 'face 'org-warning))))
9932 (progn
9933 (message "Executing %s" cmd)
9934 (shell-command cmd buf)
9935 (if (featurep 'midnight)
9936 (setq clean-buffer-list-kill-buffer-names
9937 (cons buf clean-buffer-list-kill-buffer-names))))
9938 (error "Abort"))))
9940 ((string= type "elisp")
9941 (let ((cmd path))
9942 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9943 (string-match org-confirm-elisp-link-not-regexp cmd))
9944 (not org-confirm-elisp-link-function)
9945 (funcall org-confirm-elisp-link-function
9946 (format "Execute \"%s\" as elisp? "
9947 (org-add-props cmd nil
9948 'face 'org-warning))))
9949 (message "%s => %s" cmd
9950 (if (equal (string-to-char cmd) ?\()
9951 (eval (read cmd))
9952 (call-interactively (read cmd))))
9953 (error "Abort"))))
9955 ((and (string= type "thisfile")
9956 (run-hook-with-args-until-success
9957 'org-open-link-functions path)))
9959 ((string= type "thisfile")
9960 (if arg
9961 (switch-to-buffer-other-window
9962 (org-get-buffer-for-internal-link (current-buffer)))
9963 (org-mark-ring-push))
9964 (let ((cmd `(org-link-search
9965 ,path
9966 ,(cond ((equal arg '(4)) ''occur)
9967 ((equal arg '(16)) ''org-occur))
9968 ,pos)))
9969 (condition-case nil (let ((org-link-search-inhibit-query t))
9970 (eval cmd))
9971 (error (progn (widen) (eval cmd))))))
9973 (t (browse-url-at-point)))))))
9974 (move-marker org-open-link-marker nil)
9975 (run-hook-with-args 'org-follow-link-hook)))
9977 (defun org-offer-links-in-entry (&optional nth zero)
9978 "Offer links in the current entry and follow the selected link.
9979 If there is only one link, follow it immediately as well.
9980 If NTH is an integer, immediately pick the NTH link found.
9981 If ZERO is a string, check also this string for a link, and if
9982 there is one, offer it as link number zero."
9983 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9984 "\\(" org-angle-link-re "\\)\\|"
9985 "\\(" org-plain-link-re "\\)"))
9986 (cnt ?0)
9987 (in-emacs (if (integerp nth) nil nth))
9988 have-zero end links link c)
9989 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9990 (push (match-string 0 zero) links)
9991 (setq cnt (1- cnt) have-zero t))
9992 (save-excursion
9993 (org-back-to-heading t)
9994 (setq end (save-excursion (outline-next-heading) (point)))
9995 (while (re-search-forward re end t)
9996 (push (match-string 0) links))
9997 (setq links (org-uniquify (reverse links))))
9999 (cond
10000 ((null links)
10001 (message "No links"))
10002 ((equal (length links) 1)
10003 (setq link (list (car links))))
10004 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10005 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10006 (t ; we have to select a link
10007 (save-excursion
10008 (save-window-excursion
10009 (delete-other-windows)
10010 (with-output-to-temp-buffer "*Select Link*"
10011 (mapc (lambda (l)
10012 (if (not (string-match org-bracket-link-regexp l))
10013 (princ (format "[%c] %s\n" (incf cnt)
10014 (org-remove-angle-brackets l)))
10015 (if (match-end 3)
10016 (princ (format "[%c] %s (%s)\n" (incf cnt)
10017 (match-string 3 l) (match-string 1 l)))
10018 (princ (format "[%c] %s\n" (incf cnt)
10019 (match-string 1 l))))))
10020 links))
10021 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10022 (message "Select link to open, RET to open all:")
10023 (setq c (read-char-exclusive))
10024 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10025 (when (equal c ?q) (error "Abort"))
10026 (if (equal c ?\C-m)
10027 (setq link links)
10028 (setq nth (- c ?0))
10029 (if have-zero (setq nth (1+ nth)))
10030 (unless (and (integerp nth) (>= (length links) nth))
10031 (error "Invalid link selection"))
10032 (setq link (list (nth (1- nth) links))))))
10033 (if link
10034 (let ((buf (current-buffer)))
10035 (dolist (l link)
10036 (org-open-link-from-string l in-emacs buf))
10038 nil)))
10040 ;; Add special file links that specify the way of opening
10042 (org-add-link-type "file+sys" 'org-open-file-with-system)
10043 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10044 (defun org-open-file-with-system (path)
10045 "Open file at PATH using the system way of opening it."
10046 (org-open-file path 'system))
10047 (defun org-open-file-with-emacs (path)
10048 "Open file at PATH in Emacs."
10049 (org-open-file path 'emacs))
10050 (defun org-remove-file-link-modifiers ()
10051 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10052 (goto-char (point-min))
10053 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10054 (org-if-unprotected
10055 (replace-match "file:" t t))))
10056 (eval-after-load "org-exp"
10057 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10058 'org-remove-file-link-modifiers))
10060 ;;;; Time estimates
10062 (defun org-get-effort (&optional pom)
10063 "Get the effort estimate for the current entry."
10064 (org-entry-get pom org-effort-property))
10066 ;;; File search
10068 (defvar org-create-file-search-functions nil
10069 "List of functions to construct the right search string for a file link.
10070 These functions are called in turn with point at the location to
10071 which the link should point.
10073 A function in the hook should first test if it would like to
10074 handle this file type, for example by checking the `major-mode'
10075 or the file extension. If it decides not to handle this file, it
10076 should just return nil to give other functions a chance. If it
10077 does handle the file, it must return the search string to be used
10078 when following the link. The search string will be part of the
10079 file link, given after a double colon, and `org-open-at-point'
10080 will automatically search for it. If special measures must be
10081 taken to make the search successful, another function should be
10082 added to the companion hook `org-execute-file-search-functions',
10083 which see.
10085 A function in this hook may also use `setq' to set the variable
10086 `description' to provide a suggestion for the descriptive text to
10087 be used for this link when it gets inserted into an Org-mode
10088 buffer with \\[org-insert-link].")
10090 (defvar org-execute-file-search-functions nil
10091 "List of functions to execute a file search triggered by a link.
10093 Functions added to this hook must accept a single argument, the
10094 search string that was part of the file link, the part after the
10095 double colon. The function must first check if it would like to
10096 handle this search, for example by checking the `major-mode' or
10097 the file extension. If it decides not to handle this search, it
10098 should just return nil to give other functions a chance. If it
10099 does handle the search, it must return a non-nil value to keep
10100 other functions from trying.
10102 Each function can access the current prefix argument through the
10103 variable `current-prefix-argument'. Note that a single prefix is
10104 used to force opening a link in Emacs, so it may be good to only
10105 use a numeric or double prefix to guide the search function.
10107 In case this is needed, a function in this hook can also restore
10108 the window configuration before `org-open-at-point' was called using:
10110 (set-window-configuration org-window-config-before-follow-link)")
10112 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10113 (defun org-link-search (s &optional type avoid-pos stealth)
10114 "Search for a link search option.
10115 If S is surrounded by forward slashes, it is interpreted as a
10116 regular expression. In org-mode files, this will create an `org-occur'
10117 sparse tree. In ordinary files, `occur' will be used to list matches.
10118 If the current buffer is in `dired-mode', grep will be used to search
10119 in all files. If AVOID-POS is given, ignore matches near that position.
10121 When optional argument STEALTH is non-nil, do not modify
10122 visibility around point, thus ignoring
10123 `org-show-hierarchy-above', `org-show-following-heading' and
10124 `org-show-siblings' variables."
10125 (let ((case-fold-search t)
10126 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10127 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10128 (append '(("") (" ") ("\t") ("\n"))
10129 org-emphasis-alist)
10130 "\\|") "\\)"))
10131 (pos (point))
10132 (pre nil) (post nil)
10133 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10134 (cond
10135 ;; First check if there are any special search functions
10136 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10137 ;; Now try the builtin stuff
10138 ((and (equal (string-to-char s0) ?#)
10139 (> (length s0) 1)
10140 (save-excursion
10141 (goto-char (point-min))
10142 (and
10143 (re-search-forward
10144 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10145 (setq type 'dedicated
10146 pos (match-beginning 0))))
10147 ;; There is an exact target for this
10148 (goto-char pos)
10149 (org-back-to-heading t)))
10150 ((save-excursion
10151 (goto-char (point-min))
10152 (and
10153 (re-search-forward
10154 (concat "<<" (regexp-quote s0) ">>") nil t)
10155 (setq type 'dedicated
10156 pos (match-beginning 0))))
10157 ;; There is an exact target for this
10158 (goto-char pos))
10159 ((save-excursion
10160 (goto-char (point-min))
10161 (and
10162 (re-search-forward
10163 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10164 (setq type 'dedicated pos (match-beginning 0))))
10165 ;; Found an invisible target.
10166 (goto-char pos))
10167 ((save-excursion
10168 (goto-char (point-min))
10169 (and
10170 (re-search-forward
10171 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10172 (setq type 'dedicated pos (match-beginning 0))))
10173 ;; Found an element with a matching #+name affiliated keyword.
10174 (goto-char pos))
10175 ((and (string-match "^(\\(.*\\))$" s0)
10176 (save-excursion
10177 (goto-char (point-min))
10178 (and
10179 (re-search-forward
10180 (concat "[^[]" (regexp-quote
10181 (format org-coderef-label-format
10182 (match-string 1 s0))))
10183 nil t)
10184 (setq type 'dedicated
10185 pos (1+ (match-beginning 0))))))
10186 ;; There is a coderef target for this
10187 (goto-char pos))
10188 ((string-match "^/\\(.*\\)/$" s)
10189 ;; A regular expression
10190 (cond
10191 ((derived-mode-p 'org-mode)
10192 (org-occur (match-string 1 s)))
10193 ;;((eq major-mode 'dired-mode)
10194 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10195 (t (org-do-occur (match-string 1 s)))))
10196 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10197 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10198 (goto-char (point-min))
10199 (cond
10200 ((let (case-fold-search)
10201 (re-search-forward (format org-complex-heading-regexp-format
10202 (regexp-quote s))
10203 nil t))
10204 ;; OK, found a match
10205 (setq type 'dedicated)
10206 (goto-char (match-beginning 0)))
10207 ((and (not org-link-search-inhibit-query)
10208 (eq org-link-search-must-match-exact-headline 'query-to-create)
10209 (y-or-n-p "No match - create this as a new heading? "))
10210 (goto-char (point-max))
10211 (or (bolp) (newline))
10212 (insert "* " s "\n")
10213 (beginning-of-line 0))
10215 (goto-char pos)
10216 (error "No match"))))
10218 ;; A normal search string
10219 (when (equal (string-to-char s) ?*)
10220 ;; Anchor on headlines, post may include tags.
10221 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10222 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10223 s (substring s 1)))
10224 (remove-text-properties
10225 0 (length s)
10226 '(face nil mouse-face nil keymap nil fontified nil) s)
10227 ;; Make a series of regular expressions to find a match
10228 (setq words (org-split-string s "[ \n\r\t]+")
10230 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10231 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10232 "\\)" markers)
10233 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10234 re2a (concat "[ \t\r\n]" re2a_)
10235 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10236 re4 (concat "[^a-zA-Z_]" re4_)
10238 re1 (concat pre re2 post)
10239 re3 (concat pre (if pre re4_ re4) post)
10240 re5 (concat pre ".*" re4)
10241 re2 (concat pre re2)
10242 re2a (concat pre (if pre re2a_ re2a))
10243 re4 (concat pre (if pre re4_ re4))
10244 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10245 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10246 re5 "\\)"
10248 (cond
10249 ((eq type 'org-occur) (org-occur reall))
10250 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10251 (t (goto-char (point-min))
10252 (setq type 'fuzzy)
10253 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10254 (org-search-not-self 1 re1 nil t)
10255 (org-search-not-self 1 re2 nil t)
10256 (org-search-not-self 1 re2a nil t)
10257 (org-search-not-self 1 re3 nil t)
10258 (org-search-not-self 1 re4 nil t)
10259 (org-search-not-self 1 re5 nil t)
10261 (goto-char (match-beginning 1))
10262 (goto-char pos)
10263 (error "No match"))))))
10264 (and (derived-mode-p 'org-mode)
10265 (not stealth)
10266 (org-show-context 'link-search))
10267 type))
10269 (defun org-search-not-self (group &rest args)
10270 "Execute `re-search-forward', but only accept matches that do not
10271 enclose the position of `org-open-link-marker'."
10272 (let ((m org-open-link-marker))
10273 (catch 'exit
10274 (while (apply 're-search-forward args)
10275 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10276 (goto-char (match-end group))
10277 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10278 (> (match-beginning 0) (marker-position m))
10279 (< (match-end 0) (marker-position m)))
10280 (save-match-data
10281 (or (not (org-in-regexp
10282 org-bracket-link-analytic-regexp 1))
10283 (not (match-end 4)) ; no description
10284 (and (<= (match-beginning 4) (point))
10285 (>= (match-end 4) (point))))))
10286 (throw 'exit (point))))))))
10288 (defun org-get-buffer-for-internal-link (buffer)
10289 "Return a buffer to be used for displaying the link target of internal links."
10290 (cond
10291 ((not org-display-internal-link-with-indirect-buffer)
10292 buffer)
10293 ((string-match "(Clone)$" (buffer-name buffer))
10294 (message "Buffer is already a clone, not making another one")
10295 ;; we also do not modify visibility in this case
10296 buffer)
10297 (t ; make a new indirect buffer for displaying the link
10298 (let* ((bn (buffer-name buffer))
10299 (ibn (concat bn "(Clone)"))
10300 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10301 (with-current-buffer ib (org-overview))
10302 ib))))
10304 (defun org-do-occur (regexp &optional cleanup)
10305 "Call the Emacs command `occur'.
10306 If CLEANUP is non-nil, remove the printout of the regular expression
10307 in the *Occur* buffer. This is useful if the regex is long and not useful
10308 to read."
10309 (occur regexp)
10310 (when cleanup
10311 (let ((cwin (selected-window)) win beg end)
10312 (when (setq win (get-buffer-window "*Occur*"))
10313 (select-window win))
10314 (goto-char (point-min))
10315 (when (re-search-forward "match[a-z]+" nil t)
10316 (setq beg (match-end 0))
10317 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10318 (setq end (1- (match-beginning 0)))))
10319 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10320 (goto-char (point-min))
10321 (select-window cwin))))
10323 ;;; The mark ring for links jumps
10325 (defvar org-mark-ring nil
10326 "Mark ring for positions before jumps in Org-mode.")
10327 (defvar org-mark-ring-last-goto nil
10328 "Last position in the mark ring used to go back.")
10329 ;; Fill and close the ring
10330 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10331 (loop for i from 1 to org-mark-ring-length do
10332 (push (make-marker) org-mark-ring))
10333 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10334 org-mark-ring)
10336 (defun org-mark-ring-push (&optional pos buffer)
10337 "Put the current position or POS into the mark ring and rotate it."
10338 (interactive)
10339 (setq pos (or pos (point)))
10340 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10341 (move-marker (car org-mark-ring)
10342 (or pos (point))
10343 (or buffer (current-buffer)))
10344 (message "%s"
10345 (substitute-command-keys
10346 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10348 (defun org-mark-ring-goto (&optional n)
10349 "Jump to the previous position in the mark ring.
10350 With prefix arg N, jump back that many stored positions. When
10351 called several times in succession, walk through the entire ring.
10352 Org-mode commands jumping to a different position in the current file,
10353 or to another Org-mode file, automatically push the old position
10354 onto the ring."
10355 (interactive "p")
10356 (let (p m)
10357 (if (eq last-command this-command)
10358 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10359 (setq p org-mark-ring))
10360 (setq org-mark-ring-last-goto p)
10361 (setq m (car p))
10362 (org-pop-to-buffer-same-window (marker-buffer m))
10363 (goto-char m)
10364 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10366 (defun org-remove-angle-brackets (s)
10367 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10368 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10370 (defun org-add-angle-brackets (s)
10371 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10372 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10374 (defun org-remove-double-quotes (s)
10375 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10376 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10379 ;;; Following specific links
10381 (defun org-follow-timestamp-link ()
10382 "Open an agenda view for the time-stamp date/range at point."
10383 (cond
10384 ((org-at-date-range-p t)
10385 (let ((org-agenda-start-on-weekday)
10386 (t1 (match-string 1))
10387 (t2 (match-string 2)) tt1 tt2)
10388 (setq tt1 (time-to-days (org-time-string-to-time t1))
10389 tt2 (time-to-days (org-time-string-to-time t2)))
10390 (let ((org-agenda-buffer-tmp-name
10391 (format "*Org Agenda(a:%s)"
10392 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10393 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10394 ((org-at-timestamp-p t)
10395 (let ((org-agenda-buffer-tmp-name
10396 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10397 (org-agenda-list nil (time-to-days (org-time-string-to-time
10398 (substring (match-string 1) 0 10)))
10399 1)))
10400 (t (error "This should not happen"))))
10403 ;;; Following file links
10404 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10405 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10406 (declare-function mailcap-mime-info
10407 "mailcap" (string &optional request no-decode))
10408 (defvar org-wait nil)
10409 (defun org-open-file (path &optional in-emacs line search)
10410 "Open the file at PATH.
10411 First, this expands any special file name abbreviations. Then the
10412 configuration variable `org-file-apps' is checked if it contains an
10413 entry for this file type, and if yes, the corresponding command is launched.
10415 If no application is found, Emacs simply visits the file.
10417 With optional prefix argument IN-EMACS, Emacs will visit the file.
10418 With a double \\[universal-argument] \\[universal-argument] \
10419 prefix arg, Org tries to avoid opening in Emacs
10420 and to use an external application to visit the file.
10422 Optional LINE specifies a line to go to, optional SEARCH a string
10423 to search for. If LINE or SEARCH is given, the file will be
10424 opened in Emacs, unless an entry from org-file-apps that makes
10425 use of groups in a regexp matches.
10427 If you want to change the way frames are used when following a
10428 link, please customize `org-link-frame-setup'.
10430 If the file does not exist, an error is thrown."
10431 (let* ((file (if (equal path "")
10432 buffer-file-name
10433 (substitute-in-file-name (expand-file-name path))))
10434 (file-apps (append org-file-apps (org-default-apps)))
10435 (apps (org-remove-if
10436 'org-file-apps-entry-match-against-dlink-p file-apps))
10437 (apps-dlink (org-remove-if-not
10438 'org-file-apps-entry-match-against-dlink-p file-apps))
10439 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10440 (dirp (if remp nil (file-directory-p file)))
10441 (file (if (and dirp org-open-directory-means-index-dot-org)
10442 (concat (file-name-as-directory file) "index.org")
10443 file))
10444 (a-m-a-p (assq 'auto-mode apps))
10445 (dfile (downcase file))
10446 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10447 (link (cond ((and (eq line nil)
10448 (eq search nil))
10449 file)
10450 (line
10451 (concat file "::" (number-to-string line)))
10452 (search
10453 (concat file "::" search))))
10454 (dlink (downcase link))
10455 (old-buffer (current-buffer))
10456 (old-pos (point))
10457 (old-mode major-mode)
10458 ext cmd link-match-data)
10459 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10460 (setq ext (match-string 1 dfile))
10461 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10462 (setq ext (match-string 1 dfile))))
10463 (cond
10464 ((member in-emacs '((16) system))
10465 (setq cmd (cdr (assoc 'system apps))))
10466 (in-emacs (setq cmd 'emacs))
10468 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10469 (and dirp (cdr (assoc 'directory apps)))
10470 ; first, try matching against apps-dlink
10471 ; if we get a match here, store the match data for later
10472 (let ((match (assoc-default dlink apps-dlink
10473 'string-match)))
10474 (if match
10475 (progn (setq link-match-data (match-data))
10476 match)
10477 (progn (setq in-emacs (or in-emacs line search))
10478 nil))) ; if we have no match in apps-dlink,
10479 ; always open the file in emacs if line or search
10480 ; is given (for backwards compatibility)
10481 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10482 'string-match)
10483 (cdr (assoc ext apps))
10484 (cdr (assoc t apps))))))
10485 (when (eq cmd 'system)
10486 (setq cmd (cdr (assoc 'system apps))))
10487 (when (eq cmd 'default)
10488 (setq cmd (cdr (assoc t apps))))
10489 (when (eq cmd 'mailcap)
10490 (require 'mailcap)
10491 (mailcap-parse-mailcaps)
10492 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10493 (command (mailcap-mime-info mime-type)))
10494 (if (stringp command)
10495 (setq cmd command)
10496 (setq cmd 'emacs))))
10497 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10498 (not (file-exists-p file))
10499 (not org-open-non-existing-files))
10500 (error "No such file: %s" file))
10501 (cond
10502 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10503 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10504 (while (string-match "['\"]%s['\"]" cmd)
10505 (setq cmd (replace-match "%s" t t cmd)))
10506 (while (string-match "%s" cmd)
10507 (setq cmd (replace-match
10508 (save-match-data
10509 (shell-quote-argument
10510 (convert-standard-filename file)))
10511 t t cmd)))
10513 ;; Replace "%1", "%2" etc. in command with group matches from regex
10514 (save-match-data
10515 (let ((match-index 1)
10516 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10517 (set-match-data link-match-data)
10518 (while (<= match-index number-of-groups)
10519 (let ((regex (concat "%" (number-to-string match-index)))
10520 (replace-with (match-string match-index dlink)))
10521 (while (string-match regex cmd)
10522 (setq cmd (replace-match replace-with t t cmd))))
10523 (setq match-index (+ match-index 1)))))
10525 (save-window-excursion
10526 (start-process-shell-command cmd nil cmd)
10527 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10529 ((or (stringp cmd)
10530 (eq cmd 'emacs))
10531 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10532 (widen)
10533 (if line (org-goto-line line)
10534 (if search (org-link-search search))))
10535 ((consp cmd)
10536 (let ((file (convert-standard-filename file)))
10537 (save-match-data
10538 (set-match-data link-match-data)
10539 (eval cmd))))
10540 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10541 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10542 (or (not (equal old-buffer (current-buffer)))
10543 (not (equal old-pos (point))))
10544 (org-mark-ring-push old-pos old-buffer))))
10546 (defun org-file-apps-entry-match-against-dlink-p (entry)
10547 "This function returns non-nil if `entry' uses a regular
10548 expression which should be matched against the whole link by
10549 org-open-file.
10551 It assumes that is the case when the entry uses a regular
10552 expression which has at least one grouping construct and the
10553 action is either a lisp form or a command string containing
10554 '%1', i.e. using at least one subexpression match as a
10555 parameter."
10556 (let ((selector (car entry))
10557 (action (cdr entry)))
10558 (if (stringp selector)
10559 (and (> (regexp-opt-depth selector) 0)
10560 (or (and (stringp action)
10561 (string-match "%[0-9]" action))
10562 (consp action)))
10563 nil)))
10565 (defun org-default-apps ()
10566 "Return the default applications for this operating system."
10567 (cond
10568 ((eq system-type 'darwin)
10569 org-file-apps-defaults-macosx)
10570 ((eq system-type 'windows-nt)
10571 org-file-apps-defaults-windowsnt)
10572 (t org-file-apps-defaults-gnu)))
10574 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10575 "Convert extensions to regular expressions in the cars of LIST.
10576 Also, weed out any non-string entries, because the return value is used
10577 only for regexp matching.
10578 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10579 point to the symbol `emacs', indicating that the file should
10580 be opened in Emacs."
10581 (append
10582 (delq nil
10583 (mapcar (lambda (x)
10584 (if (not (stringp (car x)))
10586 (if (string-match "\\W" (car x))
10588 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10589 list))
10590 (if add-auto-mode
10591 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10593 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10594 (defun org-file-remote-p (file)
10595 "Test whether FILE specifies a location on a remote system.
10596 Return non-nil if the location is indeed remote.
10598 For example, the filename \"/user@host:/foo\" specifies a location
10599 on the system \"/user@host:\"."
10600 (cond ((fboundp 'file-remote-p)
10601 (file-remote-p file))
10602 ((fboundp 'tramp-handle-file-remote-p)
10603 (tramp-handle-file-remote-p file))
10604 ((and (boundp 'ange-ftp-name-format)
10605 (string-match (car ange-ftp-name-format) file))
10606 t)))
10609 ;;;; Refiling
10611 (defun org-get-org-file ()
10612 "Read a filename, with default directory `org-directory'."
10613 (let ((default (or org-default-notes-file remember-data-file)))
10614 (read-file-name (format "File name [%s]: " default)
10615 (file-name-as-directory org-directory)
10616 default)))
10618 (defun org-notes-order-reversed-p ()
10619 "Check if the current file should receive notes in reversed order."
10620 (cond
10621 ((not org-reverse-note-order) nil)
10622 ((eq t org-reverse-note-order) t)
10623 ((not (listp org-reverse-note-order)) nil)
10624 (t (catch 'exit
10625 (let ((all org-reverse-note-order)
10626 entry)
10627 (while (setq entry (pop all))
10628 (if (string-match (car entry) buffer-file-name)
10629 (throw 'exit (cdr entry))))
10630 nil)))))
10632 (defvar org-refile-target-table nil
10633 "The list of refile targets, created by `org-refile'.")
10635 (defvar org-agenda-new-buffers nil
10636 "Buffers created to visit agenda files.")
10638 (defvar org-refile-cache nil
10639 "Cache for refile targets.")
10641 (defvar org-refile-markers nil
10642 "All the markers used for caching refile locations.")
10644 (defun org-refile-marker (pos)
10645 "Get a new refile marker, but only if caching is in use."
10646 (if (not org-refile-use-cache)
10648 (let ((m (make-marker)))
10649 (move-marker m pos)
10650 (push m org-refile-markers)
10651 m)))
10653 (defun org-refile-cache-clear ()
10654 "Clear the refile cache and disable all the markers."
10655 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10656 (setq org-refile-markers nil)
10657 (setq org-refile-cache nil)
10658 (message "Refile cache has been cleared"))
10660 (defun org-refile-cache-check-set (set)
10661 "Check if all the markers in the cache still have live buffers."
10662 (let (marker)
10663 (catch 'exit
10664 (while (and set (setq marker (nth 3 (pop set))))
10665 ;; if org-refile-use-outline-path is 'file, marker may be nil
10666 (when (and marker (null (marker-buffer marker)))
10667 (message "not found") (sit-for 3)
10668 (throw 'exit nil)))
10669 t)))
10671 (defun org-refile-cache-put (set &rest identifiers)
10672 "Push the refile targets SET into the cache, under IDENTIFIERS."
10673 (let* ((key (sha1 (prin1-to-string identifiers)))
10674 (entry (assoc key org-refile-cache)))
10675 (if entry
10676 (setcdr entry set)
10677 (push (cons key set) org-refile-cache))))
10679 (defun org-refile-cache-get (&rest identifiers)
10680 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10681 (cond
10682 ((not org-refile-cache) nil)
10683 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10685 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10686 org-refile-cache))))
10687 (and set (org-refile-cache-check-set set) set)))))
10689 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10690 "Produce a table with refile targets."
10691 (let ((case-fold-search nil)
10692 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10693 (entries (or org-refile-targets '((nil . (:level . 1)))))
10694 targets tgs txt re files f desc descre fast-path-p level pos0)
10695 (message "Getting targets...")
10696 (with-current-buffer (or default-buffer (current-buffer))
10697 (while (setq entry (pop entries))
10698 (setq files (car entry) desc (cdr entry))
10699 (setq fast-path-p nil)
10700 (cond
10701 ((null files) (setq files (list (current-buffer))))
10702 ((eq files 'org-agenda-files)
10703 (setq files (org-agenda-files 'unrestricted)))
10704 ((and (symbolp files) (fboundp files))
10705 (setq files (funcall files)))
10706 ((and (symbolp files) (boundp files))
10707 (setq files (symbol-value files))))
10708 (if (stringp files) (setq files (list files)))
10709 (cond
10710 ((eq (car desc) :tag)
10711 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10712 ((eq (car desc) :todo)
10713 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10714 ((eq (car desc) :regexp)
10715 (setq descre (cdr desc)))
10716 ((eq (car desc) :level)
10717 (setq descre (concat "^\\*\\{" (number-to-string
10718 (if org-odd-levels-only
10719 (1- (* 2 (cdr desc)))
10720 (cdr desc)))
10721 "\\}[ \t]")))
10722 ((eq (car desc) :maxlevel)
10723 (setq fast-path-p t)
10724 (setq descre (concat "^\\*\\{1," (number-to-string
10725 (if org-odd-levels-only
10726 (1- (* 2 (cdr desc)))
10727 (cdr desc)))
10728 "\\}[ \t]")))
10729 (t (error "Bad refiling target description %s" desc)))
10730 (while (setq f (pop files))
10731 (with-current-buffer
10732 (if (bufferp f) f (org-get-agenda-file-buffer f))
10734 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10735 (progn
10736 (if (bufferp f) (setq f (buffer-file-name
10737 (buffer-base-buffer f))))
10738 (setq f (and f (expand-file-name f)))
10739 (if (eq org-refile-use-outline-path 'file)
10740 (push (list (file-name-nondirectory f) f nil nil) tgs))
10741 (save-excursion
10742 (save-restriction
10743 (widen)
10744 (goto-char (point-min))
10745 (while (re-search-forward descre nil t)
10746 (goto-char (setq pos0 (point-at-bol)))
10747 (catch 'next
10748 (when org-refile-target-verify-function
10749 (save-match-data
10750 (or (funcall org-refile-target-verify-function)
10751 (throw 'next t))))
10752 (when (and (looking-at org-complex-heading-regexp)
10753 (not (member (match-string 4) excluded-entries))
10754 (match-string 4))
10755 (setq level (org-reduced-level
10756 (- (match-end 1) (match-beginning 1)))
10757 txt (org-link-display-format (match-string 4))
10758 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10759 re (format org-complex-heading-regexp-format
10760 (regexp-quote (match-string 4))))
10761 (when org-refile-use-outline-path
10762 (setq txt (mapconcat
10763 'org-protect-slash
10764 (append
10765 (if (eq org-refile-use-outline-path
10766 'file)
10767 (list (file-name-nondirectory
10768 (buffer-file-name
10769 (buffer-base-buffer))))
10770 (if (eq org-refile-use-outline-path
10771 'full-file-path)
10772 (list (buffer-file-name
10773 (buffer-base-buffer)))))
10774 (org-get-outline-path fast-path-p
10775 level txt)
10776 (list txt))
10777 "/")))
10778 (push (list txt f re (org-refile-marker (point)))
10779 tgs)))
10780 (when (= (point) pos0)
10781 ;; verification function has not moved point
10782 (goto-char (point-at-eol))))))))
10783 (when org-refile-use-cache
10784 (org-refile-cache-put tgs (buffer-file-name) descre))
10785 (setq targets (append tgs targets))
10786 ))))
10787 (message "Getting targets...done")
10788 (nreverse targets)))
10790 (defun org-protect-slash (s)
10791 (while (string-match "/" s)
10792 (setq s (replace-match "\\" t t s)))
10795 (defvar org-olpa (make-vector 20 nil))
10797 (defun org-get-outline-path (&optional fastp level heading)
10798 "Return the outline path to the current entry, as a list.
10800 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10801 routine which makes outline path derivations for an entire file,
10802 avoiding backtracing. Refile target collection makes use of that."
10803 (if fastp
10804 (progn
10805 (if (> level 19)
10806 (error "Outline path failure, more than 19 levels"))
10807 (loop for i from level upto 19 do
10808 (aset org-olpa i nil))
10809 (prog1
10810 (delq nil (append org-olpa nil))
10811 (aset org-olpa level heading)))
10812 (let (rtn case-fold-search)
10813 (save-excursion
10814 (save-restriction
10815 (widen)
10816 (while (org-up-heading-safe)
10817 (when (looking-at org-complex-heading-regexp)
10818 (push (org-match-string-no-properties 4) rtn)))
10819 rtn)))))
10821 (defun org-format-outline-path (path &optional width prefix)
10822 "Format the outline path PATH for display.
10823 Width is the maximum number of characters that is available.
10824 Prefix is a prefix to be included in the returned string,
10825 such as the file name."
10826 (setq width (or width 79))
10827 (if prefix (setq width (- width (length prefix))))
10828 (if (not path)
10829 (or prefix "")
10830 (let* ((nsteps (length path))
10831 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10832 (maxwidth (if (<= total-width width)
10833 10000 ;; everything fits
10834 ;; we need to shorten the level headings
10835 (/ (- width nsteps) nsteps)))
10836 (org-odd-levels-only nil)
10837 (n 0)
10838 (total (1+ (length prefix))))
10839 (setq maxwidth (max maxwidth 10))
10840 (concat prefix
10841 (mapconcat
10842 (lambda (h)
10843 (setq n (1+ n))
10844 (if (and (= n nsteps) (< maxwidth 10000))
10845 (setq maxwidth (- total-width total)))
10846 (if (< (length h) maxwidth)
10847 (progn (setq total (+ total (length h) 1)) h)
10848 (setq h (substring h 0 (- maxwidth 2))
10849 total (+ total maxwidth 1))
10850 (if (string-match "[ \t]+\\'" h)
10851 (setq h (substring h 0 (match-beginning 0))))
10852 (setq h (concat h "..")))
10853 (org-add-props h nil 'face
10854 (nth (% (1- n) org-n-level-faces)
10855 org-level-faces))
10857 path "/")))))
10859 (defun org-display-outline-path (&optional file current)
10860 "Display the current outline path in the echo area."
10861 (interactive "P")
10862 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10863 (case-fold-search nil)
10864 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10865 (if current (setq path (append path
10866 (save-excursion
10867 (org-back-to-heading t)
10868 (if (looking-at org-complex-heading-regexp)
10869 (list (match-string 4)))))))
10870 (message "%s"
10871 (org-format-outline-path
10872 path
10873 (1- (frame-width))
10874 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10876 (defvar org-refile-history nil
10877 "History for refiling operations.")
10879 (defvar org-after-refile-insert-hook nil
10880 "Hook run after `org-refile' has inserted its stuff at the new location.
10881 Note that this is still *before* the stuff will be removed from
10882 the *old* location.")
10884 (defvar org-capture-last-stored-marker)
10885 (defun org-refile (&optional goto default-buffer rfloc)
10886 "Move the entry or entries at point to another heading.
10887 The list of target headings is compiled using the information in
10888 `org-refile-targets', which see.
10890 At the target location, the entry is filed as a subitem of the target
10891 heading. Depending on `org-reverse-note-order', the new subitem will
10892 either be the first or the last subitem.
10894 If there is an active region, all entries in that region will be moved.
10895 However, the region must fulfill the requirement that the first heading
10896 is the first one sets the top-level of the moved text - at most siblings
10897 below it are allowed.
10899 With prefix arg GOTO, the command will only visit the target location
10900 and not actually move anything.
10902 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10903 go to the location where the last refiling operation has put the subtree.
10904 With a prefix argument of `2', refile to the running clock.
10906 RFLOC can be a refile location obtained in a different way.
10908 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10910 If you are using target caching (see `org-refile-use-cache'),
10911 you have to clear the target cache in order to find new targets.
10912 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10913 prefix argument (`C-u C-u C-u C-c C-w')."
10915 (interactive "P")
10916 (if (member goto '(0 (64)))
10917 (org-refile-cache-clear)
10918 (let* ((cbuf (current-buffer))
10919 (regionp (org-region-active-p))
10920 (region-start (and regionp (region-beginning)))
10921 (region-end (and regionp (region-end)))
10922 (region-length (and regionp (- region-end region-start)))
10923 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10924 pos it nbuf file re level reversed)
10925 (setq last-command nil)
10926 (when regionp
10927 (goto-char region-start)
10928 (or (bolp) (goto-char (point-at-bol)))
10929 (setq region-start (point))
10930 (unless (or (org-kill-is-subtree-p
10931 (buffer-substring region-start region-end))
10932 (prog1 org-refile-active-region-within-subtree
10933 (org-toggle-heading)))
10934 (error "The region is not a (sequence of) subtree(s)")))
10935 (if (equal goto '(16))
10936 (org-refile-goto-last-stored)
10937 (when (or
10938 (and (equal goto 2)
10939 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10940 (prog1
10941 (setq it (list (or org-clock-heading "running clock")
10942 (buffer-file-name
10943 (marker-buffer org-clock-hd-marker))
10945 (marker-position org-clock-hd-marker)))
10946 (setq goto nil)))
10947 (setq it (or rfloc
10948 (let (heading-text)
10949 (save-excursion
10950 (unless goto
10951 (org-back-to-heading t)
10952 (setq heading-text
10953 (nth 4 (org-heading-components))))
10954 (org-refile-get-location
10955 (cond (goto "Goto")
10956 (regionp "Refile region to")
10957 (t (concat "Refile subtree \""
10958 heading-text "\" to")))
10959 default-buffer
10960 (and (not (equal '(4) goto))
10961 org-refile-allow-creating-parent-nodes)
10962 goto))))))
10963 (setq file (nth 1 it)
10964 re (nth 2 it)
10965 pos (nth 3 it))
10966 (if (and (not goto)
10968 (equal (buffer-file-name) file)
10969 (if regionp
10970 (and (>= pos region-start)
10971 (<= pos region-end))
10972 (and (>= pos (point))
10973 (< pos (save-excursion
10974 (org-end-of-subtree t t))))))
10975 (error "Cannot refile to position inside the tree or region"))
10977 (setq nbuf (or (find-buffer-visiting file)
10978 (find-file-noselect file)))
10979 (if goto
10980 (progn
10981 (org-pop-to-buffer-same-window nbuf)
10982 (goto-char pos)
10983 (org-show-context 'org-goto))
10984 (if regionp
10985 (progn
10986 (org-kill-new (buffer-substring region-start region-end))
10987 (org-save-markers-in-region region-start region-end))
10988 (org-copy-subtree 1 nil t))
10989 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10990 (find-file-noselect file)))
10991 (setq reversed (org-notes-order-reversed-p))
10992 (save-excursion
10993 (save-restriction
10994 (widen)
10995 (if pos
10996 (progn
10997 (goto-char pos)
10998 (looking-at org-outline-regexp)
10999 (setq level (org-get-valid-level (funcall outline-level) 1))
11000 (goto-char
11001 (if reversed
11002 (or (outline-next-heading) (point-max))
11003 (or (save-excursion (org-get-next-sibling))
11004 (org-end-of-subtree t t)
11005 (point-max)))))
11006 (setq level 1)
11007 (if (not reversed)
11008 (goto-char (point-max))
11009 (goto-char (point-min))
11010 (or (outline-next-heading) (goto-char (point-max)))))
11011 (if (not (bolp)) (newline))
11012 (org-paste-subtree level)
11013 (when org-log-refile
11014 (org-add-log-setup 'refile nil nil 'findpos
11015 org-log-refile)
11016 (unless (eq org-log-refile 'note)
11017 (save-excursion (org-add-log-note))))
11018 (and org-auto-align-tags
11019 (let ((org-loop-over-headlines-in-active-region nil))
11020 (org-set-tags nil t)))
11021 (bookmark-set "org-refile-last-stored")
11022 ;; If we are refiling for capture, make sure that the
11023 ;; last-capture pointers point here
11024 (when (org-bound-and-true-p org-refile-for-capture)
11025 (bookmark-set "org-capture-last-stored-marker")
11026 (move-marker org-capture-last-stored-marker (point)))
11027 (if (fboundp 'deactivate-mark) (deactivate-mark))
11028 (run-hooks 'org-after-refile-insert-hook))))
11029 (if regionp
11030 (delete-region (point) (+ (point) region-length))
11031 (org-cut-subtree))
11032 (when (featurep 'org-inlinetask)
11033 (org-inlinetask-remove-END-maybe))
11034 (setq org-markers-to-move nil)
11035 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11037 (defun org-refile-goto-last-stored ()
11038 "Go to the location where the last refile was stored."
11039 (interactive)
11040 (bookmark-jump "org-refile-last-stored")
11041 (message "This is the location of the last refile"))
11043 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11044 no-exclude)
11045 "Prompt the user for a refile location, using PROMPT.
11046 PROMPT should not be suffixed with a colon and a space, because
11047 this function appends the default value from
11048 `org-refile-history' automatically, if that is not empty.
11049 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11050 this is used for the GOTO interface."
11051 (let ((org-refile-targets org-refile-targets)
11052 (org-refile-use-outline-path org-refile-use-outline-path)
11053 excluded-entries)
11054 (when (and (derived-mode-p 'org-mode)
11055 (not org-refile-use-cache)
11056 (not no-exclude))
11057 (org-map-tree
11058 (lambda()
11059 (setq excluded-entries
11060 (append excluded-entries (list (org-get-heading t t)))))))
11061 (setq org-refile-target-table
11062 (org-refile-get-targets default-buffer excluded-entries)))
11063 (unless org-refile-target-table
11064 (error "No refile targets"))
11065 (let* ((prompt (concat prompt
11066 (and (car org-refile-history)
11067 (concat " (default " (car org-refile-history) ")"))
11068 ": "))
11069 (cbuf (current-buffer))
11070 (partial-completion-mode nil)
11071 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11072 (cfunc (if (and org-refile-use-outline-path
11073 org-outline-path-complete-in-steps)
11074 'org-olpath-completing-read
11075 'org-icompleting-read))
11076 (extra (if org-refile-use-outline-path "/" ""))
11077 (filename (and cfn (expand-file-name cfn)))
11078 (tbl (mapcar
11079 (lambda (x)
11080 (if (and (not (member org-refile-use-outline-path
11081 '(file full-file-path)))
11082 (not (equal filename (nth 1 x))))
11083 (cons (concat (car x) extra " ("
11084 (file-name-nondirectory (nth 1 x)) ")")
11085 (cdr x))
11086 (cons (concat (car x) extra) (cdr x))))
11087 org-refile-target-table))
11088 (completion-ignore-case t)
11089 pa answ parent-target child parent old-hist)
11090 (setq old-hist org-refile-history)
11091 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11092 nil 'org-refile-history (car org-refile-history)))
11093 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11094 (org-refile-check-position pa)
11095 (if pa
11096 (progn
11097 (when (or (not org-refile-history)
11098 (not (eq old-hist org-refile-history))
11099 (not (equal (car pa) (car org-refile-history))))
11100 (setq org-refile-history
11101 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11102 org-refile-history
11103 (cdr org-refile-history))))
11104 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11105 (pop org-refile-history)))
11107 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11108 (progn
11109 (setq parent (match-string 1 answ)
11110 child (match-string 2 answ))
11111 (setq parent-target (or (assoc parent tbl)
11112 (assoc (concat parent "/") tbl)))
11113 (when (and parent-target
11114 (or (eq new-nodes t)
11115 (and (eq new-nodes 'confirm)
11116 (y-or-n-p (format "Create new node \"%s\"? "
11117 child)))))
11118 (org-refile-new-child parent-target child)))
11119 (error "Invalid target location")))))
11121 (declare-function org-string-nw-p "org-macs.el" (s))
11122 (defun org-refile-check-position (refile-pointer)
11123 "Check if the refile pointer matches the readline to which it points."
11124 (let* ((file (nth 1 refile-pointer))
11125 (re (nth 2 refile-pointer))
11126 (pos (nth 3 refile-pointer))
11127 buffer)
11128 (when (org-string-nw-p re)
11129 (setq buffer (if (markerp pos)
11130 (marker-buffer pos)
11131 (or (find-buffer-visiting file)
11132 (find-file-noselect file))))
11133 (with-current-buffer buffer
11134 (save-excursion
11135 (save-restriction
11136 (widen)
11137 (goto-char pos)
11138 (beginning-of-line 1)
11139 (unless (org-looking-at-p re)
11140 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11142 (defun org-refile-new-child (parent-target child)
11143 "Use refile target PARENT-TARGET to add new CHILD below it."
11144 (unless parent-target
11145 (error "Cannot find parent for new node"))
11146 (let ((file (nth 1 parent-target))
11147 (pos (nth 3 parent-target))
11148 level)
11149 (with-current-buffer (or (find-buffer-visiting file)
11150 (find-file-noselect file))
11151 (save-excursion
11152 (save-restriction
11153 (widen)
11154 (if pos
11155 (goto-char pos)
11156 (goto-char (point-max))
11157 (if (not (bolp)) (newline)))
11158 (when (looking-at org-outline-regexp)
11159 (setq level (funcall outline-level))
11160 (org-end-of-subtree t t))
11161 (org-back-over-empty-lines)
11162 (insert "\n" (make-string
11163 (if pos (org-get-valid-level level 1) 1) ?*)
11164 " " child "\n")
11165 (beginning-of-line 0)
11166 (list (concat (car parent-target) "/" child) file "" (point)))))))
11168 (defun org-olpath-completing-read (prompt collection &rest args)
11169 "Read an outline path like a file name."
11170 (let ((thetable collection)
11171 (org-completion-use-ido nil) ; does not work with ido.
11172 (org-completion-use-iswitchb nil)) ; or iswitchb
11173 (apply
11174 'org-icompleting-read prompt
11175 (lambda (string predicate &optional flag)
11176 (let (rtn r f (l (length string)))
11177 (cond
11178 ((eq flag nil)
11179 ;; try completion
11180 (try-completion string thetable))
11181 ((eq flag t)
11182 ;; all-completions
11183 (setq rtn (all-completions string thetable predicate))
11184 (mapcar
11185 (lambda (x)
11186 (setq r (substring x l))
11187 (if (string-match " ([^)]*)$" x)
11188 (setq f (match-string 0 x))
11189 (setq f ""))
11190 (if (string-match "/" r)
11191 (concat string (substring r 0 (match-end 0)) f)
11193 rtn))
11194 ((eq flag 'lambda)
11195 ;; exact match?
11196 (assoc string thetable)))))
11197 args)))
11199 ;;;; Dynamic blocks
11201 (defun org-find-dblock (name)
11202 "Find the first dynamic block with name NAME in the buffer.
11203 If not found, stay at current position and return nil."
11204 (let ((case-fold-search t) pos)
11205 (save-excursion
11206 (goto-char (point-min))
11207 (setq pos (and (re-search-forward
11208 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11209 (match-beginning 0))))
11210 (if pos (goto-char pos))
11211 pos))
11213 (defconst org-dblock-start-re
11214 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11215 "Matches the start line of a dynamic block, with parameters.")
11217 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11218 "Matches the end of a dynamic block.")
11220 (defun org-create-dblock (plist)
11221 "Create a dynamic block section, with parameters taken from PLIST.
11222 PLIST must contain a :name entry which is used as name of the block."
11223 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11224 (end-of-line 1)
11225 (newline))
11226 (let ((col (current-column))
11227 (name (plist-get plist :name)))
11228 (insert "#+BEGIN: " name)
11229 (while plist
11230 (if (eq (car plist) :name)
11231 (setq plist (cddr plist))
11232 (insert " " (prin1-to-string (pop plist)))))
11233 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11234 (beginning-of-line -2)))
11236 (defun org-prepare-dblock ()
11237 "Prepare dynamic block for refresh.
11238 This empties the block, puts the cursor at the insert position and returns
11239 the property list including an extra property :name with the block name."
11240 (unless (looking-at org-dblock-start-re)
11241 (error "Not at a dynamic block"))
11242 (let* ((begdel (1+ (match-end 0)))
11243 (name (org-no-properties (match-string 1)))
11244 (params (append (list :name name)
11245 (read (concat "(" (match-string 3) ")")))))
11246 (save-excursion
11247 (beginning-of-line 1)
11248 (skip-chars-forward " \t")
11249 (setq params (plist-put params :indentation-column (current-column))))
11250 (unless (re-search-forward org-dblock-end-re nil t)
11251 (error "Dynamic block not terminated"))
11252 (setq params
11253 (append params
11254 (list :content (buffer-substring
11255 begdel (match-beginning 0)))))
11256 (delete-region begdel (match-beginning 0))
11257 (goto-char begdel)
11258 (open-line 1)
11259 params))
11261 (defun org-map-dblocks (&optional command)
11262 "Apply COMMAND to all dynamic blocks in the current buffer.
11263 If COMMAND is not given, use `org-update-dblock'."
11264 (let ((cmd (or command 'org-update-dblock)))
11265 (save-excursion
11266 (goto-char (point-min))
11267 (while (re-search-forward org-dblock-start-re nil t)
11268 (goto-char (match-beginning 0))
11269 (save-excursion
11270 (condition-case nil
11271 (funcall cmd)
11272 (error (message "Error during update of dynamic block"))))
11273 (unless (re-search-forward org-dblock-end-re nil t)
11274 (error "Dynamic block not terminated"))))))
11276 (defun org-dblock-update (&optional arg)
11277 "User command for updating dynamic blocks.
11278 Update the dynamic block at point. With prefix ARG, update all dynamic
11279 blocks in the buffer."
11280 (interactive "P")
11281 (if arg
11282 (org-update-all-dblocks)
11283 (or (looking-at org-dblock-start-re)
11284 (org-beginning-of-dblock))
11285 (org-update-dblock)))
11287 (defun org-update-dblock ()
11288 "Update the dynamic block at point.
11289 This means to empty the block, parse for parameters and then call
11290 the correct writing function."
11291 (interactive)
11292 (save-window-excursion
11293 (let* ((pos (point))
11294 (line (org-current-line))
11295 (params (org-prepare-dblock))
11296 (name (plist-get params :name))
11297 (indent (plist-get params :indentation-column))
11298 (cmd (intern (concat "org-dblock-write:" name))))
11299 (message "Updating dynamic block `%s' at line %d..." name line)
11300 (funcall cmd params)
11301 (message "Updating dynamic block `%s' at line %d...done" name line)
11302 (goto-char pos)
11303 (when (and indent (> indent 0))
11304 (setq indent (make-string indent ?\ ))
11305 (save-excursion
11306 (org-beginning-of-dblock)
11307 (forward-line 1)
11308 (while (not (looking-at org-dblock-end-re))
11309 (insert indent)
11310 (beginning-of-line 2))
11311 (when (looking-at org-dblock-end-re)
11312 (and (looking-at "[ \t]+")
11313 (replace-match ""))
11314 (insert indent)))))))
11316 (defun org-beginning-of-dblock ()
11317 "Find the beginning of the dynamic block at point.
11318 Error if there is no such block at point."
11319 (let ((pos (point))
11320 beg)
11321 (end-of-line 1)
11322 (if (and (re-search-backward org-dblock-start-re nil t)
11323 (setq beg (match-beginning 0))
11324 (re-search-forward org-dblock-end-re nil t)
11325 (> (match-end 0) pos))
11326 (goto-char beg)
11327 (goto-char pos)
11328 (error "Not in a dynamic block"))))
11330 ;;;###autoload
11331 (defun org-update-all-dblocks ()
11332 "Update all dynamic blocks in the buffer.
11333 This function can be used in a hook."
11334 (interactive)
11335 (when (derived-mode-p 'org-mode)
11336 (org-map-dblocks 'org-update-dblock)))
11339 ;;;; Completion
11341 (defconst org-additional-option-like-keywords
11342 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11343 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11344 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11345 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11346 "BEGIN:" "END:"
11347 "ORGTBL" "TBLFM:" "TBLNAME:"
11348 "BEGIN_EXAMPLE" "END_EXAMPLE"
11349 "BEGIN_VERBATIM" "END_VERBATIM"
11350 "BEGIN_QUOTE" "END_QUOTE"
11351 "BEGIN_VERSE" "END_VERSE"
11352 "BEGIN_CENTER" "END_CENTER"
11353 "BEGIN_SRC" "END_SRC"
11354 "BEGIN_RESULT" "END_RESULT"
11355 "BEGIN_lstlisting" "END_lstlisting"
11356 "NAME:" "RESULTS:"
11357 "HEADER:" "HEADERS:"
11358 "COLUMNS:" "PROPERTY:"
11359 "CAPTION:" "LABEL:"
11360 "SETUPFILE:"
11361 "INCLUDE:"
11362 "BIND:"
11363 "MACRO:"))
11365 (defconst org-options-keywords
11366 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11367 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11368 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11369 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11370 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11371 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11372 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11374 (defconst org-additional-option-like-keywords-for-flyspell
11375 (delete-dups
11376 (split-string
11377 (mapconcat (lambda(k)
11378 (replace-regexp-in-string
11379 "_\\|:" " "
11380 (concat k " " (downcase k) " " (upcase k))))
11381 (append org-options-keywords org-additional-option-like-keywords)
11382 " ")
11383 " +" t)))
11385 (defcustom org-structure-template-alist
11387 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11388 "<src lang=\"?\">\n\n</src>")
11389 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11390 "<example>\n?\n</example>")
11391 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11392 "<quote>\n?\n</quote>")
11393 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11394 "<verse>\n?\n</verse>")
11395 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11396 "<center>\n?\n</center>")
11397 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11398 "<literal style=\"latex\">\n?\n</literal>")
11399 ("L" "#+LaTeX: "
11400 "<literal style=\"latex\">?</literal>")
11401 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11402 "<literal style=\"html\">\n?\n</literal>")
11403 ("H" "#+HTML: "
11404 "<literal style=\"html\">?</literal>")
11405 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11406 ("A" "#+ASCII: ")
11407 ("i" "#+INDEX: ?"
11408 "#+INDEX: ?")
11409 ("I" "#+INCLUDE: %file ?"
11410 "<include file=%file markup=\"?\">")
11412 "Structure completion elements.
11413 This is a list of abbreviation keys and values. The value gets inserted
11414 if you type `<' followed by the key and then press the completion key,
11415 usually `M-TAB'. %file will be replaced by a file name after prompting
11416 for the file using completion. The cursor will be placed at the position
11417 of the `?` in the template.
11418 There are two templates for each key, the first uses the original Org syntax,
11419 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11420 the default when the /org-mtags.el/ module has been loaded. See also the
11421 variable `org-mtags-prefer-muse-templates'."
11422 :group 'org-completion
11423 :type '(repeat
11424 (string :tag "Key")
11425 (string :tag "Template")
11426 (string :tag "Muse Template")))
11428 (defun org-try-structure-completion ()
11429 "Try to complete a structure template before point.
11430 This looks for strings like \"<e\" on an otherwise empty line and
11431 expands them."
11432 (let ((l (buffer-substring (point-at-bol) (point)))
11434 (when (and (looking-at "[ \t]*$")
11435 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11436 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11437 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11438 (match-beginning 1)) a)
11439 t)))
11441 (defun org-complete-expand-structure-template (start cell)
11442 "Expand a structure template."
11443 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11444 (rpl (nth (if musep 2 1) cell))
11445 (ind ""))
11446 (delete-region start (point))
11447 (when (string-match "\\`#\\+" rpl)
11448 (cond
11449 ((bolp))
11450 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11451 (setq ind (buffer-substring (point-at-bol) (point))))
11452 (t (newline))))
11453 (setq start (point))
11454 (if (string-match "%file" rpl)
11455 (setq rpl (replace-match
11456 (concat
11457 "\""
11458 (save-match-data
11459 (abbreviate-file-name (read-file-name "Include file: ")))
11460 "\"")
11461 t t rpl)))
11462 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11463 (concat "\n" ind)))
11464 (insert rpl)
11465 (if (re-search-backward "\\?" start t) (delete-char 1))))
11467 ;;;; TODO, DEADLINE, Comments
11469 (defun org-toggle-comment ()
11470 "Change the COMMENT state of an entry."
11471 (interactive)
11472 (save-excursion
11473 (org-back-to-heading)
11474 (let (case-fold-search)
11475 (cond
11476 ((looking-at (format org-heading-keyword-regexp-format
11477 org-comment-string))
11478 (goto-char (match-end 1))
11479 (looking-at (concat " +" org-comment-string))
11480 (replace-match "" t t)
11481 (when (eolp) (insert " ")))
11482 ((looking-at org-outline-regexp)
11483 (goto-char (match-end 0))
11484 (insert org-comment-string " "))))))
11486 (defvar org-last-todo-state-is-todo nil
11487 "This is non-nil when the last TODO state change led to a TODO state.
11488 If the last change removed the TODO tag or switched to DONE, then
11489 this is nil.")
11491 (defvar org-setting-tags nil) ; dynamically skipped
11493 (defvar org-todo-setup-filter-hook nil
11494 "Hook for functions that pre-filter todo specs.
11495 Each function takes a todo spec and returns either nil or the spec
11496 transformed into canonical form." )
11498 (defvar org-todo-get-default-hook nil
11499 "Hook for functions that get a default item for todo.
11500 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11501 nil or a string to be used for the todo mark." )
11503 (defvar org-agenda-headline-snapshot-before-repeat)
11505 (defun org-current-effective-time ()
11506 "Return current time adjusted for `org-extend-today-until' variable."
11507 (let* ((ct (org-current-time))
11508 (dct (decode-time ct))
11509 (ct1
11510 (if (and org-use-effective-time
11511 (< (nth 2 dct) org-extend-today-until))
11512 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11513 ct)))
11514 ct1))
11516 (defun org-todo-yesterday (&optional arg)
11517 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11518 (interactive "P")
11519 (if (eq major-mode 'org-agenda-mode)
11520 (apply 'org-agenda-todo-yesterday arg)
11521 (let* ((hour (third (decode-time
11522 (org-current-time))))
11523 (org-extend-today-until (1+ hour)))
11524 (org-todo arg))))
11526 (defun org-todo (&optional arg)
11527 "Change the TODO state of an item.
11528 The state of an item is given by a keyword at the start of the heading,
11529 like
11530 *** TODO Write paper
11531 *** DONE Call mom
11533 The different keywords are specified in the variable `org-todo-keywords'.
11534 By default the available states are \"TODO\" and \"DONE\".
11535 So for this example: when the item starts with TODO, it is changed to DONE.
11536 When it starts with DONE, the DONE is removed. And when neither TODO nor
11537 DONE are present, add TODO at the beginning of the heading.
11539 With \\[universal-argument] prefix arg, use completion to determine the new \
11540 state.
11541 With numeric prefix arg, switch to that state.
11542 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11543 keywords (nextset).
11544 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11545 With a numeric prefix arg of 0, inhibit note taking for the change.
11547 For calling through lisp, arg is also interpreted in the following way:
11548 'none -> empty state
11549 \"\"(empty string) -> switch to empty state
11550 'done -> switch to DONE
11551 'nextset -> switch to the next set of keywords
11552 'previousset -> switch to the previous set of keywords
11553 \"WAITING\" -> switch to the specified keyword, but only if it
11554 really is a member of `org-todo-keywords'."
11555 (interactive "P")
11556 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11557 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11558 'region-start-level 'region))
11559 org-loop-over-headlines-in-active-region)
11560 (org-map-entries
11561 `(org-todo ,arg)
11562 org-loop-over-headlines-in-active-region
11563 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11564 (if (equal arg '(16)) (setq arg 'nextset))
11565 (let ((org-blocker-hook org-blocker-hook)
11566 (case-fold-search nil))
11567 (when (equal arg '(64))
11568 (setq arg nil org-blocker-hook nil))
11569 (when (and org-blocker-hook
11570 (or org-inhibit-blocking
11571 (org-entry-get nil "NOBLOCKING")))
11572 (setq org-blocker-hook nil))
11573 (save-excursion
11574 (catch 'exit
11575 (org-back-to-heading t)
11576 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11577 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11578 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11579 (let* ((match-data (match-data))
11580 (startpos (point-at-bol))
11581 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11582 (org-log-done org-log-done)
11583 (org-log-repeat org-log-repeat)
11584 (org-todo-log-states org-todo-log-states)
11585 (org-inhibit-logging
11586 (if (equal arg 0)
11587 (progn (setq arg nil) 'note) org-inhibit-logging))
11588 (this (match-string 1))
11589 (hl-pos (match-beginning 0))
11590 (head (org-get-todo-sequence-head this))
11591 (ass (assoc head org-todo-kwd-alist))
11592 (interpret (nth 1 ass))
11593 (done-word (nth 3 ass))
11594 (final-done-word (nth 4 ass))
11595 (org-last-state (or this ""))
11596 (completion-ignore-case t)
11597 (member (member this org-todo-keywords-1))
11598 (tail (cdr member))
11599 (org-state (cond
11600 ((and org-todo-key-trigger
11601 (or (and (equal arg '(4))
11602 (eq org-use-fast-todo-selection 'prefix))
11603 (and (not arg) org-use-fast-todo-selection
11604 (not (eq org-use-fast-todo-selection
11605 'prefix)))))
11606 ;; Use fast selection
11607 (org-fast-todo-selection))
11608 ((and (equal arg '(4))
11609 (or (not org-use-fast-todo-selection)
11610 (not org-todo-key-trigger)))
11611 ;; Read a state with completion
11612 (org-icompleting-read
11613 "State: " (mapcar (lambda(x) (list x))
11614 org-todo-keywords-1)
11615 nil t))
11616 ((eq arg 'right)
11617 (if this
11618 (if tail (car tail) nil)
11619 (car org-todo-keywords-1)))
11620 ((eq arg 'left)
11621 (if (equal member org-todo-keywords-1)
11623 (if this
11624 (nth (- (length org-todo-keywords-1)
11625 (length tail) 2)
11626 org-todo-keywords-1)
11627 (org-last org-todo-keywords-1))))
11628 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11629 (setq arg nil))) ; hack to fall back to cycling
11630 (arg
11631 ;; user or caller requests a specific state
11632 (cond
11633 ((equal arg "") nil)
11634 ((eq arg 'none) nil)
11635 ((eq arg 'done) (or done-word (car org-done-keywords)))
11636 ((eq arg 'nextset)
11637 (or (car (cdr (member head org-todo-heads)))
11638 (car org-todo-heads)))
11639 ((eq arg 'previousset)
11640 (let ((org-todo-heads (reverse org-todo-heads)))
11641 (or (car (cdr (member head org-todo-heads)))
11642 (car org-todo-heads))))
11643 ((car (member arg org-todo-keywords-1)))
11644 ((stringp arg)
11645 (error "State `%s' not valid in this file" arg))
11646 ((nth (1- (prefix-numeric-value arg))
11647 org-todo-keywords-1))))
11648 ((null member) (or head (car org-todo-keywords-1)))
11649 ((equal this final-done-word) nil) ;; -> make empty
11650 ((null tail) nil) ;; -> first entry
11651 ((memq interpret '(type priority))
11652 (if (eq this-command last-command)
11653 (car tail)
11654 (if (> (length tail) 0)
11655 (or done-word (car org-done-keywords))
11656 nil)))
11658 (car tail))))
11659 (org-state (or
11660 (run-hook-with-args-until-success
11661 'org-todo-get-default-hook org-state org-last-state)
11662 org-state))
11663 (next (if org-state (concat " " org-state " ") " "))
11664 (change-plist (list :type 'todo-state-change :from this :to org-state
11665 :position startpos))
11666 dolog now-done-p)
11667 (when org-blocker-hook
11668 (setq org-last-todo-state-is-todo
11669 (not (member this org-done-keywords)))
11670 (unless (save-excursion
11671 (save-match-data
11672 (org-with-wide-buffer
11673 (run-hook-with-args-until-failure
11674 'org-blocker-hook change-plist))))
11675 (if (org-called-interactively-p 'interactive)
11676 (error "TODO state change from %s to %s blocked" this org-state)
11677 ;; fail silently
11678 (message "TODO state change from %s to %s blocked" this org-state)
11679 (throw 'exit nil))))
11680 (store-match-data match-data)
11681 (replace-match next t t)
11682 (unless (pos-visible-in-window-p hl-pos)
11683 (message "TODO state changed to %s" (org-trim next)))
11684 (unless head
11685 (setq head (org-get-todo-sequence-head org-state)
11686 ass (assoc head org-todo-kwd-alist)
11687 interpret (nth 1 ass)
11688 done-word (nth 3 ass)
11689 final-done-word (nth 4 ass)))
11690 (when (memq arg '(nextset previousset))
11691 (message "Keyword-Set %d/%d: %s"
11692 (- (length org-todo-sets) -1
11693 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11694 (length org-todo-sets)
11695 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11696 (setq org-last-todo-state-is-todo
11697 (not (member org-state org-done-keywords)))
11698 (setq now-done-p (and (member org-state org-done-keywords)
11699 (not (member this org-done-keywords))))
11700 (and logging (org-local-logging logging))
11701 (when (and (or org-todo-log-states org-log-done)
11702 (not (eq org-inhibit-logging t))
11703 (not (memq arg '(nextset previousset))))
11704 ;; we need to look at recording a time and note
11705 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11706 (nth 2 (assoc this org-todo-log-states))))
11707 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11708 (setq dolog 'time))
11709 (when (and org-state
11710 (member org-state org-not-done-keywords)
11711 (not (member this org-not-done-keywords)))
11712 ;; This is now a todo state and was not one before
11713 ;; If there was a CLOSED time stamp, get rid of it.
11714 (org-add-planning-info nil nil 'closed))
11715 (when (and now-done-p org-log-done)
11716 ;; It is now done, and it was not done before
11717 (org-add-planning-info 'closed (org-current-effective-time))
11718 (if (and (not dolog) (eq 'note org-log-done))
11719 (org-add-log-setup 'done org-state this 'findpos 'note)))
11720 (when (and org-state dolog)
11721 ;; This is a non-nil state, and we need to log it
11722 (org-add-log-setup 'state org-state this 'findpos dolog)))
11723 ;; Fixup tag positioning
11724 (org-todo-trigger-tag-changes org-state)
11725 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11726 (when org-provide-todo-statistics
11727 (org-update-parent-todo-statistics))
11728 (run-hooks 'org-after-todo-state-change-hook)
11729 (if (and arg (not (member org-state org-done-keywords)))
11730 (setq head (org-get-todo-sequence-head org-state)))
11731 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11732 ;; Do we need to trigger a repeat?
11733 (when now-done-p
11734 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11735 ;; This is for the agenda, take a snapshot of the headline.
11736 (save-match-data
11737 (setq org-agenda-headline-snapshot-before-repeat
11738 (org-get-heading))))
11739 (org-auto-repeat-maybe org-state))
11740 ;; Fixup cursor location if close to the keyword
11741 (if (and (outline-on-heading-p)
11742 (not (bolp))
11743 (save-excursion (beginning-of-line 1)
11744 (looking-at org-todo-line-regexp))
11745 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11746 (progn
11747 (goto-char (or (match-end 2) (match-end 1)))
11748 (and (looking-at " ") (just-one-space))))
11749 (when org-trigger-hook
11750 (save-excursion
11751 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11753 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11754 "Block turning an entry into a TODO, using the hierarchy.
11755 This checks whether the current task should be blocked from state
11756 changes. Such blocking occurs when:
11758 1. The task has children which are not all in a completed state.
11760 2. A task has a parent with the property :ORDERED:, and there
11761 are siblings prior to the current task with incomplete
11762 status.
11764 3. The parent of the task is blocked because it has siblings that should
11765 be done first, or is child of a block grandparent TODO entry."
11767 (if (not org-enforce-todo-dependencies)
11768 t ; if locally turned off don't block
11769 (catch 'dont-block
11770 ;; If this is not a todo state change, or if this entry is already DONE,
11771 ;; do not block
11772 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11773 (member (plist-get change-plist :from)
11774 (cons 'done org-done-keywords))
11775 (member (plist-get change-plist :to)
11776 (cons 'todo org-not-done-keywords))
11777 (not (plist-get change-plist :to)))
11778 (throw 'dont-block t))
11779 ;; If this task has children, and any are undone, it's blocked
11780 (save-excursion
11781 (org-back-to-heading t)
11782 (let ((this-level (funcall outline-level)))
11783 (outline-next-heading)
11784 (let ((child-level (funcall outline-level)))
11785 (while (and (not (eobp))
11786 (> child-level this-level))
11787 ;; this todo has children, check whether they are all
11788 ;; completed
11789 (if (and (not (org-entry-is-done-p))
11790 (org-entry-is-todo-p))
11791 (throw 'dont-block nil))
11792 (outline-next-heading)
11793 (setq child-level (funcall outline-level))))))
11794 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11795 ;; any previous siblings are undone, it's blocked
11796 (save-excursion
11797 (org-back-to-heading t)
11798 (let* ((pos (point))
11799 (parent-pos (and (org-up-heading-safe) (point))))
11800 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11801 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11802 (forward-line 1)
11803 (re-search-forward org-not-done-heading-regexp pos t))
11804 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11805 ;; Search further up the hierarchy, to see if an ancestor is blocked
11806 (while t
11807 (goto-char parent-pos)
11808 (if (not (looking-at org-not-done-heading-regexp))
11809 (throw 'dont-block t)) ; do not block, parent is not a TODO
11810 (setq pos (point))
11811 (setq parent-pos (and (org-up-heading-safe) (point)))
11812 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11813 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11814 (forward-line 1)
11815 (re-search-forward org-not-done-heading-regexp pos t))
11816 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11818 (defcustom org-track-ordered-property-with-tag nil
11819 "Should the ORDERED property also be shown as a tag?
11820 The ORDERED property decides if an entry should require subtasks to be
11821 completed in sequence. Since a property is not very visible, setting
11822 this option means that toggling the ORDERED property with the command
11823 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11824 not relevant for the behavior, but it makes things more visible.
11826 Note that toggling the tag with tags commands will not change the property
11827 and therefore not influence behavior!
11829 This can be t, meaning the tag ORDERED should be used, It can also be a
11830 string to select a different tag for this task."
11831 :group 'org-todo
11832 :type '(choice
11833 (const :tag "No tracking" nil)
11834 (const :tag "Track with ORDERED tag" t)
11835 (string :tag "Use other tag")))
11837 (defun org-toggle-ordered-property ()
11838 "Toggle the ORDERED property of the current entry.
11839 For better visibility, you can track the value of this property with a tag.
11840 See variable `org-track-ordered-property-with-tag'."
11841 (interactive)
11842 (let* ((t1 org-track-ordered-property-with-tag)
11843 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11844 (save-excursion
11845 (org-back-to-heading)
11846 (if (org-entry-get nil "ORDERED")
11847 (progn
11848 (org-delete-property "ORDERED")
11849 (and tag (org-toggle-tag tag 'off))
11850 (message "Subtasks can be completed in arbitrary order"))
11851 (org-entry-put nil "ORDERED" "t")
11852 (and tag (org-toggle-tag tag 'on))
11853 (message "Subtasks must be completed in sequence")))))
11855 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11856 (defun org-block-todo-from-checkboxes (change-plist)
11857 "Block turning an entry into a TODO, using checkboxes.
11858 This checks whether the current task should be blocked from state
11859 changes because there are unchecked boxes in this entry."
11860 (if (not org-enforce-todo-checkbox-dependencies)
11861 t ; if locally turned off don't block
11862 (catch 'dont-block
11863 ;; If this is not a todo state change, or if this entry is already DONE,
11864 ;; do not block
11865 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11866 (member (plist-get change-plist :from)
11867 (cons 'done org-done-keywords))
11868 (member (plist-get change-plist :to)
11869 (cons 'todo org-not-done-keywords))
11870 (not (plist-get change-plist :to)))
11871 (throw 'dont-block t))
11872 ;; If this task has checkboxes that are not checked, it's blocked
11873 (save-excursion
11874 (org-back-to-heading t)
11875 (let ((beg (point)) end)
11876 (outline-next-heading)
11877 (setq end (point))
11878 (goto-char beg)
11879 (if (org-list-search-forward
11880 (concat (org-item-beginning-re)
11881 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11882 "\\[[- ]\\]")
11883 end t)
11884 (progn
11885 (if (boundp 'org-blocked-by-checkboxes)
11886 (setq org-blocked-by-checkboxes t))
11887 (throw 'dont-block nil)))))
11888 t))) ; do not block
11890 (defun org-entry-blocked-p ()
11891 "Is the current entry blocked?"
11892 (if (org-entry-get nil "NOBLOCKING")
11893 nil ;; Never block this entry
11894 (not
11895 (run-hook-with-args-until-failure
11896 'org-blocker-hook
11897 (list :type 'todo-state-change
11898 :position (point)
11899 :from 'todo
11900 :to 'done)))))
11902 (defun org-update-statistics-cookies (all)
11903 "Update the statistics cookie, either from TODO or from checkboxes.
11904 This should be called with the cursor in a line with a statistics cookie."
11905 (interactive "P")
11906 (if all
11907 (progn
11908 (org-update-checkbox-count 'all)
11909 (org-map-entries 'org-update-parent-todo-statistics))
11910 (if (not (org-at-heading-p))
11911 (org-update-checkbox-count)
11912 (let ((pos (move-marker (make-marker) (point)))
11913 end l1 l2)
11914 (ignore-errors (org-back-to-heading t))
11915 (if (not (org-at-heading-p))
11916 (org-update-checkbox-count)
11917 (setq l1 (org-outline-level))
11918 (setq end (save-excursion
11919 (outline-next-heading)
11920 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11921 (point)))
11922 (if (and (save-excursion
11923 (re-search-forward
11924 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11925 (not (save-excursion (re-search-forward
11926 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11927 (org-update-checkbox-count)
11928 (if (and l2 (> l2 l1))
11929 (progn
11930 (goto-char end)
11931 (org-update-parent-todo-statistics))
11932 (goto-char pos)
11933 (beginning-of-line 1)
11934 (while (re-search-forward
11935 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11936 (point-at-eol) t)
11937 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11938 (goto-char pos)
11939 (move-marker pos nil)))))
11941 (defvar org-entry-property-inherited-from) ;; defined below
11942 (defun org-update-parent-todo-statistics ()
11943 "Update any statistics cookie in the parent of the current headline.
11944 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11945 the entire subtree and this will travel up the hierarchy and update
11946 statistics everywhere."
11947 (let* ((prop (save-excursion (org-up-heading-safe)
11948 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11949 (recursive (or (not org-hierarchical-todo-statistics)
11950 (and prop (string-match "\\<recursive\\>" prop))))
11951 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11953 (first t)
11954 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11955 level ltoggle l1 new ndel
11956 (cnt-all 0) (cnt-done 0) is-percent kwd
11957 checkbox-beg ov ovs ove cookie-present)
11958 (catch 'exit
11959 (save-excursion
11960 (beginning-of-line 1)
11961 (setq ltoggle (funcall outline-level))
11962 ;; Three situations are to consider:
11964 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11965 ;; to the top-level ancestor on the headline;
11967 ;; 2. If parent has "recursive" property, repeat up to the
11968 ;; headline setting that property, taking inheritance into
11969 ;; account;
11971 ;; 3. Else, move up to direct parent and proceed only once.
11972 (while (and (setq level (org-up-heading-safe))
11973 (or recursive first)
11974 (>= (point) lim))
11975 (setq first nil cookie-present nil)
11976 (unless (and level
11977 (not (string-match
11978 "\\<checkbox\\>"
11979 (downcase (or (org-entry-get nil "COOKIE_DATA")
11980 "")))))
11981 (throw 'exit nil))
11982 (while (re-search-forward box-re (point-at-eol) t)
11983 (setq cnt-all 0 cnt-done 0 cookie-present t)
11984 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11985 (save-match-data
11986 (unless (outline-next-heading) (throw 'exit nil))
11987 (while (and (looking-at org-complex-heading-regexp)
11988 (> (setq l1 (length (match-string 1))) level))
11989 (setq kwd (and (or recursive (= l1 ltoggle))
11990 (match-string 2)))
11991 (if (or (eq org-provide-todo-statistics 'all-headlines)
11992 (and (listp org-provide-todo-statistics)
11993 (or (member kwd org-provide-todo-statistics)
11994 (member kwd org-done-keywords))))
11995 (setq cnt-all (1+ cnt-all))
11996 (if (eq org-provide-todo-statistics t)
11997 (and kwd (setq cnt-all (1+ cnt-all)))))
11998 (and (member kwd org-done-keywords)
11999 (setq cnt-done (1+ cnt-done)))
12000 (outline-next-heading)))
12001 (setq new
12002 (if is-percent
12003 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12004 (format "[%d/%d]" cnt-done cnt-all))
12005 ndel (- (match-end 0) checkbox-beg))
12006 ;; handle overlays when updating cookie from column view
12007 (when (setq ov (car (overlays-at checkbox-beg)))
12008 (setq ovs (overlay-start ov) ove (overlay-end ov))
12009 (delete-overlay ov))
12010 (goto-char checkbox-beg)
12011 (insert new)
12012 (delete-region (point) (+ (point) ndel))
12013 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12014 (when ov (move-overlay ov ovs ove)))
12015 (when cookie-present
12016 (run-hook-with-args 'org-after-todo-statistics-hook
12017 cnt-done (- cnt-all cnt-done))))))
12018 (run-hooks 'org-todo-statistics-hook)))
12020 (defvar org-after-todo-statistics-hook nil
12021 "Hook that is called after a TODO statistics cookie has been updated.
12022 Each function is called with two arguments: the number of not-done entries
12023 and the number of done entries.
12025 For example, the following function, when added to this hook, will switch
12026 an entry to DONE when all children are done, and back to TODO when new
12027 entries are set to a TODO status. Note that this hook is only called
12028 when there is a statistics cookie in the headline!
12030 (defun org-summary-todo (n-done n-not-done)
12031 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12032 (let (org-log-done org-log-states) ; turn off logging
12033 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12036 (defvar org-todo-statistics-hook nil
12037 "Hook that is run whenever Org thinks TODO statistics should be updated.
12038 This hook runs even if there is no statistics cookie present, in which case
12039 `org-after-todo-statistics-hook' would not run.")
12041 (defun org-todo-trigger-tag-changes (state)
12042 "Apply the changes defined in `org-todo-state-tags-triggers'."
12043 (let ((l org-todo-state-tags-triggers)
12044 changes)
12045 (when (or (not state) (equal state ""))
12046 (setq changes (append changes (cdr (assoc "" l)))))
12047 (when (and (stringp state) (> (length state) 0))
12048 (setq changes (append changes (cdr (assoc state l)))))
12049 (when (member state org-not-done-keywords)
12050 (setq changes (append changes (cdr (assoc 'todo l)))))
12051 (when (member state org-done-keywords)
12052 (setq changes (append changes (cdr (assoc 'done l)))))
12053 (dolist (c changes)
12054 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12056 (defun org-local-logging (value)
12057 "Get logging settings from a property VALUE."
12058 (let* (words w a)
12059 ;; directly set the variables, they are already local.
12060 (setq org-log-done nil
12061 org-log-repeat nil
12062 org-todo-log-states nil)
12063 (setq words (org-split-string value))
12064 (while (setq w (pop words))
12065 (cond
12066 ((setq a (assoc w org-startup-options))
12067 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12068 (set (nth 1 a) (nth 2 a))))
12069 ((setq a (org-extract-log-state-settings w))
12070 (and (member (car a) org-todo-keywords-1)
12071 (push a org-todo-log-states)))))))
12073 (defun org-get-todo-sequence-head (kwd)
12074 "Return the head of the TODO sequence to which KWD belongs.
12075 If KWD is not set, check if there is a text property remembering the
12076 right sequence."
12077 (let (p)
12078 (cond
12079 ((not kwd)
12080 (or (get-text-property (point-at-bol) 'org-todo-head)
12081 (progn
12082 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12083 nil (point-at-eol)))
12084 (get-text-property p 'org-todo-head))))
12085 ((not (member kwd org-todo-keywords-1))
12086 (car org-todo-keywords-1))
12087 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12089 (defun org-fast-todo-selection ()
12090 "Fast TODO keyword selection with single keys.
12091 Returns the new TODO keyword, or nil if no state change should occur."
12092 (let* ((fulltable org-todo-key-alist)
12093 (done-keywords org-done-keywords) ;; needed for the faces.
12094 (maxlen (apply 'max (mapcar
12095 (lambda (x)
12096 (if (stringp (car x)) (string-width (car x)) 0))
12097 fulltable)))
12098 (expert nil)
12099 (fwidth (+ maxlen 3 1 3))
12100 (ncol (/ (- (window-width) 4) fwidth))
12101 tg cnt e c tbl
12102 groups ingroup)
12103 (save-excursion
12104 (save-window-excursion
12105 (if expert
12106 (set-buffer (get-buffer-create " *Org todo*"))
12107 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12108 (erase-buffer)
12109 (org-set-local 'org-done-keywords done-keywords)
12110 (setq tbl fulltable cnt 0)
12111 (while (setq e (pop tbl))
12112 (cond
12113 ((equal e '(:startgroup))
12114 (push '() groups) (setq ingroup t)
12115 (when (not (= cnt 0))
12116 (setq cnt 0)
12117 (insert "\n"))
12118 (insert "{ "))
12119 ((equal e '(:endgroup))
12120 (setq ingroup nil cnt 0)
12121 (insert "}\n"))
12122 ((equal e '(:newline))
12123 (when (not (= cnt 0))
12124 (setq cnt 0)
12125 (insert "\n")
12126 (setq e (car tbl))
12127 (while (equal (car tbl) '(:newline))
12128 (insert "\n")
12129 (setq tbl (cdr tbl)))))
12131 (setq tg (car e) c (cdr e))
12132 (if ingroup (push tg (car groups)))
12133 (setq tg (org-add-props tg nil 'face
12134 (org-get-todo-face tg)))
12135 (if (and (= cnt 0) (not ingroup)) (insert " "))
12136 (insert "[" c "] " tg (make-string
12137 (- fwidth 4 (length tg)) ?\ ))
12138 (when (= (setq cnt (1+ cnt)) ncol)
12139 (insert "\n")
12140 (if ingroup (insert " "))
12141 (setq cnt 0)))))
12142 (insert "\n")
12143 (goto-char (point-min))
12144 (if (not expert) (org-fit-window-to-buffer))
12145 (message "[a-z..]:Set [SPC]:clear")
12146 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12147 (cond
12148 ((or (= c ?\C-g)
12149 (and (= c ?q) (not (rassoc c fulltable))))
12150 (setq quit-flag t))
12151 ((= c ?\ ) nil)
12152 ((setq e (rassoc c fulltable) tg (car e))
12154 (t (setq quit-flag t)))))))
12156 (defun org-entry-is-todo-p ()
12157 (member (org-get-todo-state) org-not-done-keywords))
12159 (defun org-entry-is-done-p ()
12160 (member (org-get-todo-state) org-done-keywords))
12162 (defun org-get-todo-state ()
12163 (save-excursion
12164 (org-back-to-heading t)
12165 (and (looking-at org-todo-line-regexp)
12166 (match-end 2)
12167 (match-string 2))))
12169 (defun org-at-date-range-p (&optional inactive-ok)
12170 "Is the cursor inside a date range?"
12171 (interactive)
12172 (save-excursion
12173 (catch 'exit
12174 (let ((pos (point)))
12175 (skip-chars-backward "^[<\r\n")
12176 (skip-chars-backward "<[")
12177 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12178 (>= (match-end 0) pos)
12179 (throw 'exit t))
12180 (skip-chars-backward "^<[\r\n")
12181 (skip-chars-backward "<[")
12182 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12183 (>= (match-end 0) pos)
12184 (throw 'exit t)))
12185 nil)))
12187 (defun org-get-repeat (&optional tagline)
12188 "Check if there is a deadline/schedule with repeater in this entry."
12189 (save-match-data
12190 (save-excursion
12191 (org-back-to-heading t)
12192 (and (re-search-forward (if tagline
12193 (concat tagline "\\s-*" org-repeat-re)
12194 org-repeat-re)
12195 (org-entry-end-position) t)
12196 (match-string-no-properties 1)))))
12198 (defvar org-last-changed-timestamp)
12199 (defvar org-last-inserted-timestamp)
12200 (defvar org-log-post-message)
12201 (defvar org-log-note-purpose)
12202 (defvar org-log-note-how)
12203 (defvar org-log-note-extra)
12204 (defun org-auto-repeat-maybe (done-word)
12205 "Check if the current headline contains a repeated deadline/schedule.
12206 If yes, set TODO state back to what it was and change the base date
12207 of repeating deadline/scheduled time stamps to new date.
12208 This function is run automatically after each state change to a DONE state."
12209 ;; last-state is dynamically scoped into this function
12210 (let* ((repeat (org-get-repeat))
12211 (aa (assoc org-last-state org-todo-kwd-alist))
12212 (interpret (nth 1 aa))
12213 (head (nth 2 aa))
12214 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12215 (msg "Entry repeats: ")
12216 (org-log-done nil)
12217 (org-todo-log-states nil)
12218 re type n what ts time to-state)
12219 (when repeat
12220 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12221 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12222 org-todo-repeat-to-state))
12223 (unless (and to-state (member to-state org-todo-keywords-1))
12224 (setq to-state (if (eq interpret 'type) org-last-state head)))
12225 (org-todo to-state)
12226 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12227 (org-entry-put nil "LAST_REPEAT" (format-time-string
12228 (org-time-stamp-format t t))))
12229 (when org-log-repeat
12230 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12231 (memq 'org-add-log-note post-command-hook))
12232 ;; OK, we are already setup for some record
12233 (if (eq org-log-repeat 'note)
12234 ;; make sure we take a note, not only a time stamp
12235 (setq org-log-note-how 'note))
12236 ;; Set up for taking a record
12237 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12238 org-last-state
12239 'findpos org-log-repeat)))
12240 (org-back-to-heading t)
12241 (org-add-planning-info nil nil 'closed)
12242 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12243 org-deadline-time-regexp "\\)\\|\\("
12244 org-ts-regexp "\\)"))
12245 (while (re-search-forward
12246 re (save-excursion (outline-next-heading) (point)) t)
12247 (setq type (if (match-end 1) org-scheduled-string
12248 (if (match-end 3) org-deadline-string "Plain:"))
12249 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12250 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12251 (setq n (string-to-number (match-string 2 ts))
12252 what (match-string 3 ts))
12253 (if (equal what "w") (setq n (* n 7) what "d"))
12254 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12255 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12256 ;; Preparation, see if we need to modify the start date for the change
12257 (when (match-end 1)
12258 (setq time (save-match-data (org-time-string-to-time ts)))
12259 (cond
12260 ((equal (match-string 1 ts) ".")
12261 ;; Shift starting date to today
12262 (org-timestamp-change
12263 (- (org-today) (time-to-days time))
12264 'day))
12265 ((equal (match-string 1 ts) "+")
12266 (let ((nshiftmax 10) (nshift 0))
12267 (while (or (= nshift 0)
12268 (<= (time-to-days time)
12269 (time-to-days (current-time))))
12270 (when (= (incf nshift) nshiftmax)
12271 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12272 (error "Abort")))
12273 (org-timestamp-change n (cdr (assoc what whata)))
12274 (org-at-timestamp-p t)
12275 (setq ts (match-string 1))
12276 (setq time (save-match-data (org-time-string-to-time ts)))))
12277 (org-timestamp-change (- n) (cdr (assoc what whata)))
12278 ;; rematch, so that we have everything in place for the real shift
12279 (org-at-timestamp-p t)
12280 (setq ts (match-string 1))
12281 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12282 (org-timestamp-change n (cdr (assoc what whata)))
12283 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12284 (setq org-log-post-message msg)
12285 (message "%s" msg))))
12287 (defun org-show-todo-tree (arg)
12288 "Make a compact tree which shows all headlines marked with TODO.
12289 The tree will show the lines where the regexp matches, and all higher
12290 headlines above the match.
12291 With a \\[universal-argument] prefix, prompt for a regexp to match.
12292 With a numeric prefix N, construct a sparse tree for the Nth element
12293 of `org-todo-keywords-1'."
12294 (interactive "P")
12295 (let ((case-fold-search nil)
12296 (kwd-re
12297 (cond ((null arg) org-not-done-regexp)
12298 ((equal arg '(4))
12299 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12300 (mapcar 'list org-todo-keywords-1))))
12301 (concat "\\("
12302 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12303 "\\)\\>")))
12304 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12305 (regexp-quote (nth (1- (prefix-numeric-value arg))
12306 org-todo-keywords-1)))
12307 (t (error "Invalid prefix argument: %s" arg)))))
12308 (message "%d TODO entries found"
12309 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12311 (defun org-deadline (&optional remove time)
12312 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12313 With argument REMOVE, remove any deadline from the item.
12314 With argument TIME, set the deadline at the corresponding date. TIME
12315 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12316 (interactive "P")
12317 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12318 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12319 'region-start-level 'region))
12320 org-loop-over-headlines-in-active-region)
12321 (org-map-entries
12322 `(org-deadline ',remove ,time)
12323 org-loop-over-headlines-in-active-region
12324 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12325 (let* ((old-date (org-entry-get nil "DEADLINE"))
12326 (repeater (and old-date
12327 (string-match
12328 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12329 old-date)
12330 (match-string 1 old-date))))
12331 (if remove
12332 (progn
12333 (when (and old-date org-log-redeadline)
12334 (org-add-log-setup 'deldeadline nil old-date 'findpos
12335 org-log-redeadline))
12336 (org-remove-timestamp-with-keyword org-deadline-string)
12337 (message "Item no longer has a deadline."))
12338 (org-add-planning-info 'deadline time 'closed)
12339 (when (and old-date org-log-redeadline
12340 (not (equal old-date
12341 (substring org-last-inserted-timestamp 1 -1))))
12342 (org-add-log-setup 'redeadline nil old-date 'findpos
12343 org-log-redeadline))
12344 (when repeater
12345 (save-excursion
12346 (org-back-to-heading t)
12347 (when (re-search-forward (concat org-deadline-string " "
12348 org-last-inserted-timestamp)
12349 (save-excursion
12350 (outline-next-heading) (point)) t)
12351 (goto-char (1- (match-end 0)))
12352 (insert " " repeater)
12353 (setq org-last-inserted-timestamp
12354 (concat (substring org-last-inserted-timestamp 0 -1)
12355 " " repeater
12356 (substring org-last-inserted-timestamp -1))))))
12357 (message "Deadline on %s" org-last-inserted-timestamp)))))
12359 (defun org-schedule (&optional remove time)
12360 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12361 With argument REMOVE, remove any scheduling date from the item.
12362 With argument TIME, scheduled at the corresponding date. TIME can
12363 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12364 (interactive "P")
12365 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12366 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12367 'region-start-level 'region))
12368 org-loop-over-headlines-in-active-region)
12369 (org-map-entries
12370 `(org-schedule ',remove ,time)
12371 org-loop-over-headlines-in-active-region
12372 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12373 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12374 (repeater (and old-date
12375 (string-match
12376 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12377 old-date)
12378 (match-string 1 old-date))))
12379 (if remove
12380 (progn
12381 (when (and old-date org-log-reschedule)
12382 (org-add-log-setup 'delschedule nil old-date 'findpos
12383 org-log-reschedule))
12384 (org-remove-timestamp-with-keyword org-scheduled-string)
12385 (message "Item is no longer scheduled."))
12386 (org-add-planning-info 'scheduled time 'closed)
12387 (when (and old-date org-log-reschedule
12388 (not (equal old-date
12389 (substring org-last-inserted-timestamp 1 -1))))
12390 (org-add-log-setup 'reschedule nil old-date 'findpos
12391 org-log-reschedule))
12392 (when repeater
12393 (save-excursion
12394 (org-back-to-heading t)
12395 (when (re-search-forward (concat org-scheduled-string " "
12396 org-last-inserted-timestamp)
12397 (save-excursion
12398 (outline-next-heading) (point)) t)
12399 (goto-char (1- (match-end 0)))
12400 (insert " " repeater)
12401 (setq org-last-inserted-timestamp
12402 (concat (substring org-last-inserted-timestamp 0 -1)
12403 " " repeater
12404 (substring org-last-inserted-timestamp -1))))))
12405 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12407 (defun org-get-scheduled-time (pom &optional inherit)
12408 "Get the scheduled time as a time tuple, of a format suitable
12409 for calling org-schedule with, or if there is no scheduling,
12410 returns nil."
12411 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12412 (when time
12413 (apply 'encode-time (org-parse-time-string time)))))
12415 (defun org-get-deadline-time (pom &optional inherit)
12416 "Get the deadline as a time tuple, of a format suitable for
12417 calling org-deadline with, or if there is no scheduling, returns
12418 nil."
12419 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12420 (when time
12421 (apply 'encode-time (org-parse-time-string time)))))
12423 (defun org-remove-timestamp-with-keyword (keyword)
12424 "Remove all time stamps with KEYWORD in the current entry."
12425 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12426 beg)
12427 (save-excursion
12428 (org-back-to-heading t)
12429 (setq beg (point))
12430 (outline-next-heading)
12431 (while (re-search-backward re beg t)
12432 (replace-match "")
12433 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12434 (equal (char-before) ?\ ))
12435 (backward-delete-char 1)
12436 (if (string-match "^[ \t]*$" (buffer-substring
12437 (point-at-bol) (point-at-eol)))
12438 (delete-region (point-at-bol)
12439 (min (point-max) (1+ (point-at-eol))))))))))
12441 (defun org-add-planning-info (what &optional time &rest remove)
12442 "Insert new timestamp with keyword in the line directly after the headline.
12443 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12444 If non is given, the user is prompted for a date.
12445 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12446 be removed."
12447 (interactive)
12448 (let (org-time-was-given org-end-time-was-given ts
12449 end default-time default-input)
12451 (catch 'exit
12452 (when (and (memq what '(scheduled deadline))
12453 (or (not time)
12454 (and (stringp time)
12455 (string-match "^[-+]+[0-9]" time))))
12456 ;; Try to get a default date/time from existing timestamp
12457 (save-excursion
12458 (org-back-to-heading t)
12459 (setq end (save-excursion (outline-next-heading) (point)))
12460 (when (re-search-forward (if (eq what 'scheduled)
12461 org-scheduled-time-regexp
12462 org-deadline-time-regexp)
12463 end t)
12464 (setq ts (match-string 1)
12465 default-time
12466 (apply 'encode-time (org-parse-time-string ts))
12467 default-input (and ts (org-get-compact-tod ts))))))
12468 (when what
12469 (setq time
12470 (if (stringp time)
12471 ;; This is a string (relative or absolute), set proper date
12472 (apply 'encode-time
12473 (org-read-date-analyze
12474 time default-time (decode-time default-time)))
12475 ;; If necessary, get the time from the user
12476 (or time (org-read-date nil 'to-time nil nil
12477 default-time default-input)))))
12479 (when (and org-insert-labeled-timestamps-at-point
12480 (member what '(scheduled deadline)))
12481 (insert
12482 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12483 (org-insert-time-stamp time org-time-was-given
12484 nil nil nil (list org-end-time-was-given))
12485 (setq what nil))
12486 (save-excursion
12487 (save-restriction
12488 (let (col list elt ts buffer-invisibility-spec)
12489 (org-back-to-heading t)
12490 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12491 (goto-char (match-end 1))
12492 (setq col (current-column))
12493 (goto-char (match-end 0))
12494 (if (eobp) (insert "\n") (forward-char 1))
12495 (when (and (not what)
12496 (not (looking-at
12497 (concat "[ \t]*"
12498 org-keyword-time-not-clock-regexp))))
12499 ;; Nothing to add, nothing to remove...... :-)
12500 (throw 'exit nil))
12501 (if (and (not (looking-at org-outline-regexp))
12502 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12503 "[^\r\n]*"))
12504 (not (equal (match-string 1) org-clock-string)))
12505 (narrow-to-region (match-beginning 0) (match-end 0))
12506 (insert-before-markers "\n")
12507 (backward-char 1)
12508 (narrow-to-region (point) (point))
12509 (and org-adapt-indentation (org-indent-to-column col)))
12510 ;; Check if we have to remove something.
12511 (setq list (cons what remove))
12512 (while list
12513 (setq elt (pop list))
12514 (when (or (and (eq elt 'scheduled)
12515 (re-search-forward org-scheduled-time-regexp nil t))
12516 (and (eq elt 'deadline)
12517 (re-search-forward org-deadline-time-regexp nil t))
12518 (and (eq elt 'closed)
12519 (re-search-forward org-closed-time-regexp nil t)))
12520 (replace-match "")
12521 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12522 (and (looking-at "[ \t]+") (replace-match ""))
12523 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12524 (when what
12525 (insert
12526 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12527 (cond ((eq what 'scheduled) org-scheduled-string)
12528 ((eq what 'deadline) org-deadline-string)
12529 ((eq what 'closed) org-closed-string))
12530 " ")
12531 (setq ts (org-insert-time-stamp
12532 time
12533 (or org-time-was-given
12534 (and (eq what 'closed) org-log-done-with-time))
12535 (eq what 'closed)
12536 nil nil (list org-end-time-was-given)))
12537 (insert
12538 (if (not (or (bolp) (eq (char-before) ?\ )
12539 (memq (char-after) '(32 10))
12540 (eobp))) " " ""))
12541 (end-of-line 1))
12542 (goto-char (point-min))
12543 (widen)
12544 (if (and (looking-at "[ \t]*\n")
12545 (equal (char-before) ?\n))
12546 (delete-region (1- (point)) (point-at-eol)))
12547 ts))))))
12549 (defvar org-log-note-marker (make-marker))
12550 (defvar org-log-note-purpose nil)
12551 (defvar org-log-note-state nil)
12552 (defvar org-log-note-previous-state nil)
12553 (defvar org-log-note-how nil)
12554 (defvar org-log-note-extra nil)
12555 (defvar org-log-note-window-configuration nil)
12556 (defvar org-log-note-return-to (make-marker))
12557 (defvar org-log-note-effective-time nil
12558 "Remembered current time so that dynamically scoped
12559 `org-extend-today-until' affects tha timestamps in state change
12560 log")
12562 (defvar org-log-post-message nil
12563 "Message to be displayed after a log note has been stored.
12564 The auto-repeater uses this.")
12566 (defun org-add-note ()
12567 "Add a note to the current entry.
12568 This is done in the same way as adding a state change note."
12569 (interactive)
12570 (org-add-log-setup 'note nil nil 'findpos nil))
12572 (defvar org-property-end-re)
12573 (defun org-add-log-setup (&optional purpose state prev-state
12574 findpos how extra)
12575 "Set up the post command hook to take a note.
12576 If this is about to TODO state change, the new state is expected in STATE.
12577 When FINDPOS is non-nil, find the correct position for the note in
12578 the current entry. If not, assume that it can be inserted at point.
12579 HOW is an indicator what kind of note should be created.
12580 EXTRA is additional text that will be inserted into the notes buffer."
12581 (let* ((org-log-into-drawer (org-log-into-drawer))
12582 (drawer (cond ((stringp org-log-into-drawer)
12583 org-log-into-drawer)
12584 (org-log-into-drawer "LOGBOOK"))))
12585 (save-restriction
12586 (save-excursion
12587 (when findpos
12588 (org-back-to-heading t)
12589 (narrow-to-region (point) (save-excursion
12590 (outline-next-heading) (point)))
12591 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12592 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12593 "[^\r\n]*\\)?"))
12594 (goto-char (match-end 0))
12595 (cond
12596 (drawer
12597 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12598 nil t)
12599 (progn
12600 (goto-char (match-end 0))
12601 (or org-log-states-order-reversed
12602 (and (re-search-forward org-property-end-re nil t)
12603 (goto-char (1- (match-beginning 0))))))
12604 (insert "\n:" drawer ":\n:END:")
12605 (beginning-of-line 0)
12606 (org-indent-line)
12607 (beginning-of-line 2)
12608 (org-indent-line)
12609 (end-of-line 0)))
12610 ((and org-log-state-notes-insert-after-drawers
12611 (save-excursion
12612 (forward-line) (looking-at org-drawer-regexp)))
12613 (forward-line)
12614 (while (looking-at org-drawer-regexp)
12615 (goto-char (match-end 0))
12616 (re-search-forward org-property-end-re (point-max) t)
12617 (forward-line))
12618 (forward-line -1)))
12619 (unless org-log-states-order-reversed
12620 (and (= (char-after) ?\n) (forward-char 1))
12621 (org-skip-over-state-notes)
12622 (skip-chars-backward " \t\n\r")))
12623 (move-marker org-log-note-marker (point))
12624 (setq org-log-note-purpose purpose
12625 org-log-note-state state
12626 org-log-note-previous-state prev-state
12627 org-log-note-how how
12628 org-log-note-extra extra
12629 org-log-note-effective-time (org-current-effective-time))
12630 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12632 (defun org-skip-over-state-notes ()
12633 "Skip past the list of State notes in an entry."
12634 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12635 (when (ignore-errors (goto-char (org-in-item-p)))
12636 (let* ((struct (org-list-struct))
12637 (prevs (org-list-prevs-alist struct)))
12638 (while (looking-at "[ \t]*- State")
12639 (goto-char (or (org-list-get-next-item (point) struct prevs)
12640 (org-list-get-item-end (point) struct)))))))
12642 (defun org-add-log-note (&optional purpose)
12643 "Pop up a window for taking a note, and add this note later at point."
12644 (remove-hook 'post-command-hook 'org-add-log-note)
12645 (setq org-log-note-window-configuration (current-window-configuration))
12646 (delete-other-windows)
12647 (move-marker org-log-note-return-to (point))
12648 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12649 (goto-char org-log-note-marker)
12650 (org-switch-to-buffer-other-window "*Org Note*")
12651 (erase-buffer)
12652 (if (memq org-log-note-how '(time state))
12653 (let (current-prefix-arg) (org-store-log-note))
12654 (let ((org-inhibit-startup t)) (org-mode))
12655 (insert (format "# Insert note for %s.
12656 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12657 (cond
12658 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12659 ((eq org-log-note-purpose 'done) "closed todo item")
12660 ((eq org-log-note-purpose 'state)
12661 (format "state change from \"%s\" to \"%s\""
12662 (or org-log-note-previous-state "")
12663 (or org-log-note-state "")))
12664 ((eq org-log-note-purpose 'reschedule)
12665 "rescheduling")
12666 ((eq org-log-note-purpose 'delschedule)
12667 "no longer scheduled")
12668 ((eq org-log-note-purpose 'redeadline)
12669 "changing deadline")
12670 ((eq org-log-note-purpose 'deldeadline)
12671 "removing deadline")
12672 ((eq org-log-note-purpose 'refile)
12673 "refiling")
12674 ((eq org-log-note-purpose 'note)
12675 "this entry")
12676 (t (error "This should not happen")))))
12677 (if org-log-note-extra (insert org-log-note-extra))
12678 (org-set-local 'org-finish-function 'org-store-log-note)
12679 (run-hooks 'org-log-buffer-setup-hook)))
12681 (defvar org-note-abort nil) ; dynamically scoped
12682 (defun org-store-log-note ()
12683 "Finish taking a log note, and insert it to where it belongs."
12684 (let ((txt (buffer-string))
12685 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12686 lines ind bul)
12687 (kill-buffer (current-buffer))
12688 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12689 (setq txt (replace-match "" t t txt)))
12690 (if (string-match "\\s-+\\'" txt)
12691 (setq txt (replace-match "" t t txt)))
12692 (setq lines (org-split-string txt "\n"))
12693 (when (and note (string-match "\\S-" note))
12694 (setq note
12695 (org-replace-escapes
12696 note
12697 (list (cons "%u" (user-login-name))
12698 (cons "%U" user-full-name)
12699 (cons "%t" (format-time-string
12700 (org-time-stamp-format 'long 'inactive)
12701 org-log-note-effective-time))
12702 (cons "%T" (format-time-string
12703 (org-time-stamp-format 'long nil)
12704 org-log-note-effective-time))
12705 (cons "%d" (format-time-string
12706 (org-time-stamp-format nil 'inactive)
12707 org-log-note-effective-time))
12708 (cons "%D" (format-time-string
12709 (org-time-stamp-format nil nil)
12710 org-log-note-effective-time))
12711 (cons "%s" (if org-log-note-state
12712 (concat "\"" org-log-note-state "\"")
12713 ""))
12714 (cons "%S" (if org-log-note-previous-state
12715 (concat "\"" org-log-note-previous-state "\"")
12716 "\"\"")))))
12717 (if lines (setq note (concat note " \\\\")))
12718 (push note lines))
12719 (when (or current-prefix-arg org-note-abort)
12720 (when org-log-into-drawer
12721 (org-remove-empty-drawer-at
12722 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12723 org-log-note-marker))
12724 (setq lines nil))
12725 (when lines
12726 (with-current-buffer (marker-buffer org-log-note-marker)
12727 (save-excursion
12728 (goto-char org-log-note-marker)
12729 (move-marker org-log-note-marker nil)
12730 (end-of-line 1)
12731 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12732 (setq ind (save-excursion
12733 (if (ignore-errors (goto-char (org-in-item-p)))
12734 (let ((struct (org-list-struct)))
12735 (org-list-get-ind
12736 (org-list-get-top-point struct) struct))
12737 (skip-chars-backward " \r\t\n")
12738 (cond
12739 ((and (org-at-heading-p)
12740 org-adapt-indentation)
12741 (1+ (org-current-level)))
12742 ((org-at-heading-p) 0)
12743 (t (org-get-indentation))))))
12744 (setq bul (org-list-bullet-string "-"))
12745 (org-indent-line-to ind)
12746 (insert bul (pop lines))
12747 (let ((ind-body (+ (length bul) ind)))
12748 (while lines
12749 (insert "\n")
12750 (org-indent-line-to ind-body)
12751 (insert (pop lines))))
12752 (message "Note stored")
12753 (org-back-to-heading t)
12754 (org-cycle-hide-drawers 'children)))))
12755 (set-window-configuration org-log-note-window-configuration)
12756 (with-current-buffer (marker-buffer org-log-note-return-to)
12757 (goto-char org-log-note-return-to))
12758 (move-marker org-log-note-return-to nil)
12759 (and org-log-post-message (message "%s" org-log-post-message)))
12761 (defun org-remove-empty-drawer-at (drawer pos)
12762 "Remove an empty drawer DRAWER at position POS.
12763 POS may also be a marker."
12764 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12765 (save-excursion
12766 (save-restriction
12767 (widen)
12768 (goto-char pos)
12769 (if (org-in-regexp
12770 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12771 (replace-match ""))))))
12773 (defvar org-ts-type nil)
12774 (defun org-sparse-tree (&optional arg type)
12775 "Create a sparse tree, prompt for the details.
12776 This command can create sparse trees. You first need to select the type
12777 of match used to create the tree:
12779 t Show all TODO entries.
12780 T Show entries with a specific TODO keyword.
12781 m Show entries selected by a tags/property match.
12782 p Enter a property name and its value (both with completion on existing
12783 names/values) and show entries with that property.
12784 r Show entries matching a regular expression (`/' can be used as well).
12785 b Show deadlines and scheduled items before a date.
12786 a Show deadlines and scheduled items after a date.
12787 d Show deadlines due within `org-deadline-warning-days'.
12788 D Show deadlines and scheduled items between a date range."
12789 (interactive "P")
12790 (let (ans kwd value ts-type)
12791 (setq type (or type org-sparse-tree-default-date-type))
12792 (setq org-ts-type type)
12793 (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"
12794 (cond ((eq type 'all) "all timestamps")
12795 ((eq type 'scheduled) "only scheduled")
12796 ((eq type 'deadline) "only deadline")
12797 ((eq type 'active) "only active timestamps")
12798 ((eq type 'inactive) "only inactive timestamps")
12799 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12800 (t "scheduled/deadline")))
12801 (setq ans (read-char-exclusive))
12802 (cond
12803 ((equal ans ?c)
12804 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12805 ((equal ans ?d)
12806 (call-interactively 'org-check-deadlines))
12807 ((equal ans ?b)
12808 (call-interactively 'org-check-before-date))
12809 ((equal ans ?a)
12810 (call-interactively 'org-check-after-date))
12811 ((equal ans ?D)
12812 (call-interactively 'org-check-dates-range))
12813 ((equal ans ?t)
12814 (org-show-todo-tree nil))
12815 ((equal ans ?T)
12816 (org-show-todo-tree '(4)))
12817 ((member ans '(?T ?m))
12818 (call-interactively 'org-match-sparse-tree))
12819 ((member ans '(?p ?P))
12820 (setq kwd (org-icompleting-read "Property: "
12821 (mapcar 'list (org-buffer-property-keys))))
12822 (setq value (org-icompleting-read "Value: "
12823 (mapcar 'list (org-property-values kwd))))
12824 (unless (string-match "\\`{.*}\\'" value)
12825 (setq value (concat "\"" value "\"")))
12826 (org-match-sparse-tree arg (concat kwd "=" value)))
12827 ((member ans '(?r ?R ?/))
12828 (call-interactively 'org-occur))
12829 (t (error "No such sparse tree command \"%c\"" ans)))))
12831 (defvar org-occur-highlights nil
12832 "List of overlays used for occur matches.")
12833 (make-variable-buffer-local 'org-occur-highlights)
12834 (defvar org-occur-parameters nil
12835 "Parameters of the active org-occur calls.
12836 This is a list, each call to org-occur pushes as cons cell,
12837 containing the regular expression and the callback, onto the list.
12838 The list can contain several entries if `org-occur' has been called
12839 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12840 will only contain one set of parameters. When the highlights are
12841 removed (for example with `C-c C-c', or with the next edit (depending
12842 on `org-remove-highlights-with-change'), this variable is emptied
12843 as well.")
12844 (make-variable-buffer-local 'org-occur-parameters)
12846 (defun org-occur (regexp &optional keep-previous callback)
12847 "Make a compact tree which shows all matches of REGEXP.
12848 The tree will show the lines where the regexp matches, and all higher
12849 headlines above the match. It will also show the heading after the match,
12850 to make sure editing the matching entry is easy.
12851 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12852 call to `org-occur' will be kept, to allow stacking of calls to this
12853 command.
12854 If CALLBACK is non-nil, it is a function which is called to confirm
12855 that the match should indeed be shown."
12856 (interactive "sRegexp: \nP")
12857 (when (equal regexp "")
12858 (error "Regexp cannot be empty"))
12859 (unless keep-previous
12860 (org-remove-occur-highlights nil nil t))
12861 (push (cons regexp callback) org-occur-parameters)
12862 (let ((cnt 0))
12863 (save-excursion
12864 (goto-char (point-min))
12865 (if (or (not keep-previous) ; do not want to keep
12866 (not org-occur-highlights)) ; no previous matches
12867 ;; hide everything
12868 (org-overview))
12869 (while (re-search-forward regexp nil t)
12870 (when (or (not callback)
12871 (save-match-data (funcall callback)))
12872 (setq cnt (1+ cnt))
12873 (when org-highlight-sparse-tree-matches
12874 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12875 (org-show-context 'occur-tree))))
12876 (when org-remove-highlights-with-change
12877 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12878 nil 'local))
12879 (unless org-sparse-tree-open-archived-trees
12880 (org-hide-archived-subtrees (point-min) (point-max)))
12881 (run-hooks 'org-occur-hook)
12882 (if (org-called-interactively-p 'interactive)
12883 (message "%d match(es) for regexp %s" cnt regexp))
12884 cnt))
12886 (defun org-occur-next-match (&optional n reset)
12887 "Function for `next-error-function' to find sparse tree matches.
12888 N is the number of matches to move, when negative move backwards.
12889 RESET is entirely ignored - this function always goes back to the
12890 starting point when no match is found."
12891 (let* ((limit (if (< n 0) (point-min) (point-max)))
12892 (search-func (if (< n 0)
12893 'previous-single-char-property-change
12894 'next-single-char-property-change))
12895 (n (abs n))
12896 (pos (point))
12898 (catch 'exit
12899 (while (setq p1 (funcall search-func (point) 'org-type))
12900 (when (equal p1 limit)
12901 (goto-char pos)
12902 (error "No more matches"))
12903 (when (equal (get-char-property p1 'org-type) 'org-occur)
12904 (setq n (1- n))
12905 (when (= n 0)
12906 (goto-char p1)
12907 (throw 'exit (point))))
12908 (goto-char p1))
12909 (goto-char p1)
12910 (error "No more matches"))))
12912 (defun org-show-context (&optional key)
12913 "Make sure point and context are visible.
12914 How much context is shown depends upon the variables
12915 `org-show-hierarchy-above', `org-show-following-heading',
12916 `org-show-entry-below' and `org-show-siblings'."
12917 (let ((heading-p (org-at-heading-p t))
12918 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12919 (following-p (org-get-alist-option org-show-following-heading key))
12920 (entry-p (org-get-alist-option org-show-entry-below key))
12921 (siblings-p (org-get-alist-option org-show-siblings key)))
12922 (catch 'exit
12923 ;; Show heading or entry text
12924 (if (and heading-p (not entry-p))
12925 (org-flag-heading nil) ; only show the heading
12926 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12927 (org-show-hidden-entry))) ; show entire entry
12928 (when following-p
12929 ;; Show next sibling, or heading below text
12930 (save-excursion
12931 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12932 (org-flag-heading nil))))
12933 (when siblings-p (org-show-siblings))
12934 (when hierarchy-p
12935 ;; show all higher headings, possibly with siblings
12936 (save-excursion
12937 (while (and (condition-case nil
12938 (progn (org-up-heading-all 1) t)
12939 (error nil))
12940 (not (bobp)))
12941 (org-flag-heading nil)
12942 (when siblings-p (org-show-siblings))))))))
12944 (defvar org-reveal-start-hook nil
12945 "Hook run before revealing a location.")
12947 (defun org-reveal (&optional siblings)
12948 "Show current entry, hierarchy above it, and the following headline.
12949 This can be used to show a consistent set of context around locations
12950 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12951 not t for the search context.
12953 With optional argument SIBLINGS, on each level of the hierarchy all
12954 siblings are shown. This repairs the tree structure to what it would
12955 look like when opened with hierarchical calls to `org-cycle'.
12956 With double optional argument \\[universal-argument] \\[universal-argument], \
12957 go to the parent and show the
12958 entire tree."
12959 (interactive "P")
12960 (run-hooks 'org-reveal-start-hook)
12961 (let ((org-show-hierarchy-above t)
12962 (org-show-following-heading t)
12963 (org-show-siblings (if siblings t org-show-siblings)))
12964 (org-show-context nil))
12965 (when (equal siblings '(16))
12966 (save-excursion
12967 (when (org-up-heading-safe)
12968 (org-show-subtree)
12969 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12971 (defun org-highlight-new-match (beg end)
12972 "Highlight from BEG to END and mark the highlight is an occur headline."
12973 (let ((ov (make-overlay beg end)))
12974 (overlay-put ov 'face 'secondary-selection)
12975 (overlay-put ov 'org-type 'org-occur)
12976 (push ov org-occur-highlights)))
12978 (defun org-remove-occur-highlights (&optional beg end noremove)
12979 "Remove the occur highlights from the buffer.
12980 BEG and END are ignored. If NOREMOVE is nil, remove this function
12981 from the `before-change-functions' in the current buffer."
12982 (interactive)
12983 (unless org-inhibit-highlight-removal
12984 (mapc 'delete-overlay org-occur-highlights)
12985 (setq org-occur-highlights nil)
12986 (setq org-occur-parameters nil)
12987 (unless noremove
12988 (remove-hook 'before-change-functions
12989 'org-remove-occur-highlights 'local))))
12991 ;;;; Priorities
12993 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12994 "Regular expression matching the priority indicator.")
12996 (defvar org-remove-priority-next-time nil)
12998 (defun org-priority-up ()
12999 "Increase the priority of the current item."
13000 (interactive)
13001 (org-priority 'up))
13003 (defun org-priority-down ()
13004 "Decrease the priority of the current item."
13005 (interactive)
13006 (org-priority 'down))
13008 (defun org-priority (&optional action show)
13009 "Change the priority of an item.
13010 ACTION can be `set', `up', `down', or a character."
13011 (interactive "P")
13012 (if (equal action '(4))
13013 (org-show-priority)
13014 (unless org-enable-priority-commands
13015 (error "Priority commands are disabled"))
13016 (setq action (or action 'set))
13017 (let (current new news have remove)
13018 (save-excursion
13019 (org-back-to-heading t)
13020 (if (looking-at org-priority-regexp)
13021 (setq current (string-to-char (match-string 2))
13022 have t))
13023 (cond
13024 ((eq action 'remove)
13025 (setq remove t new ?\ ))
13026 ((or (eq action 'set)
13027 (if (featurep 'xemacs) (characterp action) (integerp action)))
13028 (if (not (eq action 'set))
13029 (setq new action)
13030 (message "Priority %c-%c, SPC to remove: "
13031 org-highest-priority org-lowest-priority)
13032 (save-match-data
13033 (setq new (read-char-exclusive))))
13034 (if (and (= (upcase org-highest-priority) org-highest-priority)
13035 (= (upcase org-lowest-priority) org-lowest-priority))
13036 (setq new (upcase new)))
13037 (cond ((equal new ?\ ) (setq remove t))
13038 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13039 (error "Priority must be between `%c' and `%c'"
13040 org-highest-priority org-lowest-priority))))
13041 ((eq action 'up)
13042 (setq new (if have
13043 (1- current) ; normal cycling
13044 ;; last priority was empty
13045 (if (eq last-command this-command)
13046 org-lowest-priority ; wrap around empty to lowest
13047 ;; default
13048 (if org-priority-start-cycle-with-default
13049 org-default-priority
13050 (1- org-default-priority))))))
13051 ((eq action 'down)
13052 (setq new (if have
13053 (1+ current) ; normal cycling
13054 ;; last priority was empty
13055 (if (eq last-command this-command)
13056 org-highest-priority ; wrap around empty to highest
13057 ;; default
13058 (if org-priority-start-cycle-with-default
13059 org-default-priority
13060 (1+ org-default-priority))))))
13061 (t (error "Invalid action")))
13062 (if (or (< (upcase new) org-highest-priority)
13063 (> (upcase new) org-lowest-priority))
13064 (if (and (memq action '(up down))
13065 (not have) (not (eq last-command this-command)))
13066 ;; `new' is from default priority
13067 (error
13068 "The default can not be set, see `org-default-priority' why")
13069 ;; normal cycling: `new' is beyond highest/lowest priority
13070 ;; and is wrapped around to the empty priority
13071 (setq remove t)))
13072 (setq news (format "%c" new))
13073 (if have
13074 (if remove
13075 (replace-match "" t t nil 1)
13076 (replace-match news t t nil 2))
13077 (if remove
13078 (error "No priority cookie found in line")
13079 (let ((case-fold-search nil))
13080 (looking-at org-todo-line-regexp))
13081 (if (match-end 2)
13082 (progn
13083 (goto-char (match-end 2))
13084 (insert " [#" news "]"))
13085 (goto-char (match-beginning 3))
13086 (insert "[#" news "] "))))
13087 (org-preserve-lc (org-set-tags nil 'align)))
13088 (if remove
13089 (message "Priority removed")
13090 (message "Priority of current item set to %s" news)))))
13092 (defun org-show-priority ()
13093 "Show the priority of the current item.
13094 This priority is composed of the main priority given with the [#A] cookies,
13095 and by additional input from the age of a schedules or deadline entry."
13096 (interactive)
13097 (let ((pri (if (eq major-mode 'org-agenda-mode)
13098 (org-get-at-bol 'priority)
13099 (save-excursion
13100 (save-match-data
13101 (beginning-of-line)
13102 (and (looking-at org-heading-regexp)
13103 (org-get-priority (match-string 0))))))))
13104 (message "Priority is %d" (if pri pri -1000))))
13106 (defun org-get-priority (s)
13107 "Find priority cookie and return priority."
13108 (if (functionp org-get-priority-function)
13109 (funcall org-get-priority-function)
13110 (save-match-data
13111 (if (not (string-match org-priority-regexp s))
13112 (* 1000 (- org-lowest-priority org-default-priority))
13113 (* 1000 (- org-lowest-priority
13114 (string-to-char (match-string 2 s))))))))
13116 ;;;; Tags
13118 (defvar org-agenda-archives-mode)
13119 (defvar org-map-continue-from nil
13120 "Position from where mapping should continue.
13121 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13123 (defvar org-scanner-tags nil
13124 "The current tag list while the tags scanner is running.")
13125 (defvar org-trust-scanner-tags nil
13126 "Should `org-get-tags-at' use the tags for the scanner.
13127 This is for internal dynamical scoping only.
13128 When this is non-nil, the function `org-get-tags-at' will return the value
13129 of `org-scanner-tags' instead of building the list by itself. This
13130 can lead to large speed-ups when the tags scanner is used in a file with
13131 many entries, and when the list of tags is retrieved, for example to
13132 obtain a list of properties. Building the tags list for each entry in such
13133 a file becomes an N^2 operation - but with this variable set, it scales
13134 as N.")
13136 (defun org-scan-tags (action matcher todo-only &optional start-level)
13137 "Scan headline tags with inheritance and produce output ACTION.
13139 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13140 or `agenda' to produce an entry list for an agenda view. It can also be
13141 a Lisp form or a function that should be called at each matched headline, in
13142 this case the return value is a list of all return values from these calls.
13144 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13145 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13146 only lines with a not-done TODO keyword are included in the output.
13147 This should be the same variable that was scoped into
13148 and set by `org-make-tags-matcher' when it constructed MATCHER.
13150 START-LEVEL can be a string with asterisks, reducing the scope to
13151 headlines matching this string."
13152 (require 'org-agenda)
13153 (let* ((re (concat "^"
13154 (if start-level
13155 ;; Get the correct level to match
13156 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13157 org-outline-regexp)
13158 " *\\(\\<\\("
13159 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13160 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13161 (props (list 'face 'default
13162 'done-face 'org-agenda-done
13163 'undone-face 'default
13164 'mouse-face 'highlight
13165 'org-not-done-regexp org-not-done-regexp
13166 'org-todo-regexp org-todo-regexp
13167 'org-complex-heading-regexp org-complex-heading-regexp
13168 'help-echo
13169 (format "mouse-2 or RET jump to org file %s"
13170 (abbreviate-file-name
13171 (or (buffer-file-name (buffer-base-buffer))
13172 (buffer-name (buffer-base-buffer)))))))
13173 (case-fold-search nil)
13174 (org-map-continue-from nil)
13175 lspos tags tags-list
13176 (tags-alist (list (cons 0 org-file-tags)))
13177 (llast 0) rtn rtn1 level category i txt
13178 todo marker entry priority)
13179 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13180 (setq action (list 'lambda nil action)))
13181 (save-excursion
13182 (goto-char (point-min))
13183 (when (eq action 'sparse-tree)
13184 (org-overview)
13185 (org-remove-occur-highlights))
13186 (while (re-search-forward re nil t)
13187 (setq org-map-continue-from nil)
13188 (catch :skip
13189 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13190 tags (if (match-end 4) (org-match-string-no-properties 4)))
13191 (goto-char (setq lspos (match-beginning 0)))
13192 (setq level (org-reduced-level (funcall outline-level))
13193 category (org-get-category))
13194 (setq i llast llast level)
13195 ;; remove tag lists from same and sublevels
13196 (while (>= i level)
13197 (when (setq entry (assoc i tags-alist))
13198 (setq tags-alist (delete entry tags-alist)))
13199 (setq i (1- i)))
13200 ;; add the next tags
13201 (when tags
13202 (setq tags (org-split-string tags ":")
13203 tags-alist
13204 (cons (cons level tags) tags-alist)))
13205 ;; compile tags for current headline
13206 (setq tags-list
13207 (if org-use-tag-inheritance
13208 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13209 tags)
13210 org-scanner-tags tags-list)
13211 (when org-use-tag-inheritance
13212 (setcdr (car tags-alist)
13213 (mapcar (lambda (x)
13214 (setq x (copy-sequence x))
13215 (org-add-prop-inherited x))
13216 (cdar tags-alist))))
13217 (when (and tags org-use-tag-inheritance
13218 (or (not (eq t org-use-tag-inheritance))
13219 org-tags-exclude-from-inheritance))
13220 ;; selective inheritance, remove uninherited ones
13221 (setcdr (car tags-alist)
13222 (org-remove-uninherited-tags (cdar tags-alist))))
13223 (when (and
13225 ;; eval matcher only when the todo condition is OK
13226 (and (or (not todo-only) (member todo org-not-done-keywords))
13227 (let ((case-fold-search t) (org-trust-scanner-tags t))
13228 (eval matcher)))
13230 ;; Call the skipper, but return t if it does not skip,
13231 ;; so that the `and' form continues evaluating
13232 (progn
13233 (unless (eq action 'sparse-tree) (org-agenda-skip))
13236 ;; Check if timestamps are deselecting this entry
13237 (or (not todo-only)
13238 (and (member todo org-not-done-keywords)
13239 (or (not org-agenda-tags-todo-honor-ignore-options)
13240 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13242 ;; Extra check for the archive tag
13243 ;; FIXME: Does the skipper already do this????
13245 (not (member org-archive-tag tags-list))
13246 ;; we have an archive tag, should we use this anyway?
13247 (or (not org-agenda-skip-archived-trees)
13248 (and (eq action 'agenda) org-agenda-archives-mode))))
13250 ;; select this headline
13252 (cond
13253 ((eq action 'sparse-tree)
13254 (and org-highlight-sparse-tree-matches
13255 (org-get-heading) (match-end 0)
13256 (org-highlight-new-match
13257 (match-beginning 1) (match-end 1)))
13258 (org-show-context 'tags-tree))
13259 ((eq action 'agenda)
13260 (setq txt (org-agenda-format-item
13262 (concat
13263 (if (eq org-tags-match-list-sublevels 'indented)
13264 (make-string (1- level) ?.) "")
13265 (org-get-heading))
13266 category
13267 tags-list)
13268 priority (org-get-priority txt))
13269 (goto-char lspos)
13270 (setq marker (org-agenda-new-marker))
13271 (org-add-props txt props
13272 'org-marker marker 'org-hd-marker marker 'org-category category
13273 'todo-state todo
13274 'priority priority 'type "tagsmatch")
13275 (push txt rtn))
13276 ((functionp action)
13277 (setq org-map-continue-from nil)
13278 (save-excursion
13279 (setq rtn1 (funcall action))
13280 (push rtn1 rtn)))
13281 (t (error "Invalid action")))
13283 ;; if we are to skip sublevels, jump to end of subtree
13284 (unless org-tags-match-list-sublevels
13285 (org-end-of-subtree t)
13286 (backward-char 1))))
13287 ;; Get the correct position from where to continue
13288 (if org-map-continue-from
13289 (goto-char org-map-continue-from)
13290 (and (= (point) lspos) (end-of-line 1)))))
13291 (when (and (eq action 'sparse-tree)
13292 (not org-sparse-tree-open-archived-trees))
13293 (org-hide-archived-subtrees (point-min) (point-max)))
13294 (nreverse rtn)))
13296 (defun org-remove-uninherited-tags (tags)
13297 "Remove all tags that are not inherited from the list TAGS."
13298 (cond
13299 ((eq org-use-tag-inheritance t)
13300 (if org-tags-exclude-from-inheritance
13301 (org-delete-all org-tags-exclude-from-inheritance tags)
13302 tags))
13303 ((not org-use-tag-inheritance) nil)
13304 ((stringp org-use-tag-inheritance)
13305 (delq nil (mapcar
13306 (lambda (x)
13307 (if (and (string-match org-use-tag-inheritance x)
13308 (not (member x org-tags-exclude-from-inheritance)))
13309 x nil))
13310 tags)))
13311 ((listp org-use-tag-inheritance)
13312 (delq nil (mapcar
13313 (lambda (x)
13314 (if (member x org-use-tag-inheritance) x nil))
13315 tags)))))
13317 (defun org-match-sparse-tree (&optional todo-only match)
13318 "Create a sparse tree according to tags string MATCH.
13319 MATCH can contain positive and negative selection of tags, like
13320 \"+WORK+URGENT-WITHBOSS\".
13321 If optional argument TODO-ONLY is non-nil, only select lines that are
13322 also TODO lines."
13323 (interactive "P")
13324 (org-agenda-prepare-buffers (list (current-buffer)))
13325 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13327 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13329 (defvar org-cached-props nil)
13330 (defun org-cached-entry-get (pom property)
13331 (if (or (eq t org-use-property-inheritance)
13332 (and (stringp org-use-property-inheritance)
13333 (string-match org-use-property-inheritance property))
13334 (and (listp org-use-property-inheritance)
13335 (member property org-use-property-inheritance)))
13336 ;; Caching is not possible, check it directly
13337 (org-entry-get pom property 'inherit)
13338 ;; Get all properties, so that we can do complicated checks easily
13339 (cdr (assoc property (or org-cached-props
13340 (setq org-cached-props
13341 (org-entry-properties pom)))))))
13343 (defun org-global-tags-completion-table (&optional files)
13344 "Return the list of all tags in all agenda buffer/files.
13345 Optional FILES argument is a list of files which can be used
13346 instead of the agenda files."
13347 (save-excursion
13348 (org-uniquify
13349 (delq nil
13350 (apply 'append
13351 (mapcar
13352 (lambda (file)
13353 (set-buffer (find-file-noselect file))
13354 (append (org-get-buffer-tags)
13355 (mapcar (lambda (x) (if (stringp (car-safe x))
13356 (list (car-safe x)) nil))
13357 org-tag-alist)))
13358 (if (and files (car files))
13359 files
13360 (org-agenda-files))))))))
13362 (defun org-make-tags-matcher (match)
13363 "Create the TAGS/TODO matcher form for the selection string MATCH.
13365 The variable `todo-only' is scoped dynamically into this function.
13366 It will be set to t if the matcher restricts matching to TODO entries,
13367 otherwise will not be touched.
13369 Returns a cons of the selection string MATCH and the constructed
13370 lisp form implementing the matcher. The matcher is to be evaluated
13371 at an Org entry, with point on the headline, and returns t if the
13372 entry matches the selection string MATCH. The returned lisp form
13373 references two variables with information about the entry, which
13374 must be bound around the form's evaluation: todo, the TODO keyword
13375 at the entry (or nil of none); and tags-list, the list of all tags
13376 at the entry including inherited ones. Additionally, the category
13377 of the entry (if any) must be specified as the text property
13378 'org-category on the headline.
13380 See also `org-scan-tags'.
13382 (declare (special todo-only))
13383 (unless (boundp 'todo-only)
13384 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13385 (unless match
13386 ;; Get a new match request, with completion
13387 (let ((org-last-tags-completion-table
13388 (org-global-tags-completion-table)))
13389 (setq match (org-completing-read-no-i
13390 "Match: " 'org-tags-completion-function nil nil nil
13391 'org-tags-history))))
13393 ;; Parse the string and create a lisp form
13394 (let ((match0 match)
13395 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13396 minus tag mm
13397 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13398 orterms term orlist re-p str-p level-p level-op time-p
13399 prop-p pn pv po gv rest)
13400 (if (string-match "/+" match)
13401 ;; match contains also a todo-matching request
13402 (progn
13403 (setq tagsmatch (substring match 0 (match-beginning 0))
13404 todomatch (substring match (match-end 0)))
13405 (if (string-match "^!" todomatch)
13406 (setq todo-only t todomatch (substring todomatch 1)))
13407 (if (string-match "^\\s-*$" todomatch)
13408 (setq todomatch nil)))
13409 ;; only matching tags
13410 (setq tagsmatch match todomatch nil))
13412 ;; Make the tags matcher
13413 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13414 (setq tagsmatcher t)
13415 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13416 (while (setq term (pop orterms))
13417 (while (and (equal (substring term -1) "\\") orterms)
13418 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13419 (while (string-match re term)
13420 (setq rest (substring term (match-end 0))
13421 minus (and (match-end 1)
13422 (equal (match-string 1 term) "-"))
13423 tag (save-match-data (replace-regexp-in-string
13424 "\\\\-" "-"
13425 (match-string 2 term)))
13426 re-p (equal (string-to-char tag) ?{)
13427 level-p (match-end 4)
13428 prop-p (match-end 5)
13429 mm (cond
13430 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13431 (level-p
13432 (setq level-op (org-op-to-function (match-string 3 term)))
13433 `(,level-op level ,(string-to-number
13434 (match-string 4 term))))
13435 (prop-p
13436 (setq pn (match-string 5 term)
13437 po (match-string 6 term)
13438 pv (match-string 7 term)
13439 re-p (equal (string-to-char pv) ?{)
13440 str-p (equal (string-to-char pv) ?\")
13441 time-p (save-match-data
13442 (string-match "^\"[[<].*[]>]\"$" pv))
13443 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13444 (if time-p (setq pv (org-matcher-time pv)))
13445 (setq po (org-op-to-function po (if time-p 'time str-p)))
13446 (cond
13447 ((equal pn "CATEGORY")
13448 (setq gv '(get-text-property (point) 'org-category)))
13449 ((equal pn "TODO")
13450 (setq gv 'todo))
13452 (setq gv `(org-cached-entry-get nil ,pn))))
13453 (if re-p
13454 (if (eq po 'org<>)
13455 `(not (string-match ,pv (or ,gv "")))
13456 `(string-match ,pv (or ,gv "")))
13457 (if str-p
13458 `(,po (or ,gv "") ,pv)
13459 `(,po (string-to-number (or ,gv ""))
13460 ,(string-to-number pv) ))))
13461 (t `(member ,tag tags-list)))
13462 mm (if minus (list 'not mm) mm)
13463 term rest)
13464 (push mm tagsmatcher))
13465 (push (if (> (length tagsmatcher) 1)
13466 (cons 'and tagsmatcher)
13467 (car tagsmatcher))
13468 orlist)
13469 (setq tagsmatcher nil))
13470 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13471 (setq tagsmatcher
13472 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13473 ;; Make the todo matcher
13474 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13475 (setq todomatcher t)
13476 (setq orterms (org-split-string todomatch "|") orlist nil)
13477 (while (setq term (pop orterms))
13478 (while (string-match re term)
13479 (setq minus (and (match-end 1)
13480 (equal (match-string 1 term) "-"))
13481 kwd (match-string 2 term)
13482 re-p (equal (string-to-char kwd) ?{)
13483 term (substring term (match-end 0))
13484 mm (if re-p
13485 `(string-match ,(substring kwd 1 -1) todo)
13486 (list 'equal 'todo kwd))
13487 mm (if minus (list 'not mm) mm))
13488 (push mm todomatcher))
13489 (push (if (> (length todomatcher) 1)
13490 (cons 'and todomatcher)
13491 (car todomatcher))
13492 orlist)
13493 (setq todomatcher nil))
13494 (setq todomatcher (if (> (length orlist) 1)
13495 (cons 'or orlist) (car orlist))))
13497 ;; Return the string and lisp forms of the matcher
13498 (setq matcher (if todomatcher
13499 (list 'and tagsmatcher todomatcher)
13500 tagsmatcher))
13501 (when todo-only
13502 (setq matcher (list 'and '(member todo org-not-done-keywords)
13503 matcher)))
13504 (cons match0 matcher)))
13506 (defun org-op-to-function (op &optional stringp)
13507 "Turn an operator into the appropriate function."
13508 (setq op
13509 (cond
13510 ((equal op "<" ) '(< string< org-time<))
13511 ((equal op ">" ) '(> org-string> org-time>))
13512 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13513 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13514 ((member op '("=" "==")) '(= string= org-time=))
13515 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13516 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13518 (defun org<> (a b) (not (= a b)))
13519 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13520 (defun org-string>= (a b) (not (string< a b)))
13521 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13522 (defun org-string<> (a b) (not (string= a b)))
13523 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13524 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13525 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13526 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13527 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13528 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13529 (defun org-2ft (s)
13530 "Convert S to a floating point time.
13531 If S is already a number, just return it. If it is a string, parse
13532 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13533 (cond
13534 ((numberp s) s)
13535 ((stringp s)
13536 (condition-case nil
13537 (float-time (apply 'encode-time (org-parse-time-string s)))
13538 (error 0.)))
13539 (t 0.)))
13541 (defun org-time-today ()
13542 "Time in seconds today at 0:00.
13543 Returns the float number of seconds since the beginning of the
13544 epoch to the beginning of today (00:00)."
13545 (float-time (apply 'encode-time
13546 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13548 (defun org-matcher-time (s)
13549 "Interpret a time comparison value."
13550 (save-match-data
13551 (cond
13552 ((string= s "<now>") (float-time))
13553 ((string= s "<today>") (org-time-today))
13554 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13555 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13556 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13557 (+ (org-time-today)
13558 (* (string-to-number (match-string 1 s))
13559 (cdr (assoc (match-string 2 s)
13560 '(("d" . 86400.0) ("w" . 604800.0)
13561 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13562 (t (org-2ft s)))))
13564 (defun org-match-any-p (re list)
13565 "Does re match any element of list?"
13566 (setq list (mapcar (lambda (x) (string-match re x)) list))
13567 (delq nil list))
13569 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13570 (defvar org-tags-overlay (make-overlay 1 1))
13571 (org-detach-overlay org-tags-overlay)
13573 (defun org-get-local-tags-at (&optional pos)
13574 "Get a list of tags defined in the current headline."
13575 (org-get-tags-at pos 'local))
13577 (defun org-get-local-tags ()
13578 "Get a list of tags defined in the current headline."
13579 (org-get-tags-at nil 'local))
13581 (defun org-get-tags-at (&optional pos local)
13582 "Get a list of all headline tags applicable at POS.
13583 POS defaults to point. If tags are inherited, the list contains
13584 the targets in the same sequence as the headlines appear, i.e.
13585 the tags of the current headline come last.
13586 When LOCAL is non-nil, only return tags from the current headline,
13587 ignore inherited ones."
13588 (interactive)
13589 (if (and org-trust-scanner-tags
13590 (or (not pos) (equal pos (point)))
13591 (not local))
13592 org-scanner-tags
13593 (let (tags ltags lastpos parent)
13594 (save-excursion
13595 (save-restriction
13596 (widen)
13597 (goto-char (or pos (point)))
13598 (save-match-data
13599 (catch 'done
13600 (condition-case nil
13601 (progn
13602 (org-back-to-heading t)
13603 (while (not (equal lastpos (point)))
13604 (setq lastpos (point))
13605 (when (looking-at
13606 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13607 (setq ltags (org-split-string
13608 (org-match-string-no-properties 1) ":"))
13609 (when parent
13610 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13611 (setq tags (append
13612 (if parent
13613 (org-remove-uninherited-tags ltags)
13614 ltags)
13615 tags)))
13616 (or org-use-tag-inheritance (throw 'done t))
13617 (if local (throw 'done t))
13618 (or (org-up-heading-safe) (error nil))
13619 (setq parent t)))
13620 (error nil)))))
13621 (if local
13622 tags
13623 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13625 (defun org-add-prop-inherited (s)
13626 (add-text-properties 0 (length s) '(inherited t) s)
13629 (defun org-toggle-tag (tag &optional onoff)
13630 "Toggle the tag TAG for the current line.
13631 If ONOFF is `on' or `off', don't toggle but set to this state."
13632 (let (res current)
13633 (save-excursion
13634 (org-back-to-heading t)
13635 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13636 (point-at-eol) t)
13637 (progn
13638 (setq current (match-string 1))
13639 (replace-match ""))
13640 (setq current ""))
13641 (setq current (nreverse (org-split-string current ":")))
13642 (cond
13643 ((eq onoff 'on)
13644 (setq res t)
13645 (or (member tag current) (push tag current)))
13646 ((eq onoff 'off)
13647 (or (not (member tag current)) (setq current (delete tag current))))
13648 (t (if (member tag current)
13649 (setq current (delete tag current))
13650 (setq res t)
13651 (push tag current))))
13652 (end-of-line 1)
13653 (if current
13654 (progn
13655 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13656 (org-set-tags nil t))
13657 (delete-horizontal-space))
13658 (run-hooks 'org-after-tags-change-hook))
13659 res))
13661 (defun org-align-tags-here (to-col)
13662 ;; Assumes that this is a headline
13663 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13664 (beginning-of-line 1)
13665 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13666 (< pos (match-beginning 2)))
13667 (progn
13668 (setq tags-l (- (match-end 2) (match-beginning 2)))
13669 (goto-char (match-beginning 1))
13670 (insert " ")
13671 (delete-region (point) (1+ (match-beginning 2)))
13672 (setq ncol (max (current-column)
13673 (1+ col)
13674 (if (> to-col 0)
13675 to-col
13676 (- (abs to-col) tags-l))))
13677 (setq p (point))
13678 (insert (make-string (- ncol (current-column)) ?\ ))
13679 (setq ncol (current-column))
13680 (when indent-tabs-mode (tabify p (point-at-eol)))
13681 (org-move-to-column (min ncol col) t))
13682 (goto-char pos))))
13684 (defun org-set-tags-command (&optional arg just-align)
13685 "Call the set-tags command for the current entry."
13686 (interactive "P")
13687 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13688 (org-set-tags arg just-align)
13689 (save-excursion
13690 (org-back-to-heading t)
13691 (org-set-tags arg just-align))))
13693 (defun org-set-tags-to (data)
13694 "Set the tags of the current entry to DATA, replacing the current tags.
13695 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13696 If DATA is nil or the empty string, any tags will be removed."
13697 (interactive "sTags: ")
13698 (setq data
13699 (cond
13700 ((eq data nil) "")
13701 ((equal data "") "")
13702 ((stringp data)
13703 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13704 ":"))
13705 ((listp data)
13706 (concat ":" (mapconcat 'identity data ":") ":"))))
13707 (when data
13708 (save-excursion
13709 (org-back-to-heading t)
13710 (when (looking-at org-complex-heading-regexp)
13711 (if (match-end 5)
13712 (progn
13713 (goto-char (match-beginning 5))
13714 (insert data)
13715 (delete-region (point) (point-at-eol))
13716 (org-set-tags nil 'align))
13717 (goto-char (point-at-eol))
13718 (insert " " data)
13719 (org-set-tags nil 'align)))
13720 (beginning-of-line 1)
13721 (if (looking-at ".*?\\([ \t]+\\)$")
13722 (delete-region (match-beginning 1) (match-end 1))))))
13724 (defun org-align-all-tags ()
13725 "Align the tags i all headings."
13726 (interactive)
13727 (save-excursion
13728 (or (ignore-errors (org-back-to-heading t))
13729 (outline-next-heading))
13730 (if (org-at-heading-p)
13731 (org-set-tags t)
13732 (message "No headings"))))
13734 (defvar org-indent-indentation-per-level)
13735 (defun org-set-tags (&optional arg just-align)
13736 "Set the tags for the current headline.
13737 With prefix ARG, realign all tags in headings in the current buffer."
13738 (interactive "P")
13739 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13740 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13741 'region-start-level 'region))
13742 org-loop-over-headlines-in-active-region)
13743 (org-map-entries
13744 ;; We don't use ARG and JUST-ALIGN here these args are not
13745 ;; useful when looping over headlines
13746 `(org-set-tags)
13747 org-loop-over-headlines-in-active-region
13748 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13749 (let* ((re org-outline-regexp-bol)
13750 (current (unless arg (org-get-tags-string)))
13751 (col (current-column))
13752 (org-setting-tags t)
13753 table current-tags inherited-tags ; computed below when needed
13754 tags p0 c0 c1 rpl di tc level)
13755 (if arg
13756 (save-excursion
13757 (goto-char (point-min))
13758 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13759 (while (re-search-forward re nil t)
13760 (org-set-tags nil t)
13761 (end-of-line 1)))
13762 (message "All tags realigned to column %d" org-tags-column))
13763 (if just-align
13764 (setq tags current)
13765 ;; Get a new set of tags from the user
13766 (save-excursion
13767 (setq table (append org-tag-persistent-alist
13768 (or org-tag-alist (org-get-buffer-tags))
13769 (and
13770 org-complete-tags-always-offer-all-agenda-tags
13771 (org-global-tags-completion-table
13772 (org-agenda-files))))
13773 org-last-tags-completion-table table
13774 current-tags (org-split-string current ":")
13775 inherited-tags (nreverse
13776 (nthcdr (length current-tags)
13777 (nreverse (org-get-tags-at))))
13778 tags
13779 (if (or (eq t org-use-fast-tag-selection)
13780 (and org-use-fast-tag-selection
13781 (delq nil (mapcar 'cdr table))))
13782 (org-fast-tag-selection
13783 current-tags inherited-tags table
13784 (if org-fast-tag-selection-include-todo
13785 org-todo-key-alist))
13786 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13787 (org-trim
13788 (org-icompleting-read "Tags: "
13789 'org-tags-completion-function
13790 nil nil current 'org-tags-history))))))
13791 (while (string-match "[-+&]+" tags)
13792 ;; No boolean logic, just a list
13793 (setq tags (replace-match ":" t t tags))))
13795 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13797 (if org-tags-sort-function
13798 (setq tags (mapconcat 'identity
13799 (sort (org-split-string
13800 tags (org-re "[^[:alnum:]_@#%]+"))
13801 org-tags-sort-function) ":")))
13803 (if (string-match "\\`[\t ]*\\'" tags)
13804 (setq tags "")
13805 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13806 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13808 ;; Insert new tags at the correct column
13809 (beginning-of-line 1)
13810 (setq level (or (and (looking-at org-outline-regexp)
13811 (- (match-end 0) (point) 1))
13813 (cond
13814 ((and (equal current "") (equal tags "")))
13815 ((re-search-forward
13816 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13817 (point-at-eol) t)
13818 (if (equal tags "")
13819 (setq rpl "")
13820 (goto-char (match-beginning 0))
13821 (setq c0 (current-column)
13822 ;; compute offset for the case of org-indent-mode active
13823 di (if org-indent-mode
13824 (* (1- org-indent-indentation-per-level) (1- level))
13826 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13827 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13828 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13829 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13830 (replace-match rpl t t)
13831 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13832 tags)
13833 (t (error "Tags alignment failed")))
13834 (org-move-to-column col)
13835 (unless just-align
13836 (run-hooks 'org-after-tags-change-hook))))))
13838 (defun org-change-tag-in-region (beg end tag off)
13839 "Add or remove TAG for each entry in the region.
13840 This works in the agenda, and also in an org-mode buffer."
13841 (interactive
13842 (list (region-beginning) (region-end)
13843 (let ((org-last-tags-completion-table
13844 (if (derived-mode-p 'org-mode)
13845 (org-get-buffer-tags)
13846 (org-global-tags-completion-table))))
13847 (org-icompleting-read
13848 "Tag: " 'org-tags-completion-function nil nil nil
13849 'org-tags-history))
13850 (progn
13851 (message "[s]et or [r]emove? ")
13852 (equal (read-char-exclusive) ?r))))
13853 (if (fboundp 'deactivate-mark) (deactivate-mark))
13854 (let ((agendap (equal major-mode 'org-agenda-mode))
13855 l1 l2 m buf pos newhead (cnt 0))
13856 (goto-char end)
13857 (setq l2 (1- (org-current-line)))
13858 (goto-char beg)
13859 (setq l1 (org-current-line))
13860 (loop for l from l1 to l2 do
13861 (org-goto-line l)
13862 (setq m (get-text-property (point) 'org-hd-marker))
13863 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13864 (and agendap m))
13865 (setq buf (if agendap (marker-buffer m) (current-buffer))
13866 pos (if agendap m (point)))
13867 (with-current-buffer buf
13868 (save-excursion
13869 (save-restriction
13870 (goto-char pos)
13871 (setq cnt (1+ cnt))
13872 (org-toggle-tag tag (if off 'off 'on))
13873 (setq newhead (org-get-heading)))))
13874 (and agendap (org-agenda-change-all-lines newhead m))))
13875 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13877 (defun org-tags-completion-function (string predicate &optional flag)
13878 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13879 (confirm (lambda (x) (stringp (car x)))))
13880 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13881 (setq s1 (match-string 1 string)
13882 s2 (match-string 2 string))
13883 (setq s1 "" s2 string))
13884 (cond
13885 ((eq flag nil)
13886 ;; try completion
13887 (setq rtn (try-completion s2 ctable confirm))
13888 (if (stringp rtn)
13889 (setq rtn
13890 (concat s1 s2 (substring rtn (length s2))
13891 (if (and org-add-colon-after-tag-completion
13892 (assoc rtn ctable))
13893 ":" ""))))
13894 rtn)
13895 ((eq flag t)
13896 ;; all-completions
13897 (all-completions s2 ctable confirm)
13899 ((eq flag 'lambda)
13900 ;; exact match?
13901 (assoc s2 ctable)))
13904 (defun org-fast-tag-insert (kwd tags face &optional end)
13905 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13906 (insert (format "%-12s" (concat kwd ":"))
13907 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13908 (or end "")))
13910 (defun org-fast-tag-show-exit (flag)
13911 (save-excursion
13912 (org-goto-line 3)
13913 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13914 (replace-match ""))
13915 (when flag
13916 (end-of-line 1)
13917 (org-move-to-column (- (window-width) 19) t)
13918 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13920 (defun org-set-current-tags-overlay (current prefix)
13921 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13922 (if (featurep 'xemacs)
13923 (org-overlay-display org-tags-overlay (concat prefix s)
13924 'secondary-selection)
13925 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13926 (org-overlay-display org-tags-overlay (concat prefix s)))))
13928 (defvar org-last-tag-selection-key nil)
13929 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13930 "Fast tag selection with single keys.
13931 CURRENT is the current list of tags in the headline, INHERITED is the
13932 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13933 possibly with grouping information. TODO-TABLE is a similar table with
13934 TODO keywords, should these have keys assigned to them.
13935 If the keys are nil, a-z are automatically assigned.
13936 Returns the new tags string, or nil to not change the current settings."
13937 (let* ((fulltable (append table todo-table))
13938 (maxlen (apply 'max (mapcar
13939 (lambda (x)
13940 (if (stringp (car x)) (string-width (car x)) 0))
13941 fulltable)))
13942 (buf (current-buffer))
13943 (expert (eq org-fast-tag-selection-single-key 'expert))
13944 (buffer-tags nil)
13945 (fwidth (+ maxlen 3 1 3))
13946 (ncol (/ (- (window-width) 4) fwidth))
13947 (i-face 'org-done)
13948 (c-face 'org-todo)
13949 tg cnt e c char c1 c2 ntable tbl rtn
13950 ov-start ov-end ov-prefix
13951 (exit-after-next org-fast-tag-selection-single-key)
13952 (done-keywords org-done-keywords)
13953 groups ingroup)
13954 (save-excursion
13955 (beginning-of-line 1)
13956 (if (looking-at
13957 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13958 (setq ov-start (match-beginning 1)
13959 ov-end (match-end 1)
13960 ov-prefix "")
13961 (setq ov-start (1- (point-at-eol))
13962 ov-end (1+ ov-start))
13963 (skip-chars-forward "^\n\r")
13964 (setq ov-prefix
13965 (concat
13966 (buffer-substring (1- (point)) (point))
13967 (if (> (current-column) org-tags-column)
13969 (make-string (- org-tags-column (current-column)) ?\ ))))))
13970 (move-overlay org-tags-overlay ov-start ov-end)
13971 (save-window-excursion
13972 (if expert
13973 (set-buffer (get-buffer-create " *Org tags*"))
13974 (delete-other-windows)
13975 (split-window-vertically)
13976 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13977 (erase-buffer)
13978 (org-set-local 'org-done-keywords done-keywords)
13979 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13980 (org-fast-tag-insert "Current" current c-face "\n\n")
13981 (org-fast-tag-show-exit exit-after-next)
13982 (org-set-current-tags-overlay current ov-prefix)
13983 (setq tbl fulltable char ?a cnt 0)
13984 (while (setq e (pop tbl))
13985 (cond
13986 ((equal (car e) :startgroup)
13987 (push '() groups) (setq ingroup t)
13988 (when (not (= cnt 0))
13989 (setq cnt 0)
13990 (insert "\n"))
13991 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13992 ((equal (car e) :endgroup)
13993 (setq ingroup nil cnt 0)
13994 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13995 ((equal e '(:newline))
13996 (when (not (= cnt 0))
13997 (setq cnt 0)
13998 (insert "\n")
13999 (setq e (car tbl))
14000 (while (equal (car tbl) '(:newline))
14001 (insert "\n")
14002 (setq tbl (cdr tbl)))))
14004 (setq tg (copy-sequence (car e)) c2 nil)
14005 (if (cdr e)
14006 (setq c (cdr e))
14007 ;; automatically assign a character.
14008 (setq c1 (string-to-char
14009 (downcase (substring
14010 tg (if (= (string-to-char tg) ?@) 1 0)))))
14011 (if (or (rassoc c1 ntable) (rassoc c1 table))
14012 (while (or (rassoc char ntable) (rassoc char table))
14013 (setq char (1+ char)))
14014 (setq c2 c1))
14015 (setq c (or c2 char)))
14016 (if ingroup (push tg (car groups)))
14017 (setq tg (org-add-props tg nil 'face
14018 (cond
14019 ((not (assoc tg table))
14020 (org-get-todo-face tg))
14021 ((member tg current) c-face)
14022 ((member tg inherited) i-face))))
14023 (if (and (= cnt 0) (not ingroup)) (insert " "))
14024 (insert "[" c "] " tg (make-string
14025 (- fwidth 4 (length tg)) ?\ ))
14026 (push (cons tg c) ntable)
14027 (when (= (setq cnt (1+ cnt)) ncol)
14028 (insert "\n")
14029 (if ingroup (insert " "))
14030 (setq cnt 0)))))
14031 (setq ntable (nreverse ntable))
14032 (insert "\n")
14033 (goto-char (point-min))
14034 (if (not expert) (org-fit-window-to-buffer))
14035 (setq rtn
14036 (catch 'exit
14037 (while t
14038 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14039 (if (not groups) "no " "")
14040 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14041 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14042 (setq org-last-tag-selection-key c)
14043 (cond
14044 ((= c ?\r) (throw 'exit t))
14045 ((= c ?!)
14046 (setq groups (not groups))
14047 (goto-char (point-min))
14048 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14049 ((= c ?\C-c)
14050 (if (not expert)
14051 (org-fast-tag-show-exit
14052 (setq exit-after-next (not exit-after-next)))
14053 (setq expert nil)
14054 (delete-other-windows)
14055 (set-window-buffer (split-window-vertically) " *Org tags*")
14056 (org-switch-to-buffer-other-window " *Org tags*")
14057 (org-fit-window-to-buffer)))
14058 ((or (= c ?\C-g)
14059 (and (= c ?q) (not (rassoc c ntable))))
14060 (org-detach-overlay org-tags-overlay)
14061 (setq quit-flag t))
14062 ((= c ?\ )
14063 (setq current nil)
14064 (if exit-after-next (setq exit-after-next 'now)))
14065 ((= c ?\t)
14066 (condition-case nil
14067 (setq tg (org-icompleting-read
14068 "Tag: "
14069 (or buffer-tags
14070 (with-current-buffer buf
14071 (org-get-buffer-tags)))))
14072 (quit (setq tg "")))
14073 (when (string-match "\\S-" tg)
14074 (add-to-list 'buffer-tags (list tg))
14075 (if (member tg current)
14076 (setq current (delete tg current))
14077 (push tg current)))
14078 (if exit-after-next (setq exit-after-next 'now)))
14079 ((setq e (rassoc c todo-table) tg (car e))
14080 (with-current-buffer buf
14081 (save-excursion (org-todo tg)))
14082 (if exit-after-next (setq exit-after-next 'now)))
14083 ((setq e (rassoc c ntable) tg (car e))
14084 (if (member tg current)
14085 (setq current (delete tg current))
14086 (loop for g in groups do
14087 (if (member tg g)
14088 (mapc (lambda (x)
14089 (setq current (delete x current)))
14090 g)))
14091 (push tg current))
14092 (if exit-after-next (setq exit-after-next 'now))))
14094 ;; Create a sorted list
14095 (setq current
14096 (sort current
14097 (lambda (a b)
14098 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14099 (if (eq exit-after-next 'now) (throw 'exit t))
14100 (goto-char (point-min))
14101 (beginning-of-line 2)
14102 (delete-region (point) (point-at-eol))
14103 (org-fast-tag-insert "Current" current c-face)
14104 (org-set-current-tags-overlay current ov-prefix)
14105 (while (re-search-forward
14106 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14107 (setq tg (match-string 1))
14108 (add-text-properties
14109 (match-beginning 1) (match-end 1)
14110 (list 'face
14111 (cond
14112 ((member tg current) c-face)
14113 ((member tg inherited) i-face)
14114 (t (get-text-property (match-beginning 1) 'face))))))
14115 (goto-char (point-min)))))
14116 (org-detach-overlay org-tags-overlay)
14117 (if rtn
14118 (mapconcat 'identity current ":")
14119 nil))))
14121 (defun org-get-tags-string ()
14122 "Get the TAGS string in the current headline."
14123 (unless (org-at-heading-p t)
14124 (error "Not on a heading"))
14125 (save-excursion
14126 (beginning-of-line 1)
14127 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14128 (org-match-string-no-properties 1)
14129 "")))
14131 (defun org-get-tags ()
14132 "Get the list of tags specified in the current headline."
14133 (org-split-string (org-get-tags-string) ":"))
14135 (defun org-get-buffer-tags ()
14136 "Get a table of all tags used in the buffer, for completion."
14137 (let (tags)
14138 (save-excursion
14139 (goto-char (point-min))
14140 (while (re-search-forward
14141 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14142 (when (equal (char-after (point-at-bol 0)) ?*)
14143 (mapc (lambda (x) (add-to-list 'tags x))
14144 (org-split-string (org-match-string-no-properties 1) ":")))))
14145 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14146 (mapcar 'list tags)))
14148 ;;;; The mapping API
14150 ;;;###autoload
14151 (defun org-map-entries (func &optional match scope &rest skip)
14152 "Call FUNC at each headline selected by MATCH in SCOPE.
14154 FUNC is a function or a lisp form. The function will be called without
14155 arguments, with the cursor positioned at the beginning of the headline.
14156 The return values of all calls to the function will be collected and
14157 returned as a list.
14159 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14160 does not need to preserve point. After evaluation, the cursor will be
14161 moved to the end of the line (presumably of the headline of the
14162 processed entry) and search continues from there. Under some
14163 circumstances, this may not produce the wanted results. For example,
14164 if you have removed (e.g. archived) the current (sub)tree it could
14165 mean that the next entry will be skipped entirely. In such cases, you
14166 can specify the position from where search should continue by making
14167 FUNC set the variable `org-map-continue-from' to the desired buffer
14168 position.
14170 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14171 Only headlines that are matched by this query will be considered during
14172 the iteration. When MATCH is nil or t, all headlines will be
14173 visited by the iteration.
14175 SCOPE determines the scope of this command. It can be any of:
14177 nil The current buffer, respecting the restriction if any
14178 tree The subtree started with the entry at point
14179 region The entries within the active region, if any
14180 region-start-level
14181 The entries within the active region, but only those at
14182 the same level than the first one.
14183 file The current buffer, without restriction
14184 file-with-archives
14185 The current buffer, and any archives associated with it
14186 agenda All agenda files
14187 agenda-with-archives
14188 All agenda files with any archive files associated with them
14189 \(file1 file2 ...)
14190 If this is a list, all files in the list will be scanned
14192 The remaining args are treated as settings for the skipping facilities of
14193 the scanner. The following items can be given here:
14195 archive skip trees with the archive tag.
14196 comment skip trees with the COMMENT keyword
14197 function or Emacs Lisp form:
14198 will be used as value for `org-agenda-skip-function', so whenever
14199 the function returns t, FUNC will not be called for that
14200 entry and search will continue from the point where the
14201 function leaves it.
14203 If your function needs to retrieve the tags including inherited tags
14204 at the *current* entry, you can use the value of the variable
14205 `org-scanner-tags' which will be much faster than getting the value
14206 with `org-get-tags-at'. If your function gets properties with
14207 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14208 to t around the call to `org-entry-properties' to get the same speedup.
14209 Note that if your function moves around to retrieve tags and properties at
14210 a *different* entry, you cannot use these techniques."
14211 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14212 (not (org-region-active-p)))
14213 (let* ((org-agenda-archives-mode nil) ; just to make sure
14214 (org-agenda-skip-archived-trees (memq 'archive skip))
14215 (org-agenda-skip-comment-trees (memq 'comment skip))
14216 (org-agenda-skip-function
14217 (car (org-delete-all '(comment archive) skip)))
14218 (org-tags-match-list-sublevels t)
14219 (start-level (eq scope 'region-start-level))
14220 matcher file res
14221 org-todo-keywords-for-agenda
14222 org-done-keywords-for-agenda
14223 org-todo-keyword-alist-for-agenda
14224 org-drawers-for-agenda
14225 org-tag-alist-for-agenda
14226 todo-only)
14228 (cond
14229 ((eq match t) (setq matcher t))
14230 ((eq match nil) (setq matcher t))
14231 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14233 (save-excursion
14234 (save-restriction
14235 (cond ((eq scope 'tree)
14236 (org-back-to-heading t)
14237 (org-narrow-to-subtree)
14238 (setq scope nil))
14239 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14240 (org-region-active-p))
14241 ;; If needed, set start-level to a string like "2"
14242 (when start-level
14243 (save-excursion
14244 (goto-char (region-beginning))
14245 (unless (org-at-heading-p) (outline-next-heading))
14246 (setq start-level (org-current-level))))
14247 (narrow-to-region (region-beginning)
14248 (save-excursion
14249 (goto-char (region-end))
14250 (unless (and (bolp) (org-at-heading-p))
14251 (outline-next-heading))
14252 (point)))
14253 (setq scope nil)))
14255 (if (not scope)
14256 (progn
14257 (org-agenda-prepare-buffers
14258 (list (buffer-file-name (current-buffer))))
14259 (setq res (org-scan-tags func matcher todo-only start-level)))
14260 ;; Get the right scope
14261 (cond
14262 ((and scope (listp scope) (symbolp (car scope)))
14263 (setq scope (eval scope)))
14264 ((eq scope 'agenda)
14265 (setq scope (org-agenda-files t)))
14266 ((eq scope 'agenda-with-archives)
14267 (setq scope (org-agenda-files t))
14268 (setq scope (org-add-archive-files scope)))
14269 ((eq scope 'file)
14270 (setq scope (list (buffer-file-name))))
14271 ((eq scope 'file-with-archives)
14272 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14273 (org-agenda-prepare-buffers scope)
14274 (while (setq file (pop scope))
14275 (with-current-buffer (org-find-base-buffer-visiting file)
14276 (save-excursion
14277 (save-restriction
14278 (widen)
14279 (goto-char (point-min))
14280 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14281 res)))
14283 ;;;; Properties
14285 ;;; Setting and retrieving properties
14287 (defconst org-special-properties
14288 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14289 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14290 "The special properties valid in Org-mode.
14292 These are properties that are not defined in the property drawer,
14293 but in some other way.")
14295 (defconst org-default-properties
14296 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14297 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14298 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14299 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14300 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14301 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14302 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14303 "Some properties that are used by Org-mode for various purposes.
14304 Being in this list makes sure that they are offered for completion.")
14306 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14307 "Regular expression matching the first line of a property drawer.")
14309 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14310 "Regular expression matching the last line of a property drawer.")
14312 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14313 "Regular expression matching the first line of a property drawer.")
14315 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14316 "Regular expression matching the first line of a property drawer.")
14318 (defconst org-property-drawer-re
14319 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14320 org-property-end-re "\\)\n?")
14321 "Matches an entire property drawer.")
14323 (defconst org-clock-drawer-re
14324 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14325 org-property-end-re "\\)\n?")
14326 "Matches an entire clock drawer.")
14328 (defsubst org-re-property (property)
14329 "Return a regexp matching a PROPERTY line.
14330 Match group 1 will be set to the value."
14331 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14333 (defsubst org-re-property-keyword (property)
14334 "Return a regexp matching a PROPERTY line, possibly with no
14335 value for the property."
14336 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14338 (defun org-property-action ()
14339 "Do an action on properties."
14340 (interactive)
14341 (let (c)
14342 (org-at-property-p)
14343 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14344 (setq c (read-char-exclusive))
14345 (cond
14346 ((equal c ?s)
14347 (call-interactively 'org-set-property))
14348 ((equal c ?d)
14349 (call-interactively 'org-delete-property))
14350 ((equal c ?D)
14351 (call-interactively 'org-delete-property-globally))
14352 ((equal c ?c)
14353 (call-interactively 'org-compute-property-at-point))
14354 (t (error "No such property action %c" c)))))
14356 (defun org-inc-effort ()
14357 "Increment the value of the effort property in the current entry."
14358 (interactive)
14359 (org-set-effort nil t))
14361 (defun org-set-effort (&optional value increment)
14362 "Set the effort property of the current entry.
14363 With numerical prefix arg, use the nth allowed value, 0 stands for the
14364 10th allowed value.
14366 When INCREMENT is non-nil, set the property to the next allowed value."
14367 (interactive "P")
14368 (if (equal value 0) (setq value 10))
14369 (let* ((completion-ignore-case t)
14370 (prop org-effort-property)
14371 (cur (org-entry-get nil prop))
14372 (allowed (org-property-get-allowed-values nil prop 'table))
14373 (existing (mapcar 'list (org-property-values prop)))
14375 (val (cond
14376 ((stringp value) value)
14377 ((and allowed (integerp value))
14378 (or (car (nth (1- value) allowed))
14379 (car (org-last allowed))))
14380 ((and allowed increment)
14381 (or (caadr (member (list cur) allowed))
14382 (error "Allowed effort values are not set")))
14383 (allowed
14384 (message "Select 1-9,0, [RET%s]: %s"
14385 (if cur (concat "=" cur) "")
14386 (mapconcat 'car allowed " "))
14387 (setq rpl (read-char-exclusive))
14388 (if (equal rpl ?\r)
14390 (setq rpl (- rpl ?0))
14391 (if (equal rpl 0) (setq rpl 10))
14392 (if (and (> rpl 0) (<= rpl (length allowed)))
14393 (car (nth (1- rpl) allowed))
14394 (org-completing-read "Effort: " allowed nil))))
14396 (let (org-completion-use-ido org-completion-use-iswitchb)
14397 (org-completing-read
14398 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14399 (concat "[" cur "]") "")
14400 ": ")
14401 existing nil nil "" nil cur))))))
14402 (unless (equal (org-entry-get nil prop) val)
14403 (org-entry-put nil prop val))
14404 (message "%s is now %s" prop val)))
14406 (defun org-at-property-p ()
14407 "Is cursor inside a property drawer?"
14408 (save-excursion
14409 (beginning-of-line 1)
14410 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14411 (save-match-data ;; Used by calling procedures
14412 (let ((p (point))
14413 (range (unless (org-before-first-heading-p)
14414 (org-get-property-block))))
14415 (and range (<= (car range) p) (< p (cdr range))))))))
14417 (defun org-get-property-block (&optional beg end force)
14418 "Return the (beg . end) range of the body of the property drawer.
14419 BEG and END are the beginning and end of the current subtree, or of
14420 the part before the first headline. If they are not given, they will
14421 be found. If the drawer does not exist and FORCE is non-nil, create
14422 the drawer."
14423 (catch 'exit
14424 (save-excursion
14425 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14426 (progn (org-back-to-heading t) (point))))
14427 (end (or end (and (not (outline-next-heading)) (point-max))
14428 (point))))
14429 (goto-char beg)
14430 (if (re-search-forward org-property-start-re end t)
14431 (setq beg (1+ (match-end 0)))
14432 (if force
14433 (save-excursion
14434 (org-insert-property-drawer)
14435 (setq end (progn (outline-next-heading) (point))))
14436 (throw 'exit nil))
14437 (goto-char beg)
14438 (if (re-search-forward org-property-start-re end t)
14439 (setq beg (1+ (match-end 0)))))
14440 (if (re-search-forward org-property-end-re end t)
14441 (setq end (match-beginning 0))
14442 (or force (throw 'exit nil))
14443 (goto-char beg)
14444 (setq end beg)
14445 (org-indent-line)
14446 (insert ":END:\n"))
14447 (cons beg end)))))
14449 (defun org-entry-properties (&optional pom which specific)
14450 "Get all properties of the entry at point-or-marker POM.
14451 This includes the TODO keyword, the tags, time strings for deadline,
14452 scheduled, and clocking, and any additional properties defined in the
14453 entry. The return value is an alist, keys may occur multiple times
14454 if the property key was used several times.
14455 POM may also be nil, in which case the current entry is used.
14456 If WHICH is nil or `all', get all properties. If WHICH is
14457 `special' or `standard', only get that subclass. If WHICH
14458 is a string only get exactly this property. SPECIFIC can be a string, the
14459 specific property we are interested in. Specifying it can speed
14460 things up because then unnecessary parsing is avoided."
14461 (setq which (or which 'all))
14462 (org-with-point-at pom
14463 (let ((clockstr (substring org-clock-string 0 -1))
14464 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14465 (case-fold-search nil)
14466 beg end range props sum-props key key1 value string clocksum clocksumt)
14467 (save-excursion
14468 (when (condition-case nil
14469 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14470 (error nil))
14471 (setq beg (point))
14472 (setq sum-props (get-text-property (point) 'org-summaries))
14473 (setq clocksum (get-text-property (point) :org-clock-minutes)
14474 clocksumt (get-text-property (point) :org-clock-minutes-today))
14475 (outline-next-heading)
14476 (setq end (point))
14477 (when (memq which '(all special))
14478 ;; Get the special properties, like TODO and tags
14479 (goto-char beg)
14480 (when (and (or (not specific) (string= specific "TODO"))
14481 (looking-at org-todo-line-regexp) (match-end 2))
14482 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14483 (when (and (or (not specific) (string= specific "PRIORITY"))
14484 (looking-at org-priority-regexp))
14485 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14486 (when (or (not specific) (string= specific "FILE"))
14487 (push (cons "FILE" buffer-file-name) props))
14488 (when (and (or (not specific) (string= specific "TAGS"))
14489 (setq value (org-get-tags-string))
14490 (string-match "\\S-" value))
14491 (push (cons "TAGS" value) props))
14492 (when (and (or (not specific) (string= specific "ALLTAGS"))
14493 (setq value (org-get-tags-at)))
14494 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14495 ":"))
14496 props))
14497 (when (or (not specific) (string= specific "BLOCKED"))
14498 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14499 (when (or (not specific)
14500 (member specific
14501 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14502 "TIMESTAMP" "TIMESTAMP_IA")))
14503 (catch 'match
14504 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14505 (setq key (if (match-end 1)
14506 (substring (org-match-string-no-properties 1)
14507 0 -1))
14508 string (if (equal key clockstr)
14509 (org-trim
14510 (buffer-substring-no-properties
14511 (match-beginning 3) (goto-char
14512 (point-at-eol))))
14513 (substring (org-match-string-no-properties 3)
14514 1 -1)))
14515 ;; Get the correct property name from the key. This is
14516 ;; necessary if the user has configured time keywords.
14517 (setq key1 (concat key ":"))
14518 (cond
14519 ((not key)
14520 (setq key
14521 (if (= (char-after (match-beginning 3)) ?\[)
14522 "TIMESTAMP_IA" "TIMESTAMP")))
14523 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14524 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14525 ((equal key1 org-closed-string) (setq key "CLOSED"))
14526 ((equal key1 org-clock-string) (setq key "CLOCK")))
14527 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14528 (progn
14529 (push (cons key string) props)
14530 ;; no need to search further if match is found
14531 (throw 'match t))
14532 (when (or (equal key "CLOCK") (not (assoc key props)))
14533 (push (cons key string) props)))))))
14535 (when (memq which '(all standard))
14536 ;; Get the standard properties, like :PROP: ...
14537 (setq range (org-get-property-block beg end))
14538 (when range
14539 (goto-char (car range))
14540 (while (re-search-forward
14541 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14542 (cdr range) t)
14543 (setq key (org-match-string-no-properties 1)
14544 value (org-trim (or (org-match-string-no-properties 2) "")))
14545 (unless (member key excluded)
14546 (push (cons key (or value "")) props)))))
14547 (if clocksum
14548 (push (cons "CLOCKSUM"
14549 (org-columns-number-to-string (/ (float clocksum) 60.)
14550 'add_times))
14551 props))
14552 (if clocksumt
14553 (push (cons "CLOCKSUM_T"
14554 (org-columns-number-to-string (/ (float clocksumt) 60.)
14555 'add_times))
14556 props))
14557 (unless (assoc "CATEGORY" props)
14558 (push (cons "CATEGORY" (org-get-category)) props))
14559 (append sum-props (nreverse props)))))))
14561 (defun org-entry-get (pom property &optional inherit literal-nil)
14562 "Get value of PROPERTY for entry or content at point-or-marker POM.
14563 If INHERIT is non-nil and the entry does not have the property,
14564 then also check higher levels of the hierarchy.
14565 If INHERIT is the symbol `selective', use inheritance only if the setting
14566 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14567 If the property is present but empty, the return value is the empty string.
14568 If the property is not present at all, nil is returned.
14570 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14571 do not interpret it as the list atom nil. This is used for inheritance
14572 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14573 (org-with-point-at pom
14574 (if (and inherit (if (eq inherit 'selective)
14575 (org-property-inherit-p property)
14577 (org-entry-get-with-inheritance property literal-nil)
14578 (if (member property org-special-properties)
14579 ;; We need a special property. Use `org-entry-properties' to
14580 ;; retrieve it, but specify the wanted property
14581 (cdr (assoc property (org-entry-properties nil 'special property)))
14582 (let* ((range (org-get-property-block))
14583 (props (list (or (assoc property org-file-properties)
14584 (assoc property org-global-properties)
14585 (assoc property org-global-properties-fixed))))
14586 (ap (lambda (key)
14587 (when (re-search-forward
14588 (org-re-property key) (cdr range) t)
14589 (setq props
14590 (org-update-property-plist
14592 (if (match-end 1)
14593 (org-match-string-no-properties 1) "")
14594 props)))))
14595 val)
14596 (when (and range (goto-char (car range)))
14597 (funcall ap property)
14598 (goto-char (car range))
14599 (while (funcall ap (concat property "+")))
14600 (setq val (cdr (assoc property props)))
14601 (when val (if literal-nil val (org-not-nil val)))))))))
14603 (defun org-property-or-variable-value (var &optional inherit)
14604 "Check if there is a property fixing the value of VAR.
14605 If yes, return this value. If not, return the current value of the variable."
14606 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14607 (if (and prop (stringp prop) (string-match "\\S-" prop))
14608 (read prop)
14609 (symbol-value var))))
14611 (defun org-entry-delete (pom property)
14612 "Delete the property PROPERTY from entry at point-or-marker POM."
14613 (org-with-point-at pom
14614 (if (member property org-special-properties)
14615 nil ; cannot delete these properties.
14616 (let ((range (org-get-property-block)))
14617 (if (and range
14618 (goto-char (car range))
14619 (re-search-forward
14620 (org-re-property property)
14621 (cdr range) t))
14622 (progn
14623 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14625 nil)))))
14627 ;; Multi-values properties are properties that contain multiple values
14628 ;; These values are assumed to be single words, separated by whitespace.
14629 (defun org-entry-add-to-multivalued-property (pom property value)
14630 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14631 (let* ((old (org-entry-get pom property))
14632 (values (and old (org-split-string old "[ \t]"))))
14633 (setq value (org-entry-protect-space value))
14634 (unless (member value values)
14635 (setq values (cons value values))
14636 (org-entry-put pom property
14637 (mapconcat 'identity values " ")))))
14639 (defun org-entry-remove-from-multivalued-property (pom property value)
14640 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14641 (let* ((old (org-entry-get pom property))
14642 (values (and old (org-split-string old "[ \t]"))))
14643 (setq value (org-entry-protect-space value))
14644 (when (member value values)
14645 (setq values (delete value values))
14646 (org-entry-put pom property
14647 (mapconcat 'identity values " ")))))
14649 (defun org-entry-member-in-multivalued-property (pom property value)
14650 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14651 (let* ((old (org-entry-get pom property))
14652 (values (and old (org-split-string old "[ \t]"))))
14653 (setq value (org-entry-protect-space value))
14654 (member value values)))
14656 (defun org-entry-get-multivalued-property (pom property)
14657 "Return a list of values in a multivalued property."
14658 (let* ((value (org-entry-get pom property))
14659 (values (and value (org-split-string value "[ \t]"))))
14660 (mapcar 'org-entry-restore-space values)))
14662 (defun org-entry-put-multivalued-property (pom property &rest values)
14663 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14664 VALUES should be a list of strings. Spaces will be protected."
14665 (org-entry-put pom property
14666 (mapconcat 'org-entry-protect-space values " "))
14667 (let* ((value (org-entry-get pom property))
14668 (values (and value (org-split-string value "[ \t]"))))
14669 (mapcar 'org-entry-restore-space values)))
14671 (defun org-entry-protect-space (s)
14672 "Protect spaces and newline in string S."
14673 (while (string-match " " s)
14674 (setq s (replace-match "%20" t t s)))
14675 (while (string-match "\n" s)
14676 (setq s (replace-match "%0A" t t s)))
14679 (defun org-entry-restore-space (s)
14680 "Restore spaces and newline in string S."
14681 (while (string-match "%20" s)
14682 (setq s (replace-match " " t t s)))
14683 (while (string-match "%0A" s)
14684 (setq s (replace-match "\n" t t s)))
14687 (defvar org-entry-property-inherited-from (make-marker)
14688 "Marker pointing to the entry from where a property was inherited.
14689 Each call to `org-entry-get-with-inheritance' will set this marker to the
14690 location of the entry where the inheritance search matched. If there was
14691 no match, the marker will point nowhere.
14692 Note that also `org-entry-get' calls this function, if the INHERIT flag
14693 is set.")
14695 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14696 "Get PROPERTY of entry or content at point, search higher levels if needed.
14697 The search will stop at the first ancestor which has the property defined.
14698 If the value found is \"nil\", return nil to show that the property
14699 should be considered as undefined (this is the meaning of nil here).
14700 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14701 (move-marker org-entry-property-inherited-from nil)
14702 (let (tmp)
14703 (save-excursion
14704 (save-restriction
14705 (widen)
14706 (catch 'ex
14707 (while t
14708 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14709 (or (ignore-errors (org-back-to-heading t))
14710 (goto-char (point-min)))
14711 (move-marker org-entry-property-inherited-from (point))
14712 (throw 'ex tmp))
14713 (or (ignore-errors (org-up-heading-safe))
14714 (throw 'ex nil))))))
14715 (setq tmp (or tmp
14716 (cdr (assoc property org-file-properties))
14717 (cdr (assoc property org-global-properties))
14718 (cdr (assoc property org-global-properties-fixed))))
14719 (if literal-nil tmp (org-not-nil tmp))))
14721 (defvar org-property-changed-functions nil
14722 "Hook called when the value of a property has changed.
14723 Each hook function should accept two arguments, the name of the property
14724 and the new value.")
14726 (defun org-entry-put (pom property value)
14727 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14728 (org-with-point-at pom
14729 (org-back-to-heading t)
14730 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14731 range)
14732 (cond
14733 ((equal property "TODO")
14734 (when (and (stringp value) (string-match "\\S-" value)
14735 (not (member value org-todo-keywords-1)))
14736 (error "\"%s\" is not a valid TODO state" value))
14737 (if (or (not value)
14738 (not (string-match "\\S-" value)))
14739 (setq value 'none))
14740 (org-todo value)
14741 (org-set-tags nil 'align))
14742 ((equal property "PRIORITY")
14743 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14744 (string-to-char value) ?\ ))
14745 (org-set-tags nil 'align))
14746 ((equal property "SCHEDULED")
14747 (if (re-search-forward org-scheduled-time-regexp end t)
14748 (cond
14749 ((eq value 'earlier) (org-timestamp-change -1 'day))
14750 ((eq value 'later) (org-timestamp-change 1 'day))
14751 (t (call-interactively 'org-schedule)))
14752 (call-interactively 'org-schedule)))
14753 ((equal property "DEADLINE")
14754 (if (re-search-forward org-deadline-time-regexp end t)
14755 (cond
14756 ((eq value 'earlier) (org-timestamp-change -1 'day))
14757 ((eq value 'later) (org-timestamp-change 1 'day))
14758 (t (call-interactively 'org-deadline)))
14759 (call-interactively 'org-deadline)))
14760 ((member property org-special-properties)
14761 (error "The %s property can not yet be set with `org-entry-put'"
14762 property))
14763 (t ; a non-special property
14764 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14765 (setq range (org-get-property-block beg end 'force))
14766 (goto-char (car range))
14767 (if (re-search-forward
14768 (org-re-property-keyword property) (cdr range) t)
14769 (progn
14770 (delete-region (match-beginning 0) (match-end 0))
14771 (goto-char (match-beginning 0)))
14772 (goto-char (cdr range))
14773 (insert "\n")
14774 (backward-char 1)
14775 (org-indent-line))
14776 (insert ":" property ":")
14777 (and value (insert " " value))
14778 (org-indent-line)))))
14779 (run-hook-with-args 'org-property-changed-functions property value)))
14781 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14782 "Get all property keys in the current buffer.
14783 With INCLUDE-SPECIALS, also list the special properties that reflect things
14784 like tags and TODO state.
14785 With INCLUDE-DEFAULTS, also include properties that has special meaning
14786 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14787 and others.
14788 With INCLUDE-COLUMNS, also include property names given in COLUMN
14789 formats in the current buffer."
14790 (let (rtn range cfmt s p)
14791 (save-excursion
14792 (save-restriction
14793 (widen)
14794 (goto-char (point-min))
14795 (while (re-search-forward org-property-start-re nil t)
14796 (setq range (org-get-property-block))
14797 (goto-char (car range))
14798 (while (re-search-forward
14799 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14800 (cdr range) t)
14801 (add-to-list 'rtn (org-match-string-no-properties 1)))
14802 (outline-next-heading))))
14804 (when include-specials
14805 (setq rtn (append org-special-properties rtn)))
14807 (when include-defaults
14808 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14809 (add-to-list 'rtn org-effort-property))
14811 (when include-columns
14812 (save-excursion
14813 (save-restriction
14814 (widen)
14815 (goto-char (point-min))
14816 (while (re-search-forward
14817 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14818 nil t)
14819 (setq cfmt (match-string 2) s 0)
14820 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14821 cfmt s)
14822 (setq s (match-end 0)
14823 p (match-string 1 cfmt))
14824 (unless (or (equal p "ITEM")
14825 (member p org-special-properties))
14826 (add-to-list 'rtn (match-string 1 cfmt))))))))
14828 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14830 (defun org-property-values (key)
14831 "Return a list of all values of property KEY in the current buffer."
14832 (save-excursion
14833 (save-restriction
14834 (widen)
14835 (goto-char (point-min))
14836 (let ((re (org-re-property key))
14837 values)
14838 (while (re-search-forward re nil t)
14839 (add-to-list 'values (org-trim (match-string 1))))
14840 (delete "" values)))))
14842 (defun org-insert-property-drawer ()
14843 "Insert a property drawer into the current entry."
14844 (org-back-to-heading t)
14845 (looking-at org-outline-regexp)
14846 (let ((indent (if org-adapt-indentation
14847 (- (match-end 0) (match-beginning 0))
14849 (beg (point))
14850 (re (concat "^[ \t]*" org-keyword-time-regexp))
14851 end hiddenp)
14852 (outline-next-heading)
14853 (setq end (point))
14854 (goto-char beg)
14855 (while (re-search-forward re end t))
14856 (setq hiddenp (outline-invisible-p))
14857 (end-of-line 1)
14858 (and (equal (char-after) ?\n) (forward-char 1))
14859 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14860 (if (member (match-string 1) '("CLOCK:" ":END:"))
14861 ;; just skip this line
14862 (beginning-of-line 2)
14863 ;; Drawer start, find the end
14864 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14865 (beginning-of-line 1)))
14866 (org-skip-over-state-notes)
14867 (skip-chars-backward " \t\n\r")
14868 (if (eq (char-before) ?*) (forward-char 1))
14869 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14870 (beginning-of-line 0)
14871 (org-indent-to-column indent)
14872 (beginning-of-line 2)
14873 (org-indent-to-column indent)
14874 (beginning-of-line 0)
14875 (if hiddenp
14876 (save-excursion
14877 (org-back-to-heading t)
14878 (hide-entry))
14879 (org-flag-drawer t))))
14881 (defun org-insert-drawer (&optional arg drawer)
14882 "Insert a drawer at point.
14884 Optional argument DRAWER, when non-nil, is a string representing
14885 drawer's name. Otherwise, the user is prompted for a name.
14887 If a region is active, insert the drawer around that region
14888 instead.
14890 Point is left between drawer's boundaries."
14891 (interactive "P")
14892 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14893 "LOGBOOK"))
14894 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14895 ;; internally by Org. They are meant to be inserted
14896 ;; automatically.
14897 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14898 ;; Remove system drawers from list. Note: For some reason,
14899 ;; `org-completing-read' ignores the predicate while
14900 ;; `completing-read' handles it fine.
14901 (drawer (if arg "PROPERTIES"
14902 (or drawer
14903 (completing-read
14904 "Drawer: " org-drawers
14905 (lambda (d) (not (member d system-drawers))))))))
14906 (cond
14907 ;; With C-u, fall back on `org-insert-property-drawer'
14908 (arg (org-insert-property-drawer))
14909 ;; With an active region, insert a drawer at point.
14910 ((not (org-region-active-p))
14911 (progn
14912 (unless (bolp) (insert "\n"))
14913 (insert (format ":%s:\n\n:END:\n" drawer))
14914 (forward-line -2)))
14915 ;; Otherwise, insert the drawer at point
14917 (let ((rbeg (region-beginning))
14918 (rend (copy-marker (region-end))))
14919 (unwind-protect
14920 (progn
14921 (goto-char rbeg)
14922 (beginning-of-line)
14923 (when (save-excursion
14924 (re-search-forward org-outline-regexp-bol rend t))
14925 (error "Drawers cannot contain headlines"))
14926 ;; Position point at the beginning of the first
14927 ;; non-blank line in region. Insert drawer's opening
14928 ;; there, then indent it.
14929 (org-skip-whitespace)
14930 (beginning-of-line)
14931 (insert ":" drawer ":\n")
14932 (forward-line -1)
14933 (indent-for-tab-command)
14934 ;; Move point to the beginning of the first blank line
14935 ;; after the last non-blank line in region. Insert
14936 ;; drawer's closing, then indent it.
14937 (goto-char rend)
14938 (skip-chars-backward " \r\t\n")
14939 (insert "\n:END:")
14940 (deactivate-mark t)
14941 (indent-for-tab-command)
14942 (unless (eolp) (insert "\n")))
14943 ;; Clear marker, whatever the outcome of insertion is.
14944 (set-marker rend nil)))))))
14946 (defvar org-property-set-functions-alist nil
14947 "Property set function alist.
14948 Each entry should have the following format:
14950 (PROPERTY . READ-FUNCTION)
14952 The read function will be called with the same argument as
14953 `org-completing-read'.")
14955 (defun org-set-property-function (property)
14956 "Get the function that should be used to set PROPERTY.
14957 This is computed according to `org-property-set-functions-alist'."
14958 (or (cdr (assoc property org-property-set-functions-alist))
14959 'org-completing-read))
14961 (defun org-read-property-value (property)
14962 "Read PROPERTY value from user."
14963 (let* ((completion-ignore-case t)
14964 (allowed (org-property-get-allowed-values nil property 'table))
14965 (cur (org-entry-get nil property))
14966 (prompt (concat property " value"
14967 (if (and cur (string-match "\\S-" cur))
14968 (concat " [" cur "]") "") ": "))
14969 (set-function (org-set-property-function property))
14970 (val (if allowed
14971 (funcall set-function prompt allowed nil
14972 (not (get-text-property 0 'org-unrestricted
14973 (caar allowed))))
14974 (let (org-completion-use-ido org-completion-use-iswitchb)
14975 (funcall set-function prompt
14976 (mapcar 'list (org-property-values property))
14977 nil nil "" nil cur)))))
14978 (if (equal val "")
14980 val)))
14982 (defvar org-last-set-property nil)
14983 (defun org-read-property-name ()
14984 "Read a property name."
14985 (let* ((completion-ignore-case t)
14986 (keys (org-buffer-property-keys nil t t))
14987 (default-prop (or (save-excursion
14988 (save-match-data
14989 (beginning-of-line)
14990 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14991 (null (string= (match-string 1) "END"))
14992 (match-string 1))))
14993 org-last-set-property))
14994 (property (org-icompleting-read
14995 (concat "Property"
14996 (if default-prop (concat " [" default-prop "]") "")
14997 ": ")
14998 (mapcar 'list keys)
14999 nil nil nil nil
15000 default-prop
15002 (if (member property keys)
15003 property
15004 (or (cdr (assoc (downcase property)
15005 (mapcar (lambda (x) (cons (downcase x) x))
15006 keys)))
15007 property))))
15009 (defun org-set-property (property value)
15010 "In the current entry, set PROPERTY to VALUE.
15011 When called interactively, this will prompt for a property name, offering
15012 completion on existing and default properties. And then it will prompt
15013 for a value, offering completion either on allowed values (via an inherited
15014 xxx_ALL property) or on existing values in other instances of this property
15015 in the current file."
15016 (interactive (list nil nil))
15017 (let* ((property (or property (org-read-property-name)))
15018 (value (or value (org-read-property-value property)))
15019 (fn (cdr (assoc property org-properties-postprocess-alist))))
15020 (setq org-last-set-property property)
15021 ;; Possibly postprocess the inserted value:
15022 (when fn (setq value (funcall fn value)))
15023 (unless (equal (org-entry-get nil property) value)
15024 (org-entry-put nil property value))))
15026 (defun org-delete-property (property)
15027 "In the current entry, delete PROPERTY."
15028 (interactive
15029 (let* ((completion-ignore-case t)
15030 (prop (org-icompleting-read "Property: "
15031 (org-entry-properties nil 'standard))))
15032 (list prop)))
15033 (message "Property %s %s" property
15034 (if (org-entry-delete nil property)
15035 "deleted"
15036 "was not present in the entry")))
15038 (defun org-delete-property-globally (property)
15039 "Remove PROPERTY globally, from all entries."
15040 (interactive
15041 (let* ((completion-ignore-case t)
15042 (prop (org-icompleting-read
15043 "Globally remove property: "
15044 (mapcar 'list (org-buffer-property-keys)))))
15045 (list prop)))
15046 (save-excursion
15047 (save-restriction
15048 (widen)
15049 (goto-char (point-min))
15050 (let ((cnt 0))
15051 (while (re-search-forward
15052 (org-re-property property)
15053 nil t)
15054 (setq cnt (1+ cnt))
15055 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15056 (message "Property \"%s\" removed from %d entries" property cnt)))))
15058 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15060 (defun org-compute-property-at-point ()
15061 "Compute the property at point.
15062 This looks for an enclosing column format, extracts the operator and
15063 then applies it to the property in the column format's scope."
15064 (interactive)
15065 (unless (org-at-property-p)
15066 (error "Not at a property"))
15067 (let ((prop (org-match-string-no-properties 2)))
15068 (org-columns-get-format-and-top-level)
15069 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15070 (error "No operator defined for property %s" prop))
15071 (org-columns-compute prop)))
15073 (defvar org-property-allowed-value-functions nil
15074 "Hook for functions supplying allowed values for a specific property.
15075 The functions must take a single argument, the name of the property, and
15076 return a flat list of allowed values. If \":ETC\" is one of
15077 the values, this means that these values are intended as defaults for
15078 completion, but that other values should be allowed too.
15079 The functions must return nil if they are not responsible for this
15080 property.")
15082 (defun org-property-get-allowed-values (pom property &optional table)
15083 "Get allowed values for the property PROPERTY.
15084 When TABLE is non-nil, return an alist that can directly be used for
15085 completion."
15086 (let (vals)
15087 (cond
15088 ((equal property "TODO")
15089 (setq vals (org-with-point-at pom
15090 (append org-todo-keywords-1 '("")))))
15091 ((equal property "PRIORITY")
15092 (let ((n org-lowest-priority))
15093 (while (>= n org-highest-priority)
15094 (push (char-to-string n) vals)
15095 (setq n (1- n)))))
15096 ((member property org-special-properties))
15097 ((setq vals (run-hook-with-args-until-success
15098 'org-property-allowed-value-functions property)))
15100 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15101 (when (and vals (string-match "\\S-" vals))
15102 (setq vals (car (read-from-string (concat "(" vals ")"))))
15103 (setq vals (mapcar (lambda (x)
15104 (cond ((stringp x) x)
15105 ((numberp x) (number-to-string x))
15106 ((symbolp x) (symbol-name x))
15107 (t "???")))
15108 vals)))))
15109 (when (member ":ETC" vals)
15110 (setq vals (remove ":ETC" vals))
15111 (org-add-props (car vals) '(org-unrestricted t)))
15112 (if table (mapcar 'list vals) vals)))
15114 (defun org-property-previous-allowed-value (&optional previous)
15115 "Switch to the next allowed value for this property."
15116 (interactive)
15117 (org-property-next-allowed-value t))
15119 (defun org-property-next-allowed-value (&optional previous)
15120 "Switch to the next allowed value for this property."
15121 (interactive)
15122 (unless (org-at-property-p)
15123 (error "Not at a property"))
15124 (let* ((key (match-string 2))
15125 (value (match-string 3))
15126 (allowed (or (org-property-get-allowed-values (point) key)
15127 (and (member value '("[ ]" "[-]" "[X]"))
15128 '("[ ]" "[X]"))))
15129 nval)
15130 (unless allowed
15131 (error "Allowed values for this property have not been defined"))
15132 (if previous (setq allowed (reverse allowed)))
15133 (if (member value allowed)
15134 (setq nval (car (cdr (member value allowed)))))
15135 (setq nval (or nval (car allowed)))
15136 (if (equal nval value)
15137 (error "Only one allowed value for this property"))
15138 (org-at-property-p)
15139 (replace-match (concat " :" key ": " nval) t t)
15140 (org-indent-line)
15141 (beginning-of-line 1)
15142 (skip-chars-forward " \t")
15143 (run-hook-with-args 'org-property-changed-functions key nval)))
15145 (defun org-find-olp (path &optional this-buffer)
15146 "Return a marker pointing to the entry at outline path OLP.
15147 If anything goes wrong, throw an error.
15148 You can wrap this call to catch the error like this:
15150 (condition-case msg
15151 (org-mobile-locate-entry (match-string 4))
15152 (error (nth 1 msg)))
15154 The return value will then be either a string with the error message,
15155 or a marker if everything is OK.
15157 If THIS-BUFFER is set, the outline path does not contain a file,
15158 only headings."
15159 (let* ((file (if this-buffer buffer-file-name (pop path)))
15160 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15161 (level 1)
15162 (lmin 1)
15163 (lmax 1)
15164 limit re end found pos heading cnt flevel)
15165 (unless buffer (error "File not found :%s" file))
15166 (with-current-buffer buffer
15167 (save-excursion
15168 (save-restriction
15169 (widen)
15170 (setq limit (point-max))
15171 (goto-char (point-min))
15172 (while (setq heading (pop path))
15173 (setq re (format org-complex-heading-regexp-format
15174 (regexp-quote heading)))
15175 (setq cnt 0 pos (point))
15176 (while (re-search-forward re end t)
15177 (setq level (- (match-end 1) (match-beginning 1)))
15178 (if (and (>= level lmin) (<= level lmax))
15179 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15180 (when (= cnt 0) (error "Heading not found on level %d: %s"
15181 lmax heading))
15182 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15183 lmax heading))
15184 (goto-char found)
15185 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15186 (setq end (save-excursion (org-end-of-subtree t t))))
15187 (when (org-at-heading-p)
15188 (move-marker (make-marker) (point))))))))
15190 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15191 "Find node HEADING in BUFFER.
15192 Return a marker to the heading if it was found, or nil if not.
15193 If POS-ONLY is set, return just the position instead of a marker.
15195 The heading text must match exact, but it may have a TODO keyword,
15196 a priority cookie and tags in the standard locations."
15197 (with-current-buffer (or buffer (current-buffer))
15198 (save-excursion
15199 (save-restriction
15200 (widen)
15201 (goto-char (point-min))
15202 (let (case-fold-search)
15203 (if (re-search-forward
15204 (format org-complex-heading-regexp-format
15205 (regexp-quote heading)) nil t)
15206 (if pos-only
15207 (match-beginning 0)
15208 (move-marker (make-marker) (match-beginning 0)))))))))
15210 (defun org-find-exact-heading-in-directory (heading &optional dir)
15211 "Find Org node headline HEADING in all .org files in directory DIR.
15212 When the target headline is found, return a marker to this location."
15213 (let ((files (directory-files (or dir default-directory)
15214 nil "\\`[^.#].*\\.org\\'"))
15215 file visiting m buffer)
15216 (catch 'found
15217 (while (setq file (pop files))
15218 (message "trying %s" file)
15219 (setq visiting (org-find-base-buffer-visiting file))
15220 (setq buffer (or visiting (find-file-noselect file)))
15221 (setq m (org-find-exact-headline-in-buffer
15222 heading buffer))
15223 (when (and (not m) (not visiting)) (kill-buffer buffer))
15224 (and m (throw 'found m))))))
15226 (defun org-find-entry-with-id (ident)
15227 "Locate the entry that contains the ID property with exact value IDENT.
15228 IDENT can be a string, a symbol or a number, this function will search for
15229 the string representation of it.
15230 Return the position where this entry starts, or nil if there is no such entry."
15231 (interactive "sID: ")
15232 (let ((id (cond
15233 ((stringp ident) ident)
15234 ((symbol-name ident) (symbol-name ident))
15235 ((numberp ident) (number-to-string ident))
15236 (t (error "IDENT %s must be a string, symbol or number" ident))))
15237 (case-fold-search nil))
15238 (save-excursion
15239 (save-restriction
15240 (widen)
15241 (goto-char (point-min))
15242 (when (re-search-forward
15243 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15244 nil t)
15245 (org-back-to-heading t)
15246 (point))))))
15248 ;;;; Timestamps
15250 (defvar org-last-changed-timestamp nil)
15251 (defvar org-last-inserted-timestamp nil
15252 "The last time stamp inserted with `org-insert-time-stamp'.")
15253 (defvar org-time-was-given) ; dynamically scoped parameter
15254 (defvar org-end-time-was-given) ; dynamically scoped parameter
15255 (defvar org-ts-what) ; dynamically scoped parameter
15257 (defun org-time-stamp (arg &optional inactive)
15258 "Prompt for a date/time and insert a time stamp.
15259 If the user specifies a time like HH:MM or if this command is
15260 called with at least one prefix argument, the time stamp contains
15261 the date and the time. Otherwise, only the date is be included.
15263 All parts of a date not specified by the user is filled in from
15264 the current date/time. So if you just press return without
15265 typing anything, the time stamp will represent the current
15266 date/time.
15268 If there is already a timestamp at the cursor, it will be
15269 modified.
15271 With two universal prefix arguments, insert an active timestamp
15272 with the current time without prompting the user."
15273 (interactive "P")
15274 (let* ((ts nil)
15275 (default-time
15276 ;; Default time is either today, or, when entering a range,
15277 ;; the range start.
15278 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15279 (save-excursion
15280 (re-search-backward
15281 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15282 (- (point) 20) t)))
15283 (apply 'encode-time (org-parse-time-string (match-string 1)))
15284 (current-time)))
15285 (default-input (and ts (org-get-compact-tod ts)))
15286 (repeater (save-excursion
15287 (save-match-data
15288 (beginning-of-line)
15289 (when (re-search-forward
15290 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15291 (save-excursion (progn (end-of-line) (point))) t)
15292 (match-string 0)))))
15293 org-time-was-given org-end-time-was-given time)
15294 (cond
15295 ((and (org-at-timestamp-p t)
15296 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15297 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15298 (insert "--")
15299 (setq time (let ((this-command this-command))
15300 (org-read-date arg 'totime nil nil
15301 default-time default-input inactive)))
15302 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15303 ((org-at-timestamp-p t)
15304 (setq time (let ((this-command this-command))
15305 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15306 (when (org-at-timestamp-p t) ; just to get the match data
15307 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15308 (replace-match "")
15309 (setq org-last-changed-timestamp
15310 (org-insert-time-stamp
15311 time (or org-time-was-given arg)
15312 inactive nil nil (list org-end-time-was-given)))
15313 (when repeater (goto-char (1- (point))) (insert " " repeater)
15314 (setq org-last-changed-timestamp
15315 (concat (substring org-last-inserted-timestamp 0 -1)
15316 " " repeater ">"))))
15317 (message "Timestamp updated"))
15318 ((equal arg '(16))
15319 (org-insert-time-stamp (current-time) t))
15321 (setq time (let ((this-command this-command))
15322 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15323 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15324 nil nil (list org-end-time-was-given))))))
15326 ;; FIXME: can we use this for something else, like computing time differences?
15327 (defun org-get-compact-tod (s)
15328 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15329 (let* ((t1 (match-string 1 s))
15330 (h1 (string-to-number (match-string 2 s)))
15331 (m1 (string-to-number (match-string 3 s)))
15332 (t2 (and (match-end 4) (match-string 5 s)))
15333 (h2 (and t2 (string-to-number (match-string 6 s))))
15334 (m2 (and t2 (string-to-number (match-string 7 s))))
15335 dh dm)
15336 (if (not t2)
15338 (setq dh (- h2 h1) dm (- m2 m1))
15339 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15340 (concat t1 "+" (number-to-string dh)
15341 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15343 (defun org-time-stamp-inactive (&optional arg)
15344 "Insert an inactive time stamp.
15345 An inactive time stamp is enclosed in square brackets instead of angle
15346 brackets. It is inactive in the sense that it does not trigger agenda entries,
15347 does not link to the calendar and cannot be changed with the S-cursor keys.
15348 So these are more for recording a certain time/date."
15349 (interactive "P")
15350 (org-time-stamp arg 'inactive))
15352 (defvar org-date-ovl (make-overlay 1 1))
15353 (overlay-put org-date-ovl 'face 'org-date-selected)
15354 (org-detach-overlay org-date-ovl)
15356 (defvar org-ans1) ; dynamically scoped parameter
15357 (defvar org-ans2) ; dynamically scoped parameter
15359 (defvar org-plain-time-of-day-regexp) ; defined below
15361 (defvar org-overriding-default-time nil) ; dynamically scoped
15362 (defvar org-read-date-overlay nil)
15363 (defvar org-dcst nil) ; dynamically scoped
15364 (defvar org-read-date-history nil)
15365 (defvar org-read-date-final-answer nil)
15366 (defvar org-read-date-analyze-futurep nil)
15367 (defvar org-read-date-analyze-forced-year nil)
15368 (defvar org-read-date-inactive)
15370 (defun org-read-date (&optional org-with-time to-time from-string prompt
15371 default-time default-input inactive)
15372 "Read a date, possibly a time, and make things smooth for the user.
15373 The prompt will suggest to enter an ISO date, but you can also enter anything
15374 which will at least partially be understood by `parse-time-string'.
15375 Unrecognized parts of the date will default to the current day, month, year,
15376 hour and minute. If this command is called to replace a timestamp at point,
15377 or to enter the second timestamp of a range, the default time is taken
15378 from the existing stamp. Furthermore, the command prefers the future,
15379 so if you are giving a date where the year is not given, and the day-month
15380 combination is already past in the current year, it will assume you
15381 mean next year. For details, see the manual. A few examples:
15383 3-2-5 --> 2003-02-05
15384 feb 15 --> currentyear-02-15
15385 2/15 --> currentyear-02-15
15386 sep 12 9 --> 2009-09-12
15387 12:45 --> today 12:45
15388 22 sept 0:34 --> currentyear-09-22 0:34
15389 12 --> currentyear-currentmonth-12
15390 Fri --> nearest Friday (today or later)
15391 etc.
15393 Furthermore you can specify a relative date by giving, as the *first* thing
15394 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15395 change in days weeks, months, years.
15396 With a single plus or minus, the date is relative to today. With a double
15397 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15398 +4d --> four days from today
15399 +4 --> same as above
15400 +2w --> two weeks from today
15401 ++5 --> five days from default date
15403 The function understands only English month and weekday abbreviations.
15405 While prompting, a calendar is popped up - you can also select the
15406 date with the mouse (button 1). The calendar shows a period of three
15407 months. To scroll it to other months, use the keys `>' and `<'.
15408 If you don't like the calendar, turn it off with
15409 \(setq org-read-date-popup-calendar nil)
15411 With optional argument TO-TIME, the date will immediately be converted
15412 to an internal time.
15413 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15414 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15415 still enter a time, and this function will inform the calling routine
15416 about this change. The calling routine may then choose to change the
15417 format used to insert the time stamp into the buffer to include the time.
15418 With optional argument FROM-STRING, read from this string instead from
15419 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15420 the time/date that is used for everything that is not specified by the
15421 user."
15422 (require 'parse-time)
15423 (let* ((org-time-stamp-rounding-minutes
15424 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15425 (org-dcst org-display-custom-times)
15426 (ct (org-current-time))
15427 (org-def (or org-overriding-default-time default-time ct))
15428 (org-defdecode (decode-time org-def))
15429 (dummy (progn
15430 (when (< (nth 2 org-defdecode) org-extend-today-until)
15431 (setcar (nthcdr 2 org-defdecode) -1)
15432 (setcar (nthcdr 1 org-defdecode) 59)
15433 (setq org-def (apply 'encode-time org-defdecode)
15434 org-defdecode (decode-time org-def)))))
15435 (calendar-frame-setup nil)
15436 (calendar-setup nil)
15437 (calendar-move-hook nil)
15438 (calendar-view-diary-initially-flag nil)
15439 (calendar-view-holidays-initially-flag nil)
15440 (timestr (format-time-string
15441 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15442 (prompt (concat (if prompt (concat prompt " ") "")
15443 (format "Date+time [%s]: " timestr)))
15444 ans (org-ans0 "") org-ans1 org-ans2 final)
15446 (cond
15447 (from-string (setq ans from-string))
15448 (org-read-date-popup-calendar
15449 (save-excursion
15450 (save-window-excursion
15451 (calendar)
15452 (org-eval-in-calendar '(setq cursor-type nil) t)
15453 (unwind-protect
15454 (progn
15455 (calendar-forward-day (- (time-to-days org-def)
15456 (calendar-absolute-from-gregorian
15457 (calendar-current-date))))
15458 (org-eval-in-calendar nil t)
15459 (let* ((old-map (current-local-map))
15460 (map (copy-keymap calendar-mode-map))
15461 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15462 (org-defkey map (kbd "RET") 'org-calendar-select)
15463 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15464 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15465 (org-defkey minibuffer-local-map [(meta shift left)]
15466 (lambda () (interactive)
15467 (org-eval-in-calendar '(calendar-backward-month 1))))
15468 (org-defkey minibuffer-local-map [(meta shift right)]
15469 (lambda () (interactive)
15470 (org-eval-in-calendar '(calendar-forward-month 1))))
15471 (org-defkey minibuffer-local-map [(meta shift up)]
15472 (lambda () (interactive)
15473 (org-eval-in-calendar '(calendar-backward-year 1))))
15474 (org-defkey minibuffer-local-map [(meta shift down)]
15475 (lambda () (interactive)
15476 (org-eval-in-calendar '(calendar-forward-year 1))))
15477 (org-defkey minibuffer-local-map [?\e (shift left)]
15478 (lambda () (interactive)
15479 (org-eval-in-calendar '(calendar-backward-month 1))))
15480 (org-defkey minibuffer-local-map [?\e (shift right)]
15481 (lambda () (interactive)
15482 (org-eval-in-calendar '(calendar-forward-month 1))))
15483 (org-defkey minibuffer-local-map [?\e (shift up)]
15484 (lambda () (interactive)
15485 (org-eval-in-calendar '(calendar-backward-year 1))))
15486 (org-defkey minibuffer-local-map [?\e (shift down)]
15487 (lambda () (interactive)
15488 (org-eval-in-calendar '(calendar-forward-year 1))))
15489 (org-defkey minibuffer-local-map [(shift up)]
15490 (lambda () (interactive)
15491 (org-eval-in-calendar '(calendar-backward-week 1))))
15492 (org-defkey minibuffer-local-map [(shift down)]
15493 (lambda () (interactive)
15494 (org-eval-in-calendar '(calendar-forward-week 1))))
15495 (org-defkey minibuffer-local-map [(shift left)]
15496 (lambda () (interactive)
15497 (org-eval-in-calendar '(calendar-backward-day 1))))
15498 (org-defkey minibuffer-local-map [(shift right)]
15499 (lambda () (interactive)
15500 (org-eval-in-calendar '(calendar-forward-day 1))))
15501 (org-defkey minibuffer-local-map ">"
15502 (lambda () (interactive)
15503 (org-eval-in-calendar '(scroll-calendar-left 1))))
15504 (org-defkey minibuffer-local-map "<"
15505 (lambda () (interactive)
15506 (org-eval-in-calendar '(scroll-calendar-right 1))))
15507 (org-defkey minibuffer-local-map "\C-v"
15508 (lambda () (interactive)
15509 (org-eval-in-calendar
15510 '(calendar-scroll-left-three-months 1))))
15511 (org-defkey minibuffer-local-map "\M-v"
15512 (lambda () (interactive)
15513 (org-eval-in-calendar
15514 '(calendar-scroll-right-three-months 1))))
15515 (run-hooks 'org-read-date-minibuffer-setup-hook)
15516 (unwind-protect
15517 (progn
15518 (use-local-map map)
15519 (setq org-read-date-inactive inactive)
15520 (add-hook 'post-command-hook 'org-read-date-display)
15521 (setq org-ans0 (read-string prompt default-input
15522 'org-read-date-history nil))
15523 ;; org-ans0: from prompt
15524 ;; org-ans1: from mouse click
15525 ;; org-ans2: from calendar motion
15526 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15527 (remove-hook 'post-command-hook 'org-read-date-display)
15528 (use-local-map old-map)
15529 (when org-read-date-overlay
15530 (delete-overlay org-read-date-overlay)
15531 (setq org-read-date-overlay nil)))))
15532 (bury-buffer "*Calendar*")))))
15534 (t ; Naked prompt only
15535 (unwind-protect
15536 (setq ans (read-string prompt default-input
15537 'org-read-date-history timestr))
15538 (when org-read-date-overlay
15539 (delete-overlay org-read-date-overlay)
15540 (setq org-read-date-overlay nil)))))
15542 (setq final (org-read-date-analyze ans org-def org-defdecode))
15544 (when org-read-date-analyze-forced-year
15545 (message "Year was forced into %s"
15546 (if org-read-date-force-compatible-dates
15547 "compatible range (1970-2037)"
15548 "range representable on this machine"))
15549 (ding))
15551 ;; One round trip to get rid of 34th of August and stuff like that....
15552 (setq final (decode-time (apply 'encode-time final)))
15554 (setq org-read-date-final-answer ans)
15556 (if to-time
15557 (apply 'encode-time final)
15558 (if (and (boundp 'org-time-was-given) org-time-was-given)
15559 (format "%04d-%02d-%02d %02d:%02d"
15560 (nth 5 final) (nth 4 final) (nth 3 final)
15561 (nth 2 final) (nth 1 final))
15562 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15564 (defvar org-def)
15565 (defvar org-defdecode)
15566 (defvar org-with-time)
15567 (defun org-read-date-display ()
15568 "Display the current date prompt interpretation in the minibuffer."
15569 (when org-read-date-display-live
15570 (when org-read-date-overlay
15571 (delete-overlay org-read-date-overlay))
15572 (when (minibufferp (current-buffer))
15573 (save-excursion
15574 (end-of-line 1)
15575 (while (not (equal (buffer-substring
15576 (max (point-min) (- (point) 4)) (point))
15577 " "))
15578 (insert " ")))
15579 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15580 " " (or org-ans1 org-ans2)))
15581 (org-end-time-was-given nil)
15582 (f (org-read-date-analyze ans org-def org-defdecode))
15583 (fmts (if org-dcst
15584 org-time-stamp-custom-formats
15585 org-time-stamp-formats))
15586 (fmt (if (or org-with-time
15587 (and (boundp 'org-time-was-given) org-time-was-given))
15588 (cdr fmts)
15589 (car fmts)))
15590 (txt (format-time-string fmt (apply 'encode-time f)))
15591 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15592 (txt (concat "=> " txt)))
15593 (when (and org-end-time-was-given
15594 (string-match org-plain-time-of-day-regexp txt))
15595 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15596 org-end-time-was-given
15597 (substring txt (match-end 0)))))
15598 (when org-read-date-analyze-futurep
15599 (setq txt (concat txt " (=>F)")))
15600 (setq org-read-date-overlay
15601 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15602 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15604 (defun org-read-date-analyze (ans org-def org-defdecode)
15605 "Analyze the combined answer of the date prompt."
15606 ;; FIXME: cleanup and comment
15607 (let ((nowdecode (decode-time (current-time)))
15608 delta deltan deltaw deltadef year month day
15609 hour minute second wday pm h2 m2 tl wday1
15610 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15611 (setq org-read-date-analyze-futurep nil
15612 org-read-date-analyze-forced-year nil)
15613 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15614 (setq ans "+0"))
15616 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15617 (setq ans (replace-match "" t t ans)
15618 deltan (car delta)
15619 deltaw (nth 1 delta)
15620 deltadef (nth 2 delta)))
15622 ;; Check if there is an iso week date in there. If yes, store the
15623 ;; info and postpone interpreting it until the rest of the parsing
15624 ;; is done.
15625 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15626 (setq iso-year (if (match-end 1)
15627 (org-small-year-to-year
15628 (string-to-number (match-string 1 ans))))
15629 iso-weekday (if (match-end 3)
15630 (string-to-number (match-string 3 ans)))
15631 iso-week (string-to-number (match-string 2 ans)))
15632 (setq ans (replace-match "" t t ans)))
15634 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15635 (when (string-match
15636 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15637 (setq year (if (match-end 2)
15638 (string-to-number (match-string 2 ans))
15639 (progn (setq kill-year t)
15640 (string-to-number (format-time-string "%Y"))))
15641 month (string-to-number (match-string 3 ans))
15642 day (string-to-number (match-string 4 ans)))
15643 (if (< year 100) (setq year (+ 2000 year)))
15644 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15645 t nil ans)))
15647 ;; Help matching dotted european dates
15648 (when (string-match
15649 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15650 (setq year (if (match-end 3)
15651 (string-to-number (match-string 3 ans))
15652 (progn (setq kill-year t)
15653 (string-to-number (format-time-string "%Y"))))
15654 day (string-to-number (match-string 1 ans))
15655 month (string-to-number (match-string 2 ans))
15656 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15657 t nil ans)))
15659 ;; Help matching american dates, like 5/30 or 5/30/7
15660 (when (string-match
15661 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15662 (setq year (if (match-end 4)
15663 (string-to-number (match-string 4 ans))
15664 (progn (setq kill-year t)
15665 (string-to-number (format-time-string "%Y"))))
15666 month (string-to-number (match-string 1 ans))
15667 day (string-to-number (match-string 2 ans)))
15668 (if (< year 100) (setq year (+ 2000 year)))
15669 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15670 t nil ans)))
15671 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15672 ;; If there is a time with am/pm, and *no* time without it, we convert
15673 ;; so that matching will be successful.
15674 (loop for i from 1 to 2 do ; twice, for end time as well
15675 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15676 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15677 (setq hour (string-to-number (match-string 1 ans))
15678 minute (if (match-end 3)
15679 (string-to-number (match-string 3 ans))
15681 pm (equal ?p
15682 (string-to-char (downcase (match-string 4 ans)))))
15683 (if (and (= hour 12) (not pm))
15684 (setq hour 0)
15685 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15686 (setq ans (replace-match (format "%02d:%02d" hour minute)
15687 t t ans))))
15689 ;; Check if a time range is given as a duration
15690 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15691 (setq hour (string-to-number (match-string 1 ans))
15692 h2 (+ hour (string-to-number (match-string 3 ans)))
15693 minute (string-to-number (match-string 2 ans))
15694 m2 (+ minute (if (match-end 5) (string-to-number
15695 (match-string 5 ans))0)))
15696 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15697 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15698 t t ans)))
15700 ;; Check if there is a time range
15701 (when (boundp 'org-end-time-was-given)
15702 (setq org-time-was-given nil)
15703 (when (and (string-match org-plain-time-of-day-regexp ans)
15704 (match-end 8))
15705 (setq org-end-time-was-given (match-string 8 ans))
15706 (setq ans (concat (substring ans 0 (match-beginning 7))
15707 (substring ans (match-end 7))))))
15709 (setq tl (parse-time-string ans)
15710 day (or (nth 3 tl) (nth 3 org-defdecode))
15711 month (or (nth 4 tl)
15712 (if (and org-read-date-prefer-future
15713 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15714 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15715 (nth 4 org-defdecode)))
15716 year (or (and (not kill-year) (nth 5 tl))
15717 (if (and org-read-date-prefer-future
15718 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15719 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15720 (nth 5 org-defdecode)))
15721 hour (or (nth 2 tl) (nth 2 org-defdecode))
15722 minute (or (nth 1 tl) (nth 1 org-defdecode))
15723 second (or (nth 0 tl) 0)
15724 wday (nth 6 tl))
15726 (when (and (eq org-read-date-prefer-future 'time)
15727 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15728 (equal day (nth 3 nowdecode))
15729 (equal month (nth 4 nowdecode))
15730 (equal year (nth 5 nowdecode))
15731 (nth 2 tl)
15732 (or (< (nth 2 tl) (nth 2 nowdecode))
15733 (and (= (nth 2 tl) (nth 2 nowdecode))
15734 (nth 1 tl)
15735 (< (nth 1 tl) (nth 1 nowdecode)))))
15736 (setq day (1+ day)
15737 futurep t))
15739 ;; Special date definitions below
15740 (cond
15741 (iso-week
15742 ;; There was an iso week
15743 (require 'cal-iso)
15744 (setq futurep nil)
15745 (setq year (or iso-year year)
15746 day (or iso-weekday wday 1)
15747 wday nil ; to make sure that the trigger below does not match
15748 iso-date (calendar-gregorian-from-absolute
15749 (calendar-absolute-from-iso
15750 (list iso-week day year))))
15751 ; FIXME: Should we also push ISO weeks into the future?
15752 ; (when (and org-read-date-prefer-future
15753 ; (not iso-year)
15754 ; (< (calendar-absolute-from-gregorian iso-date)
15755 ; (time-to-days (current-time))))
15756 ; (setq year (1+ year)
15757 ; iso-date (calendar-gregorian-from-absolute
15758 ; (calendar-absolute-from-iso
15759 ; (list iso-week day year)))))
15760 (setq month (car iso-date)
15761 year (nth 2 iso-date)
15762 day (nth 1 iso-date)))
15763 (deltan
15764 (setq futurep nil)
15765 (unless deltadef
15766 (let ((now (decode-time (current-time))))
15767 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15768 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15769 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15770 ((equal deltaw "m") (setq month (+ month deltan)))
15771 ((equal deltaw "y") (setq year (+ year deltan)))))
15772 ((and wday (not (nth 3 tl)))
15773 ;; Weekday was given, but no day, so pick that day in the week
15774 ;; on or after the derived date.
15775 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15776 (unless (equal wday wday1)
15777 (setq day (+ day (% (- wday wday1 -7) 7))))))
15778 (if (and (boundp 'org-time-was-given)
15779 (nth 2 tl))
15780 (setq org-time-was-given t))
15781 (if (< year 100) (setq year (+ 2000 year)))
15782 ;; Check of the date is representable
15783 (if org-read-date-force-compatible-dates
15784 (progn
15785 (if (< year 1970)
15786 (setq year 1970 org-read-date-analyze-forced-year t))
15787 (if (> year 2037)
15788 (setq year 2037 org-read-date-analyze-forced-year t)))
15789 (condition-case nil
15790 (ignore (encode-time second minute hour day month year))
15791 (error
15792 (setq year (nth 5 org-defdecode))
15793 (setq org-read-date-analyze-forced-year t))))
15794 (setq org-read-date-analyze-futurep futurep)
15795 (list second minute hour day month year)))
15797 (defvar parse-time-weekdays)
15798 (defun org-read-date-get-relative (s today default)
15799 "Check string S for special relative date string.
15800 TODAY and DEFAULT are internal times, for today and for a default.
15801 Return shift list (N what def-flag)
15802 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15803 N is the number of WHATs to shift.
15804 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15805 the DEFAULT date rather than TODAY."
15806 (require 'parse-time)
15807 (when (and
15808 (string-match
15809 (concat
15810 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15811 "\\([0-9]+\\)?"
15812 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15813 "\\([ \t]\\|$\\)") s)
15814 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15815 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15816 (string-to-char (substring (match-string 1 s) -1))
15817 ?+))
15818 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15819 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15820 (what (if (match-end 3) (match-string 3 s) "d"))
15821 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15822 (date (if rel default today))
15823 (wday (nth 6 (decode-time date)))
15824 delta)
15825 (if wday1
15826 (progn
15827 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15828 (if (= dir ?-) (setq delta (- delta 7)))
15829 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15830 (list delta "d" rel))
15831 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15833 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15834 "Turn a user-specified date into the internal representation.
15835 The internal representation needed by the calendar is (month day year).
15836 This is a wrapper to handle the brain-dead convention in calendar that
15837 user function argument order change dependent on argument order."
15838 (if (boundp 'calendar-date-style)
15839 (cond
15840 ((eq calendar-date-style 'american)
15841 (list arg1 arg2 arg3))
15842 ((eq calendar-date-style 'european)
15843 (list arg2 arg1 arg3))
15844 ((eq calendar-date-style 'iso)
15845 (list arg2 arg3 arg1)))
15846 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15847 (if (org-bound-and-true-p european-calendar-style)
15848 (list arg2 arg1 arg3)
15849 (list arg1 arg2 arg3)))))
15851 (defun org-eval-in-calendar (form &optional keepdate)
15852 "Eval FORM in the calendar window and return to current window.
15853 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15854 otherwise stick to the current value of `org-ans2'."
15855 (let ((sf (selected-frame))
15856 (sw (selected-window)))
15857 (select-window (get-buffer-window "*Calendar*" t))
15858 (eval form)
15859 (when (and (not keepdate) (calendar-cursor-to-date))
15860 (let* ((date (calendar-cursor-to-date))
15861 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15862 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15863 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15864 (select-window sw)
15865 (org-select-frame-set-input-focus sf)))
15867 (defun org-calendar-select ()
15868 "Return to `org-read-date' with the date currently selected.
15869 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15870 (interactive)
15871 (when (calendar-cursor-to-date)
15872 (let* ((date (calendar-cursor-to-date))
15873 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15874 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15875 (if (active-minibuffer-window) (exit-minibuffer))))
15877 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15878 "Insert a date stamp for the date given by the internal TIME.
15879 WITH-HM means use the stamp format that includes the time of the day.
15880 INACTIVE means use square brackets instead of angular ones, so that the
15881 stamp will not contribute to the agenda.
15882 PRE and POST are optional strings to be inserted before and after the
15883 stamp.
15884 The command returns the inserted time stamp."
15885 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15886 stamp)
15887 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15888 (insert-before-markers (or pre ""))
15889 (when (listp extra)
15890 (setq extra (car extra))
15891 (if (and (stringp extra)
15892 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15893 (setq extra (format "-%02d:%02d"
15894 (string-to-number (match-string 1 extra))
15895 (string-to-number (match-string 2 extra))))
15896 (setq extra nil)))
15897 (when extra
15898 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15899 (insert-before-markers (setq stamp (format-time-string fmt time)))
15900 (insert-before-markers (or post ""))
15901 (setq org-last-inserted-timestamp stamp)))
15903 (defun org-toggle-time-stamp-overlays ()
15904 "Toggle the use of custom time stamp formats."
15905 (interactive)
15906 (setq org-display-custom-times (not org-display-custom-times))
15907 (unless org-display-custom-times
15908 (let ((p (point-min)) (bmp (buffer-modified-p)))
15909 (while (setq p (next-single-property-change p 'display))
15910 (if (and (get-text-property p 'display)
15911 (eq (get-text-property p 'face) 'org-date))
15912 (remove-text-properties
15913 p (setq p (next-single-property-change p 'display))
15914 '(display t))))
15915 (set-buffer-modified-p bmp)))
15916 (if (featurep 'xemacs)
15917 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15918 (org-restart-font-lock)
15919 (setq org-table-may-need-update t)
15920 (if org-display-custom-times
15921 (message "Time stamps are overlaid with custom format")
15922 (message "Time stamp overlays removed")))
15924 (defun org-display-custom-time (beg end)
15925 "Overlay modified time stamp format over timestamp between BEG and END."
15926 (let* ((ts (buffer-substring beg end))
15927 t1 w1 with-hm tf time str w2 (off 0))
15928 (save-match-data
15929 (setq t1 (org-parse-time-string ts t))
15930 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15931 (setq off (- (match-end 0) (match-beginning 0)))))
15932 (setq end (- end off))
15933 (setq w1 (- end beg)
15934 with-hm (and (nth 1 t1) (nth 2 t1))
15935 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15936 time (org-fix-decoded-time t1)
15937 str (org-add-props
15938 (format-time-string
15939 (substring tf 1 -1) (apply 'encode-time time))
15940 nil 'mouse-face 'highlight)
15941 w2 (length str))
15942 (if (not (= w2 w1))
15943 (add-text-properties (1+ beg) (+ 2 beg)
15944 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15945 (if (featurep 'xemacs)
15946 (progn
15947 (put-text-property beg end 'invisible t)
15948 (put-text-property beg end 'end-glyph (make-glyph str)))
15949 (put-text-property beg end 'display str))))
15951 (defun org-translate-time (string)
15952 "Translate all timestamps in STRING to custom format.
15953 But do this only if the variable `org-display-custom-times' is set."
15954 (when org-display-custom-times
15955 (save-match-data
15956 (let* ((start 0)
15957 (re org-ts-regexp-both)
15958 t1 with-hm inactive tf time str beg end)
15959 (while (setq start (string-match re string start))
15960 (setq beg (match-beginning 0)
15961 end (match-end 0)
15962 t1 (save-match-data
15963 (org-parse-time-string (substring string beg end) t))
15964 with-hm (and (nth 1 t1) (nth 2 t1))
15965 inactive (equal (substring string beg (1+ beg)) "[")
15966 tf (funcall (if with-hm 'cdr 'car)
15967 org-time-stamp-custom-formats)
15968 time (org-fix-decoded-time t1)
15969 str (format-time-string
15970 (concat
15971 (if inactive "[" "<") (substring tf 1 -1)
15972 (if inactive "]" ">"))
15973 (apply 'encode-time time))
15974 string (replace-match str t t string)
15975 start (+ start (length str)))))))
15976 string)
15978 (defun org-fix-decoded-time (time)
15979 "Set 0 instead of nil for the first 6 elements of time.
15980 Don't touch the rest."
15981 (let ((n 0))
15982 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15984 (defun org-days-to-time (timestamp-string)
15985 "Difference between TIMESTAMP-STRING and now in days."
15986 (- (time-to-days (org-time-string-to-time timestamp-string))
15987 (time-to-days (current-time))))
15989 (defun org-deadline-close (timestamp-string &optional ndays)
15990 "Is the time in TIMESTAMP-STRING close to the current date?"
15991 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15992 (and (< (org-days-to-time timestamp-string) ndays)
15993 (not (org-entry-is-done-p))))
15995 (defun org-get-wdays (ts)
15996 "Get the deadline lead time appropriate for timestring TS."
15997 (cond
15998 ((<= org-deadline-warning-days 0)
15999 ;; 0 or negative, enforce this value no matter what
16000 (- org-deadline-warning-days))
16001 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16002 ;; lead time is specified.
16003 (floor (* (string-to-number (match-string 1 ts))
16004 (cdr (assoc (match-string 2 ts)
16005 '(("d" . 1) ("w" . 7)
16006 ("m" . 30.4) ("y" . 365.25)))))))
16007 ;; go for the default.
16008 (t org-deadline-warning-days)))
16010 (defun org-calendar-select-mouse (ev)
16011 "Return to `org-read-date' with the date currently selected.
16012 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16013 (interactive "e")
16014 (mouse-set-point ev)
16015 (when (calendar-cursor-to-date)
16016 (let* ((date (calendar-cursor-to-date))
16017 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16018 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16019 (if (active-minibuffer-window) (exit-minibuffer))))
16021 (defun org-check-deadlines (ndays)
16022 "Check if there are any deadlines due or past due.
16023 A deadline is considered due if it happens within `org-deadline-warning-days'
16024 days from today's date. If the deadline appears in an entry marked DONE,
16025 it is not shown. The prefix arg NDAYS can be used to test that many
16026 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16027 (interactive "P")
16028 (let* ((org-warn-days
16029 (cond
16030 ((equal ndays '(4)) 100000)
16031 (ndays (prefix-numeric-value ndays))
16032 (t (abs org-deadline-warning-days))))
16033 (case-fold-search nil)
16034 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16035 (callback
16036 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16038 (message "%d deadlines past-due or due within %d days"
16039 (org-occur regexp nil callback)
16040 org-warn-days)))
16042 (defsubst org-re-timestamp (type)
16043 "Return a regexp for timestamp TYPE.
16044 Allowed values for TYPE are:
16046 all: all timestamps
16047 active: only active timestamps (<...>)
16048 inactive: only inactive timestamps ([...])
16049 scheduled: only scheduled timestamps
16050 deadline: only deadline timestamps
16052 When TYPE is nil, fall back on returning a regexp that matches
16053 both scheduled and deadline timestamps."
16054 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16055 ((eq type 'active) org-ts-regexp)
16056 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16057 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16058 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16059 ((eq type 'scheduled-or-deadline)
16060 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16062 (defun org-check-before-date (date)
16063 "Check if there are deadlines or scheduled entries before DATE."
16064 (interactive (list (org-read-date)))
16065 (let ((case-fold-search nil)
16066 (regexp (org-re-timestamp org-ts-type))
16067 (callback
16068 (lambda () (time-less-p
16069 (org-time-string-to-time (match-string 1))
16070 (org-time-string-to-time date)))))
16071 (message "%d entries before %s"
16072 (org-occur regexp nil callback) date)))
16074 (defun org-check-after-date (date)
16075 "Check if there are deadlines or scheduled entries after DATE."
16076 (interactive (list (org-read-date)))
16077 (let ((case-fold-search nil)
16078 (regexp (org-re-timestamp org-ts-type))
16079 (callback
16080 (lambda () (not
16081 (time-less-p
16082 (org-time-string-to-time (match-string 1))
16083 (org-time-string-to-time date))))))
16084 (message "%d entries after %s"
16085 (org-occur regexp nil callback) date)))
16087 (defun org-check-dates-range (start-date end-date)
16088 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16089 (interactive (list (org-read-date nil nil nil "Range starts")
16090 (org-read-date nil nil nil "Range end")))
16091 (let ((case-fold-search nil)
16092 (regexp (org-re-timestamp org-ts-type))
16093 (callback
16094 (lambda ()
16095 (let ((match (match-string 1)))
16096 (and
16097 (not (time-less-p
16098 (org-time-string-to-time match)
16099 (org-time-string-to-time start-date)))
16100 (time-less-p
16101 (org-time-string-to-time match)
16102 (org-time-string-to-time end-date)))))))
16103 (message "%d entries between %s and %s"
16104 (org-occur regexp nil callback) start-date end-date)))
16106 (defun org-evaluate-time-range (&optional to-buffer)
16107 "Evaluate a time range by computing the difference between start and end.
16108 Normally the result is just printed in the echo area, but with prefix arg
16109 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16110 If the time range is actually in a table, the result is inserted into the
16111 next column.
16112 For time difference computation, a year is assumed to be exactly 365
16113 days in order to avoid rounding problems."
16114 (interactive "P")
16116 (org-clock-update-time-maybe)
16117 (save-excursion
16118 (unless (org-at-date-range-p t)
16119 (goto-char (point-at-bol))
16120 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16121 (if (not (org-at-date-range-p t))
16122 (error "Not at a time-stamp range, and none found in current line")))
16123 (let* ((ts1 (match-string 1))
16124 (ts2 (match-string 2))
16125 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16126 (match-end (match-end 0))
16127 (time1 (org-time-string-to-time ts1))
16128 (time2 (org-time-string-to-time ts2))
16129 (t1 (org-float-time time1))
16130 (t2 (org-float-time time2))
16131 (diff (abs (- t2 t1)))
16132 (negative (< (- t2 t1) 0))
16133 ;; (ys (floor (* 365 24 60 60)))
16134 (ds (* 24 60 60))
16135 (hs (* 60 60))
16136 (fy "%dy %dd %02d:%02d")
16137 (fy1 "%dy %dd")
16138 (fd "%dd %02d:%02d")
16139 (fd1 "%dd")
16140 (fh "%02d:%02d")
16141 y d h m align)
16142 (if havetime
16143 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16145 d (floor (/ diff ds)) diff (mod diff ds)
16146 h (floor (/ diff hs)) diff (mod diff hs)
16147 m (floor (/ diff 60)))
16148 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16150 d (floor (+ (/ diff ds) 0.5))
16151 h 0 m 0))
16152 (if (not to-buffer)
16153 (message "%s" (org-make-tdiff-string y d h m))
16154 (if (org-at-table-p)
16155 (progn
16156 (goto-char match-end)
16157 (setq align t)
16158 (and (looking-at " *|") (goto-char (match-end 0))))
16159 (goto-char match-end))
16160 (if (looking-at
16161 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16162 (replace-match ""))
16163 (if negative (insert " -"))
16164 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16165 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16166 (insert " " (format fh h m))))
16167 (if align (org-table-align))
16168 (message "Time difference inserted")))))
16170 (defun org-make-tdiff-string (y d h m)
16171 (let ((fmt "")
16172 (l nil))
16173 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16174 l (push y l)))
16175 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16176 l (push d l)))
16177 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16178 l (push h l)))
16179 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16180 l (push m l)))
16181 (apply 'format fmt (nreverse l))))
16183 (defun org-time-string-to-time (s &optional buffer pos)
16184 "Convert a timestamp string into internal time."
16185 (condition-case errdata
16186 (apply 'encode-time (org-parse-time-string s))
16187 (error (error "Bad timestamp `%s'%s\nError was: %s"
16188 s (if (not (and buffer pos))
16190 (format " at %d in buffer `%s'" pos buffer))
16191 (cdr errdata)))))
16193 (defun org-time-string-to-seconds (s)
16194 "Convert a timestamp string to a number of seconds."
16195 (org-float-time (org-time-string-to-time s)))
16197 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16198 "Convert a time stamp to an absolute day number.
16199 If there is a specifier for a cyclic time stamp, get the closest date to
16200 DAYNR.
16201 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16202 The variable date is bound by the calendar when this is called."
16203 (cond
16204 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16205 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16206 daynr
16207 (+ daynr 1000)))
16208 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16209 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16210 (time-to-days (current-time))) (match-string 0 s)
16211 prefer show-all))
16212 (t (time-to-days
16213 (condition-case errdata
16214 (apply 'encode-time (org-parse-time-string s))
16215 (error (error "Bad timestamp `%s'%s\nError was: %s"
16216 s (if (not (and buffer pos))
16218 (format " at %d in buffer `%s'" pos buffer))
16219 (cdr errdata))))))))
16221 (defun org-days-to-iso-week (days)
16222 "Return the iso week number."
16223 (require 'cal-iso)
16224 (car (calendar-iso-from-absolute days)))
16226 (defun org-small-year-to-year (year)
16227 "Convert 2-digit years into 4-digit years.
16228 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16229 The year 2000 cannot be abbreviated. Any year larger than 99
16230 is returned unchanged."
16231 (if (< year 38)
16232 (setq year (+ 2000 year))
16233 (if (< year 100)
16234 (setq year (+ 1900 year))))
16235 year)
16237 (defun org-time-from-absolute (d)
16238 "Return the time corresponding to date D.
16239 D may be an absolute day number, or a calendar-type list (month day year)."
16240 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16241 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16243 (defun org-calendar-holiday ()
16244 "List of holidays, for Diary display in Org-mode."
16245 (require 'holidays)
16246 (let ((hl (funcall
16247 (if (fboundp 'calendar-check-holidays)
16248 'calendar-check-holidays 'check-calendar-holidays) date)))
16249 (if hl (mapconcat 'identity hl "; "))))
16251 (defun org-diary-sexp-entry (sexp entry date)
16252 "Process a SEXP diary ENTRY for DATE."
16253 (require 'diary-lib)
16254 (let ((result (if calendar-debug-sexp
16255 (let ((stack-trace-on-error t))
16256 (eval (car (read-from-string sexp))))
16257 (condition-case nil
16258 (eval (car (read-from-string sexp)))
16259 (error
16260 (beep)
16261 (message "Bad sexp at line %d in %s: %s"
16262 (org-current-line)
16263 (buffer-file-name) sexp)
16264 (sleep-for 2))))))
16265 (cond ((stringp result) (split-string result "; "))
16266 ((and (consp result)
16267 (not (consp (cdr result)))
16268 (stringp (cdr result))) (cdr result))
16269 ((and (consp result)
16270 (stringp (car result))) result)
16271 (result entry))))
16273 (defun org-diary-to-ical-string (frombuf)
16274 "Get iCalendar entries from diary entries in buffer FROMBUF.
16275 This uses the icalendar.el library."
16276 (let* ((tmpdir (if (featurep 'xemacs)
16277 (temp-directory)
16278 temporary-file-directory))
16279 (tmpfile (make-temp-name
16280 (expand-file-name "orgics" tmpdir)))
16281 buf rtn b e)
16282 (with-current-buffer frombuf
16283 (icalendar-export-region (point-min) (point-max) tmpfile)
16284 (setq buf (find-buffer-visiting tmpfile))
16285 (set-buffer buf)
16286 (goto-char (point-min))
16287 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16288 (setq b (match-beginning 0)))
16289 (goto-char (point-max))
16290 (if (re-search-backward "^END:VEVENT" nil t)
16291 (setq e (match-end 0)))
16292 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16293 (kill-buffer buf)
16294 (delete-file tmpfile)
16295 rtn))
16297 (defun org-closest-date (start current change prefer show-all)
16298 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16299 When PREFER is `past', return a date that is either CURRENT or past.
16300 When PREFER is `future', return a date that is either CURRENT or future.
16301 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16302 ;; Make the proper lists from the dates
16303 (catch 'exit
16304 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16305 dn dw sday cday n1 n2 n0
16306 d m y y1 y2 date1 date2 nmonths nm ny m2)
16308 (setq start (org-date-to-gregorian start)
16309 current (org-date-to-gregorian
16310 (if show-all
16311 current
16312 (time-to-days (current-time))))
16313 sday (calendar-absolute-from-gregorian start)
16314 cday (calendar-absolute-from-gregorian current))
16316 (if (<= cday sday) (throw 'exit sday))
16318 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16319 (setq dn (string-to-number (match-string 1 change))
16320 dw (cdr (assoc (match-string 2 change) a1)))
16321 (error "Invalid change specifier: %s" change))
16322 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16323 (cond
16324 ((eq dw 'day)
16325 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16326 n2 (+ n1 dn)))
16327 ((eq dw 'year)
16328 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16329 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16330 (setq date1 (list m d y1)
16331 n1 (calendar-absolute-from-gregorian date1)
16332 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16333 n2 (calendar-absolute-from-gregorian date2)))
16334 ((eq dw 'month)
16335 ;; approx number of month between the two dates
16336 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16337 ;; How often does dn fit in there?
16338 (setq d (nth 1 start) m (car start) y (nth 2 start)
16339 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16340 m (+ m nm)
16341 ny (floor (/ m 12))
16342 y (+ y ny)
16343 m (- m (* ny 12)))
16344 (while (> m 12) (setq m (- m 12) y (1+ y)))
16345 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16346 (setq m2 (+ m dn) y2 y)
16347 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16348 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16349 (while (<= n2 cday)
16350 (setq n1 n2 m m2 y y2)
16351 (setq m2 (+ m dn) y2 y)
16352 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16353 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16354 ;; Make sure n1 is the earlier date
16355 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16356 (if show-all
16357 (cond
16358 ((eq prefer 'past) (if (= cday n2) n2 n1))
16359 ((eq prefer 'future) (if (= cday n1) n1 n2))
16360 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16361 (cond
16362 ((eq prefer 'past) (if (= cday n2) n2 n1))
16363 ((eq prefer 'future) (if (= cday n1) n1 n2))
16364 (t (if (= cday n1) n1 n2)))))))
16366 (defun org-date-to-gregorian (date)
16367 "Turn any specification of DATE into a Gregorian date for the calendar."
16368 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16369 ((and (listp date) (= (length date) 3)) date)
16370 ((stringp date)
16371 (setq date (org-parse-time-string date))
16372 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16373 ((listp date)
16374 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16376 (defun org-parse-time-string (s &optional nodefault)
16377 "Parse the standard Org-mode time string.
16378 This should be a lot faster than the normal `parse-time-string'.
16379 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16380 hour and minute fields will be nil if not given."
16381 (if (string-match org-ts-regexp0 s)
16382 (list 0
16383 (if (or (match-beginning 8) (not nodefault))
16384 (string-to-number (or (match-string 8 s) "0")))
16385 (if (or (match-beginning 7) (not nodefault))
16386 (string-to-number (or (match-string 7 s) "0")))
16387 (string-to-number (match-string 4 s))
16388 (string-to-number (match-string 3 s))
16389 (string-to-number (match-string 2 s))
16390 nil nil nil)
16391 (error "Not a standard Org-mode time string: %s" s)))
16393 (defun org-timestamp-up (&optional arg)
16394 "Increase the date item at the cursor by one.
16395 If the cursor is on the year, change the year. If it is on the month,
16396 the day or the time, change that.
16397 With prefix ARG, change by that many units."
16398 (interactive "p")
16399 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16401 (defun org-timestamp-down (&optional arg)
16402 "Decrease the date item at the cursor by one.
16403 If the cursor is on the year, change the year. If it is on the month,
16404 the day or the time, change that.
16405 With prefix ARG, change by that many units."
16406 (interactive "p")
16407 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16409 (defun org-timestamp-up-day (&optional arg)
16410 "Increase the date in the time stamp by one day.
16411 With prefix ARG, change that many days."
16412 (interactive "p")
16413 (if (and (not (org-at-timestamp-p t))
16414 (org-at-heading-p))
16415 (org-todo 'up)
16416 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16418 (defun org-timestamp-down-day (&optional arg)
16419 "Decrease the date in the time stamp by one day.
16420 With prefix ARG, change that many days."
16421 (interactive "p")
16422 (if (and (not (org-at-timestamp-p t))
16423 (org-at-heading-p))
16424 (org-todo 'down)
16425 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16427 (defun org-at-timestamp-p (&optional inactive-ok)
16428 "Determine if the cursor is in or at a timestamp."
16429 (interactive)
16430 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16431 (pos (point))
16432 (ans (or (looking-at tsr)
16433 (save-excursion
16434 (skip-chars-backward "^[<\n\r\t")
16435 (if (> (point) (point-min)) (backward-char 1))
16436 (and (looking-at tsr)
16437 (> (- (match-end 0) pos) -1))))))
16438 (and ans
16439 (boundp 'org-ts-what)
16440 (setq org-ts-what
16441 (cond
16442 ((= pos (match-beginning 0)) 'bracket)
16443 ;; Point is considered to be "on the bracket" whether
16444 ;; it's really on it or right after it.
16445 ((= pos (1- (match-end 0))) 'bracket)
16446 ((= pos (match-end 0)) 'after)
16447 ((org-pos-in-match-range pos 2) 'year)
16448 ((org-pos-in-match-range pos 3) 'month)
16449 ((org-pos-in-match-range pos 7) 'hour)
16450 ((org-pos-in-match-range pos 8) 'minute)
16451 ((or (org-pos-in-match-range pos 4)
16452 (org-pos-in-match-range pos 5)) 'day)
16453 ((and (> pos (or (match-end 8) (match-end 5)))
16454 (< pos (match-end 0)))
16455 (- pos (or (match-end 8) (match-end 5))))
16456 (t 'day))))
16457 ans))
16459 (defun org-toggle-timestamp-type ()
16460 "Toggle the type (<active> or [inactive]) of a time stamp."
16461 (interactive)
16462 (when (org-at-timestamp-p t)
16463 (let ((beg (match-beginning 0)) (end (match-end 0))
16464 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16465 (save-excursion
16466 (goto-char beg)
16467 (while (re-search-forward "[][<>]" end t)
16468 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16469 t t)))
16470 (message "Timestamp is now %sactive"
16471 (if (equal (char-after beg) ?<) "" "in")))))
16473 (defvar org-clock-history) ; defined in org-clock.el
16474 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16475 (defun org-timestamp-change (n &optional what updown)
16476 "Change the date in the time stamp at point.
16477 The date will be changed by N times WHAT. WHAT can be `day', `month',
16478 `year', `minute', `second'. If WHAT is not given, the cursor position
16479 in the timestamp determines what will be changed."
16480 (let ((origin (point)) origin-cat
16481 with-hm inactive
16482 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16483 org-ts-what
16484 extra rem
16485 ts time time0 fixnext clrgx)
16486 (if (not (org-at-timestamp-p t))
16487 (error "Not at a timestamp"))
16488 (if (and (not what) (eq org-ts-what 'bracket))
16489 (org-toggle-timestamp-type)
16490 ;; Point isn't on brackets. Remember the part of the time-stamp
16491 ;; the point was in. Indeed, size of time-stamps may change,
16492 ;; but point must be kept in the same category nonetheless.
16493 (setq origin-cat org-ts-what)
16494 (if (and (not what) (not (eq org-ts-what 'day))
16495 org-display-custom-times
16496 (get-text-property (point) 'display)
16497 (not (get-text-property (1- (point)) 'display)))
16498 (setq org-ts-what 'day))
16499 (setq org-ts-what (or what org-ts-what)
16500 inactive (= (char-after (match-beginning 0)) ?\[)
16501 ts (match-string 0))
16502 (replace-match "")
16503 (if (string-match
16504 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16506 (setq extra (match-string 1 ts)))
16507 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16508 (setq with-hm t))
16509 (setq time0 (org-parse-time-string ts))
16510 (when (and updown
16511 (eq org-ts-what 'minute)
16512 (not current-prefix-arg))
16513 ;; This looks like s-up and s-down. Change by one rounding step.
16514 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16515 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16516 (setcar (cdr time0) (+ (nth 1 time0)
16517 (if (> n 0) (- rem) (- dm rem))))))
16518 (setq time
16519 (encode-time (or (car time0) 0)
16520 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16521 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16522 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16523 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16524 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16525 (nthcdr 6 time0)))
16526 (when (and (member org-ts-what '(hour minute))
16527 extra
16528 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16529 (setq extra (org-modify-ts-extra
16530 extra
16531 (if (eq org-ts-what 'hour) 2 5)
16532 n dm)))
16533 (when (integerp org-ts-what)
16534 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16535 (if (eq what 'calendar)
16536 (let ((cal-date (org-get-date-from-calendar)))
16537 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16538 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16539 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16540 (setcar time0 (or (car time0) 0))
16541 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16542 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16543 (setq time (apply 'encode-time time0))))
16544 ;; Insert the new time-stamp, and ensure point stays in the same
16545 ;; category as before (i.e. not after the last position in that
16546 ;; category).
16547 (let ((pos (point)))
16548 ;; Stay before inserted string. `save-excursion' is of no use.
16549 (setq org-last-changed-timestamp
16550 (org-insert-time-stamp time with-hm inactive nil nil extra))
16551 (goto-char pos))
16552 (save-match-data
16553 (looking-at org-ts-regexp3)
16554 (goto-char (cond
16555 ;; `day' category ends before `hour' if any, or at
16556 ;; the end of the day name.
16557 ((eq origin-cat 'day)
16558 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16559 ((eq origin-cat 'hour) (min (match-end 7) origin))
16560 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16561 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16562 ;; `year' and `month' have both fixed size: point
16563 ;; couldn't have moved into another part.
16564 (t origin))))
16565 ;; Update clock if on a CLOCK line.
16566 (org-clock-update-time-maybe)
16567 ;; Maybe adjust the closest clock in `org-clock-history'
16568 (when org-clock-adjust-closest
16569 (if (not (and (org-at-clock-log-p)
16570 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16571 org-clock-history))))))
16572 (message "No clock to adjust")
16573 (cond ((save-excursion ; fix previous clock?
16574 (re-search-backward org-ts-regexp0 nil t)
16575 (org-looking-back (concat org-clock-string " \\[")))
16576 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16577 ((save-excursion ; fix next clock?
16578 (re-search-backward org-ts-regexp0 nil t)
16579 (looking-at (concat org-ts-regexp0 "\\] =>")))
16580 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16581 (save-window-excursion
16582 ;; Find closest clock to point, adjust the previous/next one in history
16583 (let* ((p (save-excursion (org-back-to-heading t)))
16584 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16585 (clfixnth
16586 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16587 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16588 (if (not clfixpos)
16589 (message "No clock to adjust")
16590 (save-excursion
16591 (org-goto-marker-or-bmk clfixpos)
16592 (org-show-subtree)
16593 (when (re-search-forward clrgx nil t)
16594 (goto-char (match-beginning 1))
16595 (let (org-clock-adjust-closest)
16596 (org-timestamp-change n org-ts-what updown))
16597 (message "Clock adjusted in %s for heading: %s"
16598 (file-name-nondirectory (buffer-file-name))
16599 (org-get-heading t t)))))))))
16600 ;; Try to recenter the calendar window, if any.
16601 (if (and org-calendar-follow-timestamp-change
16602 (get-buffer-window "*Calendar*" t)
16603 (memq org-ts-what '(day month year)))
16604 (org-recenter-calendar (time-to-days time))))))
16606 (defun org-modify-ts-extra (s pos n dm)
16607 "Change the different parts of the lead-time and repeat fields in timestamp."
16608 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16609 ng h m new rem)
16610 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16611 (cond
16612 ((or (org-pos-in-match-range pos 2)
16613 (org-pos-in-match-range pos 3))
16614 (setq m (string-to-number (match-string 3 s))
16615 h (string-to-number (match-string 2 s)))
16616 (if (org-pos-in-match-range pos 2)
16617 (setq h (+ h n))
16618 (setq n (* dm (org-no-warnings (signum n))))
16619 (when (not (= 0 (setq rem (% m dm))))
16620 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16621 (setq m (+ m n)))
16622 (if (< m 0) (setq m (+ m 60) h (1- h)))
16623 (if (> m 59) (setq m (- m 60) h (1+ h)))
16624 (setq h (min 24 (max 0 h)))
16625 (setq ng 1 new (format "-%02d:%02d" h m)))
16626 ((org-pos-in-match-range pos 6)
16627 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16628 ((org-pos-in-match-range pos 5)
16629 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16631 ((org-pos-in-match-range pos 9)
16632 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16633 ((org-pos-in-match-range pos 8)
16634 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16636 (when ng
16637 (setq s (concat
16638 (substring s 0 (match-beginning ng))
16640 (substring s (match-end ng))))))
16643 (defun org-recenter-calendar (date)
16644 "If the calendar is visible, recenter it to DATE."
16645 (let ((cwin (get-buffer-window "*Calendar*" t)))
16646 (when cwin
16647 (let ((calendar-move-hook nil))
16648 (with-selected-window cwin
16649 (calendar-goto-date (if (listp date) date
16650 (calendar-gregorian-from-absolute date))))))))
16652 (defun org-goto-calendar (&optional arg)
16653 "Go to the Emacs calendar at the current date.
16654 If there is a time stamp in the current line, go to that date.
16655 A prefix ARG can be used to force the current date."
16656 (interactive "P")
16657 (let ((tsr org-ts-regexp) diff
16658 (calendar-move-hook nil)
16659 (calendar-view-holidays-initially-flag nil)
16660 (calendar-view-diary-initially-flag nil))
16661 (if (or (org-at-timestamp-p)
16662 (save-excursion
16663 (beginning-of-line 1)
16664 (looking-at (concat ".*" tsr))))
16665 (let ((d1 (time-to-days (current-time)))
16666 (d2 (time-to-days
16667 (org-time-string-to-time (match-string 1)))))
16668 (setq diff (- d2 d1))))
16669 (calendar)
16670 (calendar-goto-today)
16671 (if (and diff (not arg)) (calendar-forward-day diff))))
16673 (defun org-get-date-from-calendar ()
16674 "Return a list (month day year) of date at point in calendar."
16675 (with-current-buffer "*Calendar*"
16676 (save-match-data
16677 (calendar-cursor-to-date))))
16679 (defun org-date-from-calendar ()
16680 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16681 If there is already a time stamp at the cursor position, update it."
16682 (interactive)
16683 (if (org-at-timestamp-p t)
16684 (org-timestamp-change 0 'calendar)
16685 (let ((cal-date (org-get-date-from-calendar)))
16686 (org-insert-time-stamp
16687 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16689 (defun org-minutes-to-hh:mm-string (m)
16690 "Compute H:MM from a number of minutes."
16691 (let ((h (/ m 60)))
16692 (setq m (- m (* 60 h)))
16693 (format org-time-clocksum-format h m)))
16695 (defun org-hh:mm-string-to-minutes (s)
16696 "Convert a string H:MM to a number of minutes.
16697 If the string is just a number, interpret it as minutes.
16698 In fact, the first hh:mm or number in the string will be taken,
16699 there can be extra stuff in the string.
16700 If no number is found, the return value is 0."
16701 (cond
16702 ((integerp s) s)
16703 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16704 (+ (* (string-to-number (match-string 1 s)) 60)
16705 (string-to-number (match-string 2 s))))
16706 ((string-match "\\([0-9]+\\)" s)
16707 (string-to-number (match-string 1 s)))
16708 (t 0)))
16710 (defcustom org-effort-durations
16711 `(("h" . 60)
16712 ("d" . ,(* 60 8))
16713 ("w" . ,(* 60 8 5))
16714 ("m" . ,(* 60 8 5 4))
16715 ("y" . ,(* 60 8 5 40)))
16716 "Conversion factor to minutes for an effort modifier.
16718 Each entry has the form (MODIFIER . MINUTES).
16720 In an effort string, a number followed by MODIFIER is multiplied
16721 by the specified number of MINUTES to obtain an effort in
16722 minutes.
16724 For example, if the value of this variable is ((\"hours\" . 60)), then an
16725 effort string \"2hours\" is equivalent to 120 minutes."
16726 :group 'org-agenda
16727 :version "24.1"
16728 :type '(alist :key-type (string :tag "Modifier")
16729 :value-type (number :tag "Minutes")))
16731 (defun org-duration-string-to-minutes (s &optional output-to-string)
16732 "Convert a duration string S to minutes.
16734 A bare number is interpreted as minutes, modifiers can be set by
16735 customizing `org-effort-durations' (which see).
16737 Entries containing a colon are interpreted as H:MM by
16738 `org-hh:mm-string-to-minutes'."
16739 (let ((result 0)
16740 (re (concat "\\([0-9.]+\\) *\\("
16741 (regexp-opt (mapcar 'car org-effort-durations))
16742 "\\)")))
16743 (while (string-match re s)
16744 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16745 (string-to-number (match-string 1 s))))
16746 (setq s (replace-match "" nil t s)))
16747 (setq result (floor result))
16748 (incf result (org-hh:mm-string-to-minutes s))
16749 (if output-to-string (number-to-string result) result)))
16751 ;;;; Files
16753 (defun org-save-all-org-buffers ()
16754 "Save all Org-mode buffers without user confirmation."
16755 (interactive)
16756 (message "Saving all Org-mode buffers...")
16757 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16758 (when (featurep 'org-id) (org-id-locations-save))
16759 (message "Saving all Org-mode buffers... done"))
16761 (defun org-revert-all-org-buffers ()
16762 "Revert all Org-mode buffers.
16763 Prompt for confirmation when there are unsaved changes.
16764 Be sure you know what you are doing before letting this function
16765 overwrite your changes.
16767 This function is useful in a setup where one tracks org files
16768 with a version control system, to revert on one machine after pulling
16769 changes from another. I believe the procedure must be like this:
16771 1. M-x org-save-all-org-buffers
16772 2. Pull changes from the other machine, resolve conflicts
16773 3. M-x org-revert-all-org-buffers"
16774 (interactive)
16775 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16776 (error "Abort"))
16777 (save-excursion
16778 (save-window-excursion
16779 (mapc
16780 (lambda (b)
16781 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16782 (with-current-buffer b buffer-file-name))
16783 (org-pop-to-buffer-same-window b)
16784 (revert-buffer t 'no-confirm)))
16785 (buffer-list))
16786 (when (and (featurep 'org-id) org-id-track-globally)
16787 (org-id-locations-load)))))
16789 ;;;; Agenda files
16791 ;;;###autoload
16792 (defun org-switchb (&optional arg)
16793 "Switch between Org buffers.
16794 With one prefix argument, restrict available buffers to files.
16795 With two prefix arguments, restrict available buffers to agenda files.
16797 Defaults to `iswitchb' for buffer name completion.
16798 Set `org-completion-use-ido' to make it use ido instead."
16799 (interactive "P")
16800 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16801 ((equal arg '(16)) (org-buffer-list 'agenda))
16802 (t (org-buffer-list))))
16803 (org-completion-use-iswitchb org-completion-use-iswitchb)
16804 (org-completion-use-ido org-completion-use-ido))
16805 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16806 (setq org-completion-use-iswitchb t))
16807 (org-pop-to-buffer-same-window
16808 (org-icompleting-read "Org buffer: "
16809 (mapcar 'list (mapcar 'buffer-name blist))
16810 nil t))))
16812 ;;; Define some older names previously used for this functionality
16813 ;;;###autoload
16814 (defalias 'org-ido-switchb 'org-switchb)
16815 ;;;###autoload
16816 (defalias 'org-iswitchb 'org-switchb)
16818 (defun org-buffer-list (&optional predicate exclude-tmp)
16819 "Return a list of Org buffers.
16820 PREDICATE can be `export', `files' or `agenda'.
16822 export restrict the list to Export buffers.
16823 files restrict the list to buffers visiting Org files.
16824 agenda restrict the list to buffers visiting agenda files.
16826 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16827 (let* ((bfn nil)
16828 (agenda-files (and (eq predicate 'agenda)
16829 (mapcar 'file-truename (org-agenda-files t))))
16830 (filter
16831 (cond
16832 ((eq predicate 'files)
16833 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16834 ((eq predicate 'export)
16835 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16836 ((eq predicate 'agenda)
16837 (lambda (b)
16838 (with-current-buffer b
16839 (and (derived-mode-p 'org-mode)
16840 (setq bfn (buffer-file-name b))
16841 (member (file-truename bfn) agenda-files)))))
16842 (t (lambda (b) (with-current-buffer b
16843 (or (derived-mode-p 'org-mode)
16844 (string-match "\*Org .*Export"
16845 (buffer-name b)))))))))
16846 (delq nil
16847 (mapcar
16848 (lambda(b)
16849 (if (and (funcall filter b)
16850 (or (not exclude-tmp)
16851 (not (string-match "tmp" (buffer-name b)))))
16853 nil))
16854 (buffer-list)))))
16856 (defun org-agenda-files (&optional unrestricted archives)
16857 "Get the list of agenda files.
16858 Optional UNRESTRICTED means return the full list even if a restriction
16859 is currently in place.
16860 When ARCHIVES is t, include all archive files that are really being
16861 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16862 `org-agenda-archives-mode' is t."
16863 (let ((files
16864 (cond
16865 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16866 ((stringp org-agenda-files) (org-read-agenda-file-list))
16867 ((listp org-agenda-files) org-agenda-files)
16868 (t (error "Invalid value of `org-agenda-files'")))))
16869 (setq files (apply 'append
16870 (mapcar (lambda (f)
16871 (if (file-directory-p f)
16872 (directory-files
16873 f t org-agenda-file-regexp)
16874 (list f)))
16875 files)))
16876 (when org-agenda-skip-unavailable-files
16877 (setq files (delq nil
16878 (mapcar (function
16879 (lambda (file)
16880 (and (file-readable-p file) file)))
16881 files))))
16882 (when (or (eq archives t)
16883 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16884 (setq files (org-add-archive-files files)))
16885 files))
16887 (defun org-agenda-file-p (&optional file)
16888 "Return non-nil, if FILE is an agenda file.
16889 If FILE is omitted, use the file associated with the current
16890 buffer."
16891 (member (or file (buffer-file-name))
16892 (org-agenda-files t)))
16894 (defun org-edit-agenda-file-list ()
16895 "Edit the list of agenda files.
16896 Depending on setup, this either uses customize to edit the variable
16897 `org-agenda-files', or it visits the file that is holding the list. In the
16898 latter case, the buffer is set up in a way that saving it automatically kills
16899 the buffer and restores the previous window configuration."
16900 (interactive)
16901 (if (stringp org-agenda-files)
16902 (let ((cw (current-window-configuration)))
16903 (find-file org-agenda-files)
16904 (org-set-local 'org-window-configuration cw)
16905 (org-add-hook 'after-save-hook
16906 (lambda ()
16907 (set-window-configuration
16908 (prog1 org-window-configuration
16909 (kill-buffer (current-buffer))))
16910 (org-install-agenda-files-menu)
16911 (message "New agenda file list installed"))
16912 nil 'local)
16913 (message "%s" (substitute-command-keys
16914 "Edit list and finish with \\[save-buffer]")))
16915 (customize-variable 'org-agenda-files)))
16917 (defun org-store-new-agenda-file-list (list)
16918 "Set new value for the agenda file list and save it correctly."
16919 (if (stringp org-agenda-files)
16920 (let ((fe (org-read-agenda-file-list t)) b u)
16921 (while (setq b (find-buffer-visiting org-agenda-files))
16922 (kill-buffer b))
16923 (with-temp-file org-agenda-files
16924 (insert
16925 (mapconcat
16926 (lambda (f) ;; Keep un-expanded entries.
16927 (if (setq u (assoc f fe))
16928 (cdr u)
16930 list "\n")
16931 "\n")))
16932 (let ((org-mode-hook nil) (org-inhibit-startup t)
16933 (org-insert-mode-line-in-empty-file nil))
16934 (setq org-agenda-files list)
16935 (customize-save-variable 'org-agenda-files org-agenda-files))))
16937 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16938 "Read the list of agenda files from a file.
16939 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16940 filenames, used by `org-store-new-agenda-file-list' to write back
16941 un-expanded file names."
16942 (when (file-directory-p org-agenda-files)
16943 (error "`org-agenda-files' cannot be a single directory"))
16944 (when (stringp org-agenda-files)
16945 (with-temp-buffer
16946 (insert-file-contents org-agenda-files)
16947 (mapcar
16948 (lambda (f)
16949 (let ((e (expand-file-name (substitute-in-file-name f)
16950 org-directory)))
16951 (if pair-with-expansion
16952 (cons e f)
16953 e)))
16954 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16956 ;;;###autoload
16957 (defun org-cycle-agenda-files ()
16958 "Cycle through the files in `org-agenda-files'.
16959 If the current buffer visits an agenda file, find the next one in the list.
16960 If the current buffer does not, find the first agenda file."
16961 (interactive)
16962 (let* ((fs (org-agenda-files t))
16963 (files (append fs (list (car fs))))
16964 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16965 file)
16966 (unless files (error "No agenda files"))
16967 (catch 'exit
16968 (while (setq file (pop files))
16969 (if (equal (file-truename file) tcf)
16970 (when (car files)
16971 (find-file (car files))
16972 (throw 'exit t))))
16973 (find-file (car fs)))
16974 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16976 (defun org-agenda-file-to-front (&optional to-end)
16977 "Move/add the current file to the top of the agenda file list.
16978 If the file is not present in the list, it is added to the front. If it is
16979 present, it is moved there. With optional argument TO-END, add/move to the
16980 end of the list."
16981 (interactive "P")
16982 (let ((org-agenda-skip-unavailable-files nil)
16983 (file-alist (mapcar (lambda (x)
16984 (cons (file-truename x) x))
16985 (org-agenda-files t)))
16986 (ctf (file-truename buffer-file-name))
16987 x had)
16988 (setq x (assoc ctf file-alist) had x)
16990 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16991 (if to-end
16992 (setq file-alist (append (delq x file-alist) (list x)))
16993 (setq file-alist (cons x (delq x file-alist))))
16994 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16995 (org-install-agenda-files-menu)
16996 (message "File %s to %s of agenda file list"
16997 (if had "moved" "added") (if to-end "end" "front"))))
16999 (defun org-remove-file (&optional file)
17000 "Remove current file from the list of files in variable `org-agenda-files'.
17001 These are the files which are being checked for agenda entries.
17002 Optional argument FILE means use this file instead of the current."
17003 (interactive)
17004 (let* ((org-agenda-skip-unavailable-files nil)
17005 (file (or file buffer-file-name))
17006 (true-file (file-truename file))
17007 (afile (abbreviate-file-name file))
17008 (files (delq nil (mapcar
17009 (lambda (x)
17010 (if (equal true-file
17011 (file-truename x))
17012 nil x))
17013 (org-agenda-files t)))))
17014 (if (not (= (length files) (length (org-agenda-files t))))
17015 (progn
17016 (org-store-new-agenda-file-list files)
17017 (org-install-agenda-files-menu)
17018 (message "Removed file: %s" afile))
17019 (message "File was not in list: %s (not removed)" afile))))
17021 (defun org-file-menu-entry (file)
17022 (vector file (list 'find-file file) t))
17024 (defun org-check-agenda-file (file)
17025 "Make sure FILE exists. If not, ask user what to do."
17026 (when (not (file-exists-p file))
17027 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17028 (abbreviate-file-name file))
17029 (let ((r (downcase (read-char-exclusive))))
17030 (cond
17031 ((equal r ?r)
17032 (org-remove-file file)
17033 (throw 'nextfile t))
17034 (t (error "Abort"))))))
17036 (defun org-get-agenda-file-buffer (file)
17037 "Get a buffer visiting FILE. If the buffer needs to be created, add
17038 it to the list of buffers which might be released later."
17039 (let ((buf (org-find-base-buffer-visiting file)))
17040 (if buf
17041 buf ; just return it
17042 ;; Make a new buffer and remember it
17043 (setq buf (find-file-noselect file))
17044 (if buf (push buf org-agenda-new-buffers))
17045 buf)))
17047 (defun org-release-buffers (blist)
17048 "Release all buffers in list, asking the user for confirmation when needed.
17049 When a buffer is unmodified, it is just killed. When modified, it is saved
17050 \(if the user agrees) and then killed."
17051 (let (buf file)
17052 (while (setq buf (pop blist))
17053 (setq file (buffer-file-name buf))
17054 (when (and (buffer-modified-p buf)
17055 file
17056 (y-or-n-p (format "Save file %s? " file)))
17057 (with-current-buffer buf (save-buffer)))
17058 (kill-buffer buf))))
17060 (defun org-agenda-prepare-buffers (files)
17061 "Create buffers for all agenda files, protect archived trees and comments."
17062 (interactive)
17063 (let ((pa '(:org-archived t))
17064 (pc '(:org-comment t))
17065 (pall '(:org-archived t :org-comment t))
17066 (inhibit-read-only t)
17067 (rea (concat ":" org-archive-tag ":"))
17068 bmp file re)
17069 (save-excursion
17070 (save-restriction
17071 (while (setq file (pop files))
17072 (catch 'nextfile
17073 (if (bufferp file)
17074 (set-buffer file)
17075 (org-check-agenda-file file)
17076 (set-buffer (org-get-agenda-file-buffer file)))
17077 (widen)
17078 (setq bmp (buffer-modified-p))
17079 (org-refresh-category-properties)
17080 (setq org-todo-keywords-for-agenda
17081 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17082 (setq org-done-keywords-for-agenda
17083 (append org-done-keywords-for-agenda org-done-keywords))
17084 (setq org-todo-keyword-alist-for-agenda
17085 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17086 (setq org-drawers-for-agenda
17087 (append org-drawers-for-agenda org-drawers))
17088 (setq org-tag-alist-for-agenda
17089 (append org-tag-alist-for-agenda org-tag-alist))
17091 (save-excursion
17092 (remove-text-properties (point-min) (point-max) pall)
17093 (when org-agenda-skip-archived-trees
17094 (goto-char (point-min))
17095 (while (re-search-forward rea nil t)
17096 (if (org-at-heading-p t)
17097 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17098 (goto-char (point-min))
17099 (setq re (format org-heading-keyword-regexp-format
17100 org-comment-string))
17101 (while (re-search-forward re nil t)
17102 (add-text-properties
17103 (match-beginning 0) (org-end-of-subtree t) pc)))
17104 (set-buffer-modified-p bmp)))))
17105 (setq org-todo-keywords-for-agenda
17106 (org-uniquify org-todo-keywords-for-agenda))
17107 (setq org-todo-keyword-alist-for-agenda
17108 (org-uniquify org-todo-keyword-alist-for-agenda)
17109 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17111 ;;;; Embedded LaTeX
17113 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17114 "Keymap for the minor `org-cdlatex-mode'.")
17116 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17117 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17118 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17119 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17120 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17122 (defvar org-cdlatex-texmathp-advice-is-done nil
17123 "Flag remembering if we have applied the advice to texmathp already.")
17125 (define-minor-mode org-cdlatex-mode
17126 "Toggle the minor `org-cdlatex-mode'.
17127 This mode supports entering LaTeX environment and math in LaTeX fragments
17128 in Org-mode.
17129 \\{org-cdlatex-mode-map}"
17130 nil " OCDL" nil
17131 (when org-cdlatex-mode
17132 (require 'cdlatex)
17133 (run-hooks 'cdlatex-mode-hook)
17134 (cdlatex-compute-tables))
17135 (unless org-cdlatex-texmathp-advice-is-done
17136 (setq org-cdlatex-texmathp-advice-is-done t)
17137 (defadvice texmathp (around org-math-always-on activate)
17138 "Always return t in org-mode buffers.
17139 This is because we want to insert math symbols without dollars even outside
17140 the LaTeX math segments. If Orgmode thinks that point is actually inside
17141 an embedded LaTeX fragment, let texmathp do its job.
17142 \\[org-cdlatex-mode-map]"
17143 (interactive)
17144 (let (p)
17145 (cond
17146 ((not (derived-mode-p 'org-mode)) ad-do-it)
17147 ((eq this-command 'cdlatex-math-symbol)
17148 (setq ad-return-value t
17149 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17151 (let ((p (org-inside-LaTeX-fragment-p)))
17152 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17153 (setq ad-return-value t
17154 texmathp-why '("Org-mode embedded math" . 0))
17155 (if p ad-do-it)))))))))
17157 (defun turn-on-org-cdlatex ()
17158 "Unconditionally turn on `org-cdlatex-mode'."
17159 (org-cdlatex-mode 1))
17161 (defun org-inside-LaTeX-fragment-p ()
17162 "Test if point is inside a LaTeX fragment.
17163 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17164 sequence appearing also before point.
17165 Even though the matchers for math are configurable, this function assumes
17166 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17167 delimiters are skipped when they have been removed by customization.
17168 The return value is nil, or a cons cell with the delimiter and the
17169 position of this delimiter.
17171 This function does a reasonably good job, but can locally be fooled by
17172 for example currency specifications. For example it will assume being in
17173 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17174 fragments that are properly closed, but during editing, we have to live
17175 with the uncertainty caused by missing closing delimiters. This function
17176 looks only before point, not after."
17177 (catch 'exit
17178 (let ((pos (point))
17179 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17180 (lim (progn
17181 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17182 (point)))
17183 dd-on str (start 0) m re)
17184 (goto-char pos)
17185 (when dodollar
17186 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17187 re (nth 1 (assoc "$" org-latex-regexps)))
17188 (while (string-match re str start)
17189 (cond
17190 ((= (match-end 0) (length str))
17191 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17192 ((= (match-end 0) (- (length str) 5))
17193 (throw 'exit nil))
17194 (t (setq start (match-end 0))))))
17195 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17196 (goto-char pos)
17197 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17198 (and (match-beginning 2) (throw 'exit nil))
17199 ;; count $$
17200 (while (re-search-backward "\\$\\$" lim t)
17201 (setq dd-on (not dd-on)))
17202 (goto-char pos)
17203 (if dd-on (cons "$$" m))))))
17205 (defun org-inside-latex-macro-p ()
17206 "Is point inside a LaTeX macro or its arguments?"
17207 (save-match-data
17208 (org-in-regexp
17209 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17211 (defun org-try-cdlatex-tab ()
17212 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17213 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17214 - inside a LaTeX fragment, or
17215 - after the first word in a line, where an abbreviation expansion could
17216 insert a LaTeX environment."
17217 (when org-cdlatex-mode
17218 (cond
17219 ;; Before any word on the line: No expansion possible.
17220 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17221 ;; Just after first word on the line: Expand it. Make sure it
17222 ;; cannot happen on headlines, though.
17223 ((save-excursion
17224 (skip-chars-backward "a-zA-Z0-9*")
17225 (skip-chars-backward " \t")
17226 (and (bolp) (not (org-at-heading-p))))
17227 (cdlatex-tab) t)
17228 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17230 (defun org-cdlatex-underscore-caret (&optional arg)
17231 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17232 Revert to the normal definition outside of these fragments."
17233 (interactive "P")
17234 (if (org-inside-LaTeX-fragment-p)
17235 (call-interactively 'cdlatex-sub-superscript)
17236 (let (org-cdlatex-mode)
17237 (call-interactively (key-binding (vector last-input-event))))))
17239 (defun org-cdlatex-math-modify (&optional arg)
17240 "Execute `cdlatex-math-modify' in LaTeX fragments.
17241 Revert to the normal definition outside of these fragments."
17242 (interactive "P")
17243 (if (org-inside-LaTeX-fragment-p)
17244 (call-interactively 'cdlatex-math-modify)
17245 (let (org-cdlatex-mode)
17246 (call-interactively (key-binding (vector last-input-event))))))
17248 (defvar org-latex-fragment-image-overlays nil
17249 "List of overlays carrying the images of latex fragments.")
17250 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17252 (defun org-remove-latex-fragment-image-overlays ()
17253 "Remove all overlays with LaTeX fragment images in current buffer."
17254 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17255 (setq org-latex-fragment-image-overlays nil))
17257 (defun org-preview-latex-fragment (&optional subtree)
17258 "Preview the LaTeX fragment at point, or all locally or globally.
17259 If the cursor is in a LaTeX fragment, create the image and overlay
17260 it over the source code. If there is no fragment at point, display
17261 all fragments in the current text, from one headline to the next. With
17262 prefix SUBTREE, display all fragments in the current subtree. With a
17263 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17264 the cursor is before the first headline,
17265 display all fragments in the buffer.
17266 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17267 (interactive "P")
17268 (unless buffer-file-name
17269 (error "Can't preview LaTeX fragment in a non-file buffer"))
17270 (org-remove-latex-fragment-image-overlays)
17271 (save-excursion
17272 (save-restriction
17273 (let (beg end at msg)
17274 (cond
17275 ((or (equal subtree '(16))
17276 (not (save-excursion
17277 (re-search-backward org-outline-regexp-bol nil t))))
17278 (setq beg (point-min) end (point-max)
17279 msg "Creating images for buffer...%s"))
17280 ((equal subtree '(4))
17281 (org-back-to-heading)
17282 (setq beg (point) end (org-end-of-subtree t)
17283 msg "Creating images for subtree...%s"))
17285 (if (setq at (org-inside-LaTeX-fragment-p))
17286 (goto-char (max (point-min) (- (cdr at) 2)))
17287 (org-back-to-heading))
17288 (setq beg (point) end (progn (outline-next-heading) (point))
17289 msg (if at "Creating image...%s"
17290 "Creating images for entry...%s"))))
17291 (message msg "")
17292 (narrow-to-region beg end)
17293 (goto-char beg)
17294 (org-format-latex
17295 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17296 (file-name-nondirectory
17297 buffer-file-name)))
17298 default-directory 'overlays msg at 'forbuffer
17299 org-latex-create-formula-image-program)
17300 (message msg "done. Use `C-c C-c' to remove images.")))))
17302 (defvar org-latex-regexps
17303 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17304 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17305 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17306 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17307 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17308 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17309 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17310 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17311 "Regular expressions for matching embedded LaTeX.")
17313 (defvar org-export-have-math nil) ;; dynamic scoping
17314 (defun org-format-latex (prefix &optional dir overlays msg at
17315 forbuffer processing-type)
17316 "Replace LaTeX fragments with links to an image, and produce images.
17317 Some of the options can be changed using the variable
17318 `org-format-latex-options'."
17319 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17320 (let* ((prefixnodir (file-name-nondirectory prefix))
17321 (absprefix (expand-file-name prefix dir))
17322 (todir (file-name-directory absprefix))
17323 (opt org-format-latex-options)
17324 (matchers (plist-get opt :matchers))
17325 (re-list org-latex-regexps)
17326 (org-format-latex-header-extra
17327 (plist-get (org-infile-export-plist) :latex-header-extra))
17328 (cnt 0) txt hash link beg end re e checkdir
17329 executables-checked string
17330 m n block-type block linkfile movefile ov)
17331 ;; Check the different regular expressions
17332 (while (setq e (pop re-list))
17333 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17334 block (if block-type "\n\n" ""))
17335 (when (member m matchers)
17336 (goto-char (point-min))
17337 (while (re-search-forward re nil t)
17338 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17339 (not (get-text-property (match-beginning n)
17340 'org-protected))
17341 (or (not overlays)
17342 (not (eq (get-char-property (match-beginning n)
17343 'org-overlay-type)
17344 'org-latex-overlay))))
17345 (setq org-export-have-math t)
17346 (cond
17347 ((eq processing-type 'verbatim)
17348 ;; Leave the text verbatim, just protect it
17349 (add-text-properties (match-beginning n) (match-end n)
17350 '(org-protected t)))
17351 ((eq processing-type 'mathjax)
17352 ;; Prepare for MathJax processing
17353 (setq string (match-string n))
17354 (if (member m '("$" "$1"))
17355 (save-excursion
17356 (delete-region (match-beginning n) (match-end n))
17357 (goto-char (match-beginning n))
17358 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17359 "\\)")
17360 '(org-protected t))))
17361 (add-text-properties (match-beginning n) (match-end n)
17362 '(org-protected t))))
17363 ((or (eq processing-type 'dvipng)
17364 (eq processing-type 'imagemagick))
17365 ;; Process to an image
17366 (setq txt (match-string n)
17367 beg (match-beginning n) end (match-end n)
17368 cnt (1+ cnt))
17369 (let (print-length print-level) ; make sure full list is printed
17370 (setq hash (sha1 (prin1-to-string
17371 (list org-format-latex-header
17372 org-format-latex-header-extra
17373 org-export-latex-default-packages-alist
17374 org-export-latex-packages-alist
17375 org-format-latex-options
17376 forbuffer txt)))
17377 linkfile (format "%s_%s.png" prefix hash)
17378 movefile (format "%s_%s.png" absprefix hash)))
17379 (setq link (concat block "[[file:" linkfile "]]" block))
17380 (if msg (message msg cnt))
17381 (goto-char beg)
17382 (unless checkdir ; make sure the directory exists
17383 (setq checkdir t)
17384 (or (file-directory-p todir) (make-directory todir t)))
17385 (cond
17386 ((eq processing-type 'dvipng)
17387 (unless executables-checked
17388 (org-check-external-command
17389 "latex" "needed to convert LaTeX fragments to images")
17390 (org-check-external-command
17391 "dvipng" "needed to convert LaTeX fragments to images")
17392 (setq executables-checked t))
17393 (unless (file-exists-p movefile)
17394 (org-create-formula-image-with-dvipng
17395 txt movefile opt forbuffer)))
17396 ((eq processing-type 'imagemagick)
17397 (unless executables-checked
17398 (org-check-external-command
17399 "convert" "you need to install imagemagick")
17400 (setq executables-checked t))
17401 (unless (file-exists-p movefile)
17402 (org-create-formula-image-with-imagemagick
17403 txt movefile opt forbuffer))))
17404 (if overlays
17405 (progn
17406 (mapc (lambda (o)
17407 (if (eq (overlay-get o 'org-overlay-type)
17408 'org-latex-overlay)
17409 (delete-overlay o)))
17410 (overlays-in beg end))
17411 (setq ov (make-overlay beg end))
17412 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17413 (if (featurep 'xemacs)
17414 (progn
17415 (overlay-put ov 'invisible t)
17416 (overlay-put
17417 ov 'end-glyph
17418 (make-glyph (vector 'png :file movefile))))
17419 (overlay-put
17420 ov 'display
17421 (list 'image :type 'png :file movefile :ascent 'center)))
17422 (push ov org-latex-fragment-image-overlays)
17423 (goto-char end))
17424 (delete-region beg end)
17425 (insert (org-add-props link
17426 (list 'org-latex-src
17427 (replace-regexp-in-string
17428 "\"" "" txt)
17429 'org-latex-src-embed-type
17430 (if block-type 'paragraph 'character))))))
17431 ((eq processing-type 'mathml)
17432 ;; Process to MathML
17433 (unless executables-checked
17434 (unless (save-match-data (org-format-latex-mathml-available-p))
17435 (error "LaTeX to MathML converter not configured"))
17436 (setq executables-checked t))
17437 (setq txt (match-string n)
17438 beg (match-beginning n) end (match-end n)
17439 cnt (1+ cnt))
17440 (if msg (message msg cnt))
17441 (goto-char beg)
17442 (delete-region beg end)
17443 (insert (org-format-latex-as-mathml
17444 txt block-type prefix dir)))
17446 (error "Unknown conversion type %s for latex fragments"
17447 processing-type)))))))))
17449 (defun org-create-math-formula (latex-frag &optional mathml-file)
17450 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17451 Use `org-latex-to-mathml-convert-command'. If the conversion is
17452 sucessful, return the portion between \"<math...> </math>\"
17453 elements otherwise return nil. When MATHML-FILE is specified,
17454 write the results in to that file. When invoked as an
17455 interactive command, prompt for LATEX-FRAG, with initial value
17456 set to the current active region and echo the results for user
17457 inspection."
17458 (interactive (list (let ((frag (when (org-region-active-p)
17459 (buffer-substring-no-properties
17460 (region-beginning) (region-end)))))
17461 (read-string "LaTeX Fragment: " frag nil frag))))
17462 (unless latex-frag (error "Invalid latex-frag"))
17463 (let* ((tmp-in-file (file-relative-name
17464 (make-temp-name (expand-file-name "ltxmathml-in"))))
17465 (ignore (write-region latex-frag nil tmp-in-file))
17466 (tmp-out-file (file-relative-name
17467 (make-temp-name (expand-file-name "ltxmathml-out"))))
17468 (cmd (format-spec
17469 org-latex-to-mathml-convert-command
17470 `((?j . ,(shell-quote-argument
17471 (expand-file-name org-latex-to-mathml-jar-file)))
17472 (?I . ,(shell-quote-argument tmp-in-file))
17473 (?o . ,(shell-quote-argument tmp-out-file)))))
17474 mathml shell-command-output)
17475 (when (org-called-interactively-p 'any)
17476 (unless (org-format-latex-mathml-available-p)
17477 (error "LaTeX to MathML converter not configured")))
17478 (message "Running %s" cmd)
17479 (setq shell-command-output (shell-command-to-string cmd))
17480 (setq mathml
17481 (when (file-readable-p tmp-out-file)
17482 (with-current-buffer (find-file-noselect tmp-out-file t)
17483 (goto-char (point-min))
17484 (when (re-search-forward
17485 (concat
17486 (regexp-quote
17487 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17488 "\\(.\\|\n\\)*"
17489 (regexp-quote "</math>")) nil t)
17490 (prog1 (match-string 0) (kill-buffer))))))
17491 (cond
17492 (mathml
17493 (setq mathml
17494 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17495 (when mathml-file
17496 (write-region mathml nil mathml-file))
17497 (when (org-called-interactively-p 'any)
17498 (message mathml)))
17499 ((message "LaTeX to MathML conversion failed")
17500 (message shell-command-output)))
17501 (delete-file tmp-in-file)
17502 (when (file-exists-p tmp-out-file)
17503 (delete-file tmp-out-file))
17504 mathml))
17506 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17507 prefix &optional dir)
17508 "Use `org-create-math-formula' but check local cache first."
17509 (let* ((absprefix (expand-file-name prefix dir))
17510 (print-length nil) (print-level nil)
17511 (formula-id (concat
17512 "formula-"
17513 (sha1
17514 (prin1-to-string
17515 (list latex-frag
17516 org-latex-to-mathml-convert-command)))))
17517 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17518 (formula-cache-dir (file-name-directory formula-cache)))
17520 (unless (file-directory-p formula-cache-dir)
17521 (make-directory formula-cache-dir t))
17523 (unless (file-exists-p formula-cache)
17524 (org-create-math-formula latex-frag formula-cache))
17526 (if (file-exists-p formula-cache)
17527 ;; Successful conversion. Return the link to MathML file.
17528 (org-add-props
17529 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17530 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17531 'org-latex-src-embed-type (if latex-frag-type
17532 'paragraph 'character)))
17533 ;; Failed conversion. Return the LaTeX fragment verbatim
17534 (add-text-properties
17535 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17536 latex-frag)))
17538 ;; This function borrows from Ganesh Swami's latex2png.el
17539 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17540 "This calls dvipng."
17541 (require 'org-latex)
17542 (let* ((tmpdir (if (featurep 'xemacs)
17543 (temp-directory)
17544 temporary-file-directory))
17545 (texfilebase (make-temp-name
17546 (expand-file-name "orgtex" tmpdir)))
17547 (texfile (concat texfilebase ".tex"))
17548 (dvifile (concat texfilebase ".dvi"))
17549 (pngfile (concat texfilebase ".png"))
17550 (fnh (if (featurep 'xemacs)
17551 (font-height (face-font 'default))
17552 (face-attribute 'default :height nil)))
17553 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17554 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17555 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17556 "Black"))
17557 (bg (or (plist-get options (if buffer :background :html-background))
17558 "Transparent")))
17559 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17560 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17561 (with-temp-file texfile
17562 (insert (org-splice-latex-header
17563 org-format-latex-header
17564 org-export-latex-default-packages-alist
17565 org-export-latex-packages-alist t
17566 org-format-latex-header-extra))
17567 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17568 (require 'org-latex)
17569 (org-export-latex-fix-inputenc))
17570 (let ((dir default-directory))
17571 (condition-case nil
17572 (progn
17573 (cd tmpdir)
17574 (call-process "latex" nil nil nil texfile))
17575 (error nil))
17576 (cd dir))
17577 (if (not (file-exists-p dvifile))
17578 (progn (message "Failed to create dvi file from %s" texfile) nil)
17579 (condition-case nil
17580 (if (featurep 'xemacs)
17581 (call-process "dvipng" nil nil nil
17582 "-fg" fg "-bg" bg
17583 "-T" "tight"
17584 "-o" pngfile
17585 dvifile)
17586 (call-process "dvipng" nil nil nil
17587 "-fg" fg "-bg" bg
17588 "-D" dpi
17589 ;;"-x" scale "-y" scale
17590 "-T" "tight"
17591 "-o" pngfile
17592 dvifile))
17593 (error nil))
17594 (if (not (file-exists-p pngfile))
17595 (if org-format-latex-signal-error
17596 (error "Failed to create png file from %s" texfile)
17597 (message "Failed to create png file from %s" texfile)
17598 nil)
17599 ;; Use the requested file name and clean up
17600 (copy-file pngfile tofile 'replace)
17601 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17602 (if (file-exists-p (concat texfilebase e))
17603 (delete-file (concat texfilebase e))))
17604 pngfile))))
17606 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17607 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17608 "This calls convert, which is included into imagemagick."
17609 (require 'org-latex)
17610 (let* ((tmpdir (if (featurep 'xemacs)
17611 (temp-directory)
17612 temporary-file-directory))
17613 (texfilebase (make-temp-name
17614 (expand-file-name "orgtex" tmpdir)))
17615 (texfile (concat texfilebase ".tex"))
17616 (pdffile (concat texfilebase ".pdf"))
17617 (pngfile (concat texfilebase ".png"))
17618 (fnh (if (featurep 'xemacs)
17619 (font-height (face-font 'default))
17620 (face-attribute 'default :height nil)))
17621 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17622 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17623 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17624 "black"))
17625 (bg (or (plist-get options (if buffer :background :html-background))
17626 "white")))
17627 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17628 (setq fg (org-latex-color-format fg)))
17629 (if (eq bg 'default) (setq bg (org-latex-color :background))
17630 (setq bg (org-latex-color-format
17631 (if (string= bg "Transparent")(setq bg "white")))))
17632 (with-temp-file texfile
17633 (insert (org-splice-latex-header
17634 org-format-latex-header
17635 org-export-latex-default-packages-alist
17636 org-export-latex-packages-alist t
17637 org-format-latex-header-extra))
17638 (insert "\n\\begin{document}\n"
17639 "\\definecolor{fg}{rgb}{" fg "}\n"
17640 "\\definecolor{bg}{rgb}{" bg "}\n"
17641 "\n\\pagecolor{bg}\n"
17642 "\n{\\color{fg}\n"
17643 string
17644 "\n}\n"
17645 "\n\\end{document}\n" )
17646 (require 'org-latex)
17647 (org-export-latex-fix-inputenc))
17648 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17649 (condition-case nil
17650 (progn
17651 (cd tmpdir)
17652 (setq cmds org-latex-to-pdf-process)
17653 (while cmds
17654 (setq latex-frags-cmds (pop cmds))
17655 (if (listp latex-frags-cmds)
17656 (setq cmds nil)
17657 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17658 (while latex-frags-cmds
17659 (setq cmd (pop latex-frags-cmds))
17660 (while (string-match "%b" cmd)
17661 (setq cmd (replace-match
17662 (save-match-data
17663 (shell-quote-argument texfile))
17664 t t cmd)))
17665 (while (string-match "%f" cmd)
17666 (setq cmd (replace-match
17667 (save-match-data
17668 (shell-quote-argument (file-name-nondirectory texfile)))
17669 t t cmd)))
17670 (while (string-match "%o" cmd)
17671 (setq cmd (replace-match
17672 (save-match-data
17673 (shell-quote-argument (file-name-directory texfile)))
17674 t t cmd)))
17675 (setq cmd (split-string cmd))
17676 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17677 (error nil))
17678 (cd dir))
17679 (if (not (file-exists-p pdffile))
17680 (progn (message "Failed to create pdf file from %s" texfile) nil)
17681 (condition-case nil
17682 (if (featurep 'xemacs)
17683 (call-process "convert" nil nil nil
17684 "-density" "96"
17685 "-trim"
17686 "-antialias"
17687 pdffile
17688 "-quality" "100"
17689 ;; "-sharpen" "0x1.0"
17690 pngfile)
17691 (call-process "convert" nil nil nil
17692 "-density" dpi
17693 "-trim"
17694 "-antialias"
17695 pdffile
17696 "-quality" "100"
17697 ; "-sharpen" "0x1.0"
17698 pngfile))
17699 (error nil))
17700 (if (not (file-exists-p pngfile))
17701 (if org-format-latex-signal-error
17702 (error "Failed to create png file from %s" texfile)
17703 (message "Failed to create png file from %s" texfile)
17704 nil)
17705 ;; Use the requested file name and clean up
17706 (copy-file pngfile tofile 'replace)
17707 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17708 (if (file-exists-p (concat texfilebase e))
17709 (delete-file (concat texfilebase e))))
17710 pngfile))))
17712 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17713 "Fill a LaTeX header template TPL.
17714 In the template, the following place holders will be recognized:
17716 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17717 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17718 [PACKAGES] \\usepackage statements for PKG
17719 [NO-PACKAGES] do not include PKG
17720 [EXTRA] the string EXTRA
17721 [NO-EXTRA] do not include EXTRA
17723 For backward compatibility, if both the positive and the negative place
17724 holder is missing, the positive one (without the \"NO-\") will be
17725 assumed to be present at the end of the template.
17726 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17727 EXTRA is a string.
17728 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17729 (let (rpl (end ""))
17730 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17731 (setq rpl (if (or (match-end 1) (not def-pkg))
17732 "" (org-latex-packages-to-string def-pkg snippets-p t))
17733 tpl (replace-match rpl t t tpl))
17734 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17736 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17737 (setq rpl (if (or (match-end 1) (not pkg))
17738 "" (org-latex-packages-to-string pkg snippets-p t))
17739 tpl (replace-match rpl t t tpl))
17740 (if pkg (setq end
17741 (concat end "\n"
17742 (org-latex-packages-to-string pkg snippets-p)))))
17744 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17745 (setq rpl (if (or (match-end 1) (not extra))
17746 "" (concat extra "\n"))
17747 tpl (replace-match rpl t t tpl))
17748 (if (and extra (string-match "\\S-" extra))
17749 (setq end (concat end "\n" extra))))
17751 (if (string-match "\\S-" end)
17752 (concat tpl "\n" end)
17753 tpl)))
17755 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17756 "Turn an alist of packages into a string with the \\usepackage macros."
17757 (setq pkg (mapconcat (lambda(p)
17758 (cond
17759 ((stringp p) p)
17760 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17761 (format "%% Package %s omitted" (cadr p)))
17762 ((equal "" (car p))
17763 (format "\\usepackage{%s}" (cadr p)))
17765 (format "\\usepackage[%s]{%s}"
17766 (car p) (cadr p)))))
17768 "\n"))
17769 (if newline (concat pkg "\n") pkg))
17771 (defun org-dvipng-color (attr)
17772 "Return a RGB color specification for dvipng."
17773 (apply 'format "rgb %s %s %s"
17774 (mapcar 'org-normalize-color
17775 (if (featurep 'xemacs)
17776 (color-rgb-components
17777 (face-property 'default
17778 (cond ((eq attr :foreground) 'foreground)
17779 ((eq attr :background) 'background))))
17780 (color-values (face-attribute 'default attr nil))))))
17782 (defun org-latex-color (attr)
17783 "Return a RGB color for the LaTeX color package."
17784 (apply 'format "%s,%s,%s"
17785 (mapcar 'org-normalize-color
17786 (if (featurep 'xemacs)
17787 (color-rgb-components
17788 (face-property 'default
17789 (cond ((eq attr :foreground) 'foreground)
17790 ((eq attr :background) 'background))))
17791 (color-values (face-attribute 'default attr nil))))))
17793 (defun org-latex-color-format (color-name)
17794 "Convert COLOR-NAME to a RGB color value."
17795 (apply 'format "%s,%s,%s"
17796 (mapcar 'org-normalize-color
17797 (color-values color-name))))
17799 (defun org-normalize-color (value)
17800 "Return string to be used as color value for an RGB component."
17801 (format "%g" (/ value 65535.0)))
17803 ;; Image display
17806 (defvar org-inline-image-overlays nil)
17807 (make-variable-buffer-local 'org-inline-image-overlays)
17809 (defun org-toggle-inline-images (&optional include-linked)
17810 "Toggle the display of inline images.
17811 INCLUDE-LINKED is passed to `org-display-inline-images'."
17812 (interactive "P")
17813 (if org-inline-image-overlays
17814 (progn
17815 (org-remove-inline-images)
17816 (message "Inline image display turned off"))
17817 (org-display-inline-images include-linked)
17818 (if org-inline-image-overlays
17819 (message "%d images displayed inline"
17820 (length org-inline-image-overlays))
17821 (message "No images to display inline"))))
17823 (defun org-redisplay-inline-images ()
17824 "Refresh the display of inline images."
17825 (interactive)
17826 (if (not org-inline-image-overlays)
17827 (org-toggle-inline-images)
17828 (org-toggle-inline-images)
17829 (org-toggle-inline-images)))
17831 (defun org-display-inline-images (&optional include-linked refresh beg end)
17832 "Display inline images.
17833 Normally only links without a description part are inlined, because this
17834 is how it will work for export. When INCLUDE-LINKED is set, also links
17835 with a description part will be inlined. This can be nice for a quick
17836 look at those images, but it does not reflect what exported files will look
17837 like.
17838 When REFRESH is set, refresh existing images between BEG and END.
17839 This will create new image displays only if necessary.
17840 BEG and END default to the buffer boundaries."
17841 (interactive "P")
17842 (unless refresh
17843 (org-remove-inline-images)
17844 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17845 (save-excursion
17846 (save-restriction
17847 (widen)
17848 (setq beg (or beg (point-min)) end (or end (point-max)))
17849 (goto-char beg)
17850 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17851 (substring (org-image-file-name-regexp) 0 -2)
17852 "\\)\\]" (if include-linked "" "\\]")))
17853 old file ov img)
17854 (while (re-search-forward re end t)
17855 (setq old (get-char-property-and-overlay (match-beginning 1)
17856 'org-image-overlay))
17857 (setq file (expand-file-name
17858 (concat (or (match-string 3) "") (match-string 4))))
17859 (when (file-exists-p file)
17860 (if (and (car-safe old) refresh)
17861 (image-refresh (overlay-get (cdr old) 'display))
17862 (setq img (save-match-data (create-image file)))
17863 (when img
17864 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17865 (overlay-put ov 'display img)
17866 (overlay-put ov 'face 'default)
17867 (overlay-put ov 'org-image-overlay t)
17868 (overlay-put ov 'modification-hooks
17869 (list 'org-display-inline-remove-overlay))
17870 (push ov org-inline-image-overlays)))))))))
17872 (define-obsolete-function-alias
17873 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17875 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17876 "Remove inline-display overlay if a corresponding region is modified."
17877 (let ((inhibit-modification-hooks t))
17878 (when (and ov after)
17879 (delete ov org-inline-image-overlays)
17880 (delete-overlay ov))))
17882 (defun org-remove-inline-images ()
17883 "Remove inline display of images."
17884 (interactive)
17885 (mapc 'delete-overlay org-inline-image-overlays)
17886 (setq org-inline-image-overlays nil))
17888 ;;;; Key bindings
17890 ;; Outline functions from `outline-mode-prefix-map'
17891 ;; that can be remapped in Org:
17892 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17893 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17894 (define-key org-mode-map [remap outline-forward-same-level]
17895 'org-forward-heading-same-level)
17896 (define-key org-mode-map [remap outline-backward-same-level]
17897 'org-backward-heading-same-level)
17898 (define-key org-mode-map [remap show-branches]
17899 'org-kill-note-or-show-branches)
17900 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17901 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17902 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17904 ;; Outline functions from `outline-mode-prefix-map' that can not
17905 ;; be remapped in Org:
17907 ;; - the column "key binding" shows whether the Outline function is still
17908 ;; available in Org mode on the same key that it has been bound to in
17909 ;; Outline mode:
17910 ;; - "overridden": key used for a different functionality in Org mode
17911 ;; - else: key still bound to the same Outline function in Org mode
17913 ;; | Outline function | key binding | Org replacement |
17914 ;; |------------------------------------+-------------+-----------------------|
17915 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17916 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17917 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17918 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17919 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17920 ;; | `show-entry' | overridden | no replacement |
17921 ;; | `show-children' | `C-c C-i' | visibility cycling |
17922 ;; | `show-branches' | `C-c C-k' | still same function |
17923 ;; | `show-subtree' | overridden | visibility cycling |
17924 ;; | `show-all' | overridden | no replacement |
17925 ;; | `hide-subtree' | overridden | visibility cycling |
17926 ;; | `hide-body' | overridden | no replacement |
17927 ;; | `hide-entry' | overridden | visibility cycling |
17928 ;; | `hide-leaves' | overridden | no replacement |
17929 ;; | `hide-sublevels' | overridden | no replacement |
17930 ;; | `hide-other' | overridden | no replacement |
17932 ;; Make `C-c C-x' a prefix key
17933 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17935 ;; TAB key with modifiers
17936 (org-defkey org-mode-map "\C-i" 'org-cycle)
17937 (org-defkey org-mode-map [(tab)] 'org-cycle)
17938 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17939 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17940 ;; The following line is necessary under Suse GNU/Linux
17941 (unless (featurep 'xemacs)
17942 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17943 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17944 (define-key org-mode-map [backtab] 'org-shifttab)
17946 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17947 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17948 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17950 ;; Cursor keys with modifiers
17951 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17952 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17953 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17954 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17956 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17957 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17958 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17959 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17961 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17962 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17963 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17964 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17966 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17967 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17968 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17969 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17971 ;; Babel keys
17972 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17973 (mapc (lambda (pair)
17974 (define-key org-babel-map (car pair) (cdr pair)))
17975 org-babel-key-bindings)
17977 ;;; Extra keys for tty access.
17978 ;; We only set them when really needed because otherwise the
17979 ;; menus don't show the simple keys
17981 (when (or org-use-extra-keys
17982 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17983 (not window-system))
17984 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17985 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17986 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17987 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17988 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17989 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17990 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17991 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17992 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17993 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17994 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17995 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17996 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17997 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17998 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17999 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18000 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18001 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18002 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18003 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18004 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18005 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18006 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18007 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18008 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18009 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18010 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18011 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18013 ;; All the other keys
18015 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18016 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18017 (if (boundp 'narrow-map)
18018 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18019 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18020 (if (boundp 'narrow-map)
18021 (org-defkey narrow-map "b" 'org-narrow-to-block)
18022 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18023 (if (boundp 'narrow-map)
18024 (org-defkey narrow-map "e" 'org-narrow-to-element)
18025 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18026 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18027 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18028 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18029 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18030 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18031 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18032 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18033 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18034 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18035 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18036 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18037 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18038 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18039 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18040 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18041 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18042 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18043 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18044 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18045 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18046 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18047 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18048 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18049 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18050 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18051 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18052 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18053 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18054 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18055 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18056 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18057 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18058 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18059 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18060 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18061 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18062 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18063 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18064 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18065 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18066 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18067 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18068 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18069 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18070 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18071 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18072 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18073 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18074 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18075 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18076 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18077 (org-defkey org-mode-map "\C-c^" 'org-sort)
18078 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18079 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18080 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18081 (org-defkey org-mode-map "\C-m" 'org-return)
18082 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18083 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18084 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18085 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18086 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18087 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18088 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18089 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18090 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18091 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18092 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18093 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18094 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18095 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18096 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18097 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18098 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18099 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18100 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18101 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18102 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18103 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18104 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18106 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18107 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18108 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18110 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18111 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18112 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18113 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18114 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18115 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18116 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18117 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18118 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18119 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18120 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18121 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18122 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18123 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18124 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18125 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18126 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18127 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18128 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18129 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18130 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18131 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18133 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18134 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18135 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18136 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18137 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18139 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18141 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18143 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18144 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18146 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18149 (when (featurep 'xemacs)
18150 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18153 (defconst org-speed-commands-default
18155 ("Outline Navigation")
18156 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18157 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18158 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18159 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18160 ("u" . (org-speed-move-safe 'outline-up-heading))
18161 ("j" . org-goto)
18162 ("g" . (org-refile t))
18163 ("Outline Visibility")
18164 ("c" . org-cycle)
18165 ("C" . org-shifttab)
18166 (" " . org-display-outline-path)
18167 (":" . org-columns)
18168 ("Outline Structure Editing")
18169 ("U" . org-shiftmetaup)
18170 ("D" . org-shiftmetadown)
18171 ("r" . org-metaright)
18172 ("l" . org-metaleft)
18173 ("R" . org-shiftmetaright)
18174 ("L" . org-shiftmetaleft)
18175 ("i" . (progn (forward-char 1) (call-interactively
18176 'org-insert-heading-respect-content)))
18177 ("^" . org-sort)
18178 ("w" . org-refile)
18179 ("a" . org-archive-subtree-default-with-confirmation)
18180 ("." . org-mark-subtree)
18181 ("#" . org-toggle-comment)
18182 ("Clock Commands")
18183 ("I" . org-clock-in)
18184 ("O" . org-clock-out)
18185 ("Meta Data Editing")
18186 ("t" . org-todo)
18187 ("," . (org-priority))
18188 ("0" . (org-priority ?\ ))
18189 ("1" . (org-priority ?A))
18190 ("2" . (org-priority ?B))
18191 ("3" . (org-priority ?C))
18192 (";" . org-set-tags-command)
18193 ("e" . org-set-effort)
18194 ("E" . org-inc-effort)
18195 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18196 (org-entry-put (point) "APPT_WARNTIME" m)))
18197 ("Agenda Views etc")
18198 ("v" . org-agenda)
18199 ("/" . org-sparse-tree)
18200 ("Misc")
18201 ("o" . org-open-at-point)
18202 ("?" . org-speed-command-help)
18203 ("<" . (org-agenda-set-restriction-lock 'subtree))
18204 (">" . (org-agenda-remove-restriction-lock))
18206 "The default speed commands.")
18208 (defun org-print-speed-command (e)
18209 (if (> (length (car e)) 1)
18210 (progn
18211 (princ "\n")
18212 (princ (car e))
18213 (princ "\n")
18214 (princ (make-string (length (car e)) ?-))
18215 (princ "\n"))
18216 (princ (car e))
18217 (princ " ")
18218 (if (symbolp (cdr e))
18219 (princ (symbol-name (cdr e)))
18220 (prin1 (cdr e)))
18221 (princ "\n")))
18223 (defun org-speed-command-help ()
18224 "Show the available speed commands."
18225 (interactive)
18226 (if (not org-use-speed-commands)
18227 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18228 (with-output-to-temp-buffer "*Help*"
18229 (princ "User-defined Speed commands\n===========================\n")
18230 (mapc 'org-print-speed-command org-speed-commands-user)
18231 (princ "\n")
18232 (princ "Built-in Speed commands\n=======================\n")
18233 (mapc 'org-print-speed-command org-speed-commands-default))
18234 (with-current-buffer "*Help*"
18235 (setq truncate-lines t))))
18237 (defun org-speed-move-safe (cmd)
18238 "Execute CMD, but make sure that the cursor always ends up in a headline.
18239 If not, return to the original position and throw an error."
18240 (interactive)
18241 (let ((pos (point)))
18242 (call-interactively cmd)
18243 (unless (and (bolp) (org-at-heading-p))
18244 (goto-char pos)
18245 (error "Boundary reached while executing %s" cmd))))
18247 (defvar org-self-insert-command-undo-counter 0)
18249 (defvar org-table-auto-blank-field) ; defined in org-table.el
18250 (defvar org-speed-command nil)
18252 (define-obsolete-function-alias
18253 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18255 (defun org-speed-command-activate (keys)
18256 "Hook for activating single-letter speed commands.
18257 `org-speed-commands-default' specifies a minimal command set.
18258 Use `org-speed-commands-user' for further customization."
18259 (when (or (and (bolp) (looking-at org-outline-regexp))
18260 (and (functionp org-use-speed-commands)
18261 (funcall org-use-speed-commands)))
18262 (cdr (assoc keys (append org-speed-commands-user
18263 org-speed-commands-default)))))
18265 (define-obsolete-function-alias
18266 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18268 (defun org-babel-speed-command-activate (keys)
18269 "Hook for activating single-letter code block commands."
18270 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18271 (cdr (assoc keys org-babel-key-bindings))))
18273 (defcustom org-speed-command-hook
18274 '(org-speed-command-default-hook org-babel-speed-command-hook)
18275 "Hook for activating speed commands at strategic locations.
18276 Hook functions are called in sequence until a valid handler is
18277 found.
18279 Each hook takes a single argument, a user-pressed command key
18280 which is also a `self-insert-command' from the global map.
18282 Within the hook, examine the cursor position and the command key
18283 and return nil or a valid handler as appropriate. Handler could
18284 be one of an interactive command, a function, or a form.
18286 Set `org-use-speed-commands' to non-nil value to enable this
18287 hook. The default setting is `org-speed-command-activate'."
18288 :group 'org-structure
18289 :version "24.1"
18290 :type 'hook)
18292 (defun org-self-insert-command (N)
18293 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18294 If the cursor is in a table looking at whitespace, the whitespace is
18295 overwritten, and the table is not marked as requiring realignment."
18296 (interactive "p")
18297 (org-check-before-invisible-edit 'insert)
18298 (cond
18299 ((and org-use-speed-commands
18300 (setq org-speed-command
18301 (run-hook-with-args-until-success
18302 'org-speed-command-hook (this-command-keys))))
18303 (cond
18304 ((commandp org-speed-command)
18305 (setq this-command org-speed-command)
18306 (call-interactively org-speed-command))
18307 ((functionp org-speed-command)
18308 (funcall org-speed-command))
18309 ((and org-speed-command (listp org-speed-command))
18310 (eval org-speed-command))
18311 (t (let (org-use-speed-commands)
18312 (call-interactively 'org-self-insert-command)))))
18313 ((and
18314 (org-table-p)
18315 (progn
18316 ;; check if we blank the field, and if that triggers align
18317 (and (featurep 'org-table) org-table-auto-blank-field
18318 (member last-command
18319 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18320 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18321 ;; got extra space, this field does not determine column width
18322 (let (org-table-may-need-update) (org-table-blank-field))
18323 ;; no extra space, this field may determine column width
18324 (org-table-blank-field)))
18326 (eq N 1)
18327 (looking-at "[^|\n]* |"))
18328 (let (org-table-may-need-update)
18329 (goto-char (1- (match-end 0)))
18330 (backward-delete-char 1)
18331 (goto-char (match-beginning 0))
18332 (self-insert-command N)))
18334 (setq org-table-may-need-update t)
18335 (self-insert-command N)
18336 (org-fix-tags-on-the-fly)
18337 (if org-self-insert-cluster-for-undo
18338 (if (not (eq last-command 'org-self-insert-command))
18339 (setq org-self-insert-command-undo-counter 1)
18340 (if (>= org-self-insert-command-undo-counter 20)
18341 (setq org-self-insert-command-undo-counter 1)
18342 (and (> org-self-insert-command-undo-counter 0)
18343 buffer-undo-list (listp buffer-undo-list)
18344 (not (cadr buffer-undo-list)) ; remove nil entry
18345 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18346 (setq org-self-insert-command-undo-counter
18347 (1+ org-self-insert-command-undo-counter))))))))
18349 (defun org-check-before-invisible-edit (kind)
18350 "Check is editing if kind KIND would be dangerous with invisible text around.
18351 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18352 ;; First, try to get out of here as quickly as possible, to reduce overhead
18353 (if (and org-catch-invisible-edits
18354 (or (not (boundp 'visible-mode)) (not visible-mode))
18355 (or (get-char-property (point) 'invisible)
18356 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18357 ;; OK, we need to take a closer look
18358 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18359 (invisible-before-point (if (bobp) nil (get-char-property
18360 (1- (point)) 'invisible)))
18361 (border-and-ok-direction
18363 ;; Check if we are acting predictably before invisible text
18364 (and invisible-at-point (not invisible-before-point)
18365 (memq kind '(insert delete-backward)))
18366 ;; Check if we are acting predictably after invisible text
18367 ;; This works not well, and I have turned it off. It seems
18368 ;; better to always show and stop after invisible text.
18369 ;; (and (not invisible-at-point) invisible-before-point
18370 ;; (memq kind '(insert delete)))
18372 (when (or (memq invisible-at-point '(outline org-hide-block t))
18373 (memq invisible-before-point '(outline org-hide-block t)))
18374 (if (eq org-catch-invisible-edits 'error)
18375 (error "Editing in invisible areas is prohibited - make visible first"))
18376 (if (and org-custom-properties-overlays
18377 (y-or-n-p "Display invisible properties in this buffer? "))
18378 (org-toggle-custom-properties-visibility)
18379 ;; Make the area visible
18380 (save-excursion
18381 (if invisible-before-point
18382 (goto-char (previous-single-char-property-change
18383 (point) 'invisible)))
18384 (org-cycle))
18385 (cond
18386 ((eq org-catch-invisible-edits 'show)
18387 ;; That's it, we do the edit after showing
18388 (message
18389 "Unfolding invisible region around point before editing")
18390 (sit-for 1))
18391 ((and (eq org-catch-invisible-edits 'smart)
18392 border-and-ok-direction)
18393 (message "Unfolding invisible region around point before editing"))
18395 ;; Don't do the edit, make the user repeat it in full visibility
18396 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18398 (defun org-fix-tags-on-the-fly ()
18399 (when (and (equal (char-after (point-at-bol)) ?*)
18400 (org-at-heading-p))
18401 (org-align-tags-here org-tags-column)))
18403 (defun org-delete-backward-char (N)
18404 "Like `delete-backward-char', insert whitespace at field end in tables.
18405 When deleting backwards, in tables this function will insert whitespace in
18406 front of the next \"|\" separator, to keep the table aligned. The table will
18407 still be marked for re-alignment if the field did fill the entire column,
18408 because, in this case the deletion might narrow the column."
18409 (interactive "p")
18410 (org-check-before-invisible-edit 'delete-backward)
18411 (if (and (org-table-p)
18412 (eq N 1)
18413 (string-match "|" (buffer-substring (point-at-bol) (point)))
18414 (looking-at ".*?|"))
18415 (let ((pos (point))
18416 (noalign (looking-at "[^|\n\r]* |"))
18417 (c org-table-may-need-update))
18418 (backward-delete-char N)
18419 (if (not overwrite-mode)
18420 (progn
18421 (skip-chars-forward "^|")
18422 (insert " ")
18423 (goto-char (1- pos))))
18424 ;; noalign: if there were two spaces at the end, this field
18425 ;; does not determine the width of the column.
18426 (if noalign (setq org-table-may-need-update c)))
18427 (backward-delete-char N)
18428 (org-fix-tags-on-the-fly)))
18430 (defun org-delete-char (N)
18431 "Like `delete-char', but insert whitespace at field end in tables.
18432 When deleting characters, in tables this function will insert whitespace in
18433 front of the next \"|\" separator, to keep the table aligned. The table will
18434 still be marked for re-alignment if the field did fill the entire column,
18435 because, in this case the deletion might narrow the column."
18436 (interactive "p")
18437 (org-check-before-invisible-edit 'delete)
18438 (if (and (org-table-p)
18439 (not (bolp))
18440 (not (= (char-after) ?|))
18441 (eq N 1))
18442 (if (looking-at ".*?|")
18443 (let ((pos (point))
18444 (noalign (looking-at "[^|\n\r]* |"))
18445 (c org-table-may-need-update))
18446 (replace-match (concat
18447 (substring (match-string 0) 1 -1)
18448 " |"))
18449 (goto-char pos)
18450 ;; noalign: if there were two spaces at the end, this field
18451 ;; does not determine the width of the column.
18452 (if noalign (setq org-table-may-need-update c)))
18453 (delete-char N))
18454 (delete-char N)
18455 (org-fix-tags-on-the-fly)))
18457 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18458 (put 'org-self-insert-command 'delete-selection t)
18459 (put 'orgtbl-self-insert-command 'delete-selection t)
18460 (put 'org-delete-char 'delete-selection 'supersede)
18461 (put 'org-delete-backward-char 'delete-selection 'supersede)
18462 (put 'org-yank 'delete-selection 'yank)
18464 ;; Make `flyspell-mode' delay after some commands
18465 (put 'org-self-insert-command 'flyspell-delayed t)
18466 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18467 (put 'org-delete-char 'flyspell-delayed t)
18468 (put 'org-delete-backward-char 'flyspell-delayed t)
18470 ;; Make pabbrev-mode expand after org-mode commands
18471 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18472 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18474 ;; How to do this: Measure non-white length of current string
18475 ;; If equal to column width, we should realign.
18477 (defun org-remap (map &rest commands)
18478 "In MAP, remap the functions given in COMMANDS.
18479 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18480 (let (new old)
18481 (while commands
18482 (setq old (pop commands) new (pop commands))
18483 (if (fboundp 'command-remapping)
18484 (org-defkey map (vector 'remap old) new)
18485 (substitute-key-definition old new map global-map)))))
18487 (when (eq org-enable-table-editor 'optimized)
18488 ;; If the user wants maximum table support, we need to hijack
18489 ;; some standard editing functions
18490 (org-remap org-mode-map
18491 'self-insert-command 'org-self-insert-command
18492 'delete-char 'org-delete-char
18493 'delete-backward-char 'org-delete-backward-char)
18494 (org-defkey org-mode-map "|" 'org-force-self-insert))
18496 (defvar org-ctrl-c-ctrl-c-hook nil
18497 "Hook for functions attaching themselves to `C-c C-c'.
18499 This can be used to add additional functionality to the C-c C-c
18500 key which executes context-dependent commands. This hook is run
18501 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18502 run after the last test.
18504 Each function will be called with no arguments. The function
18505 must check if the context is appropriate for it to act. If yes,
18506 it should do its thing and then return a non-nil value. If the
18507 context is wrong, just do nothing and return nil.")
18509 (defvar org-ctrl-c-ctrl-c-final-hook nil
18510 "Hook for functions attaching themselves to `C-c C-c'.
18512 This can be used to add additional functionality to the C-c C-c
18513 key which executes context-dependent commands. This hook is run
18514 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18515 before the first test.
18517 Each function will be called with no arguments. The function
18518 must check if the context is appropriate for it to act. If yes,
18519 it should do its thing and then return a non-nil value. If the
18520 context is wrong, just do nothing and return nil.")
18522 (defvar org-tab-first-hook nil
18523 "Hook for functions to attach themselves to TAB.
18524 See `org-ctrl-c-ctrl-c-hook' for more information.
18525 This hook runs as the first action when TAB is pressed, even before
18526 `org-cycle' messes around with the `outline-regexp' to cater for
18527 inline tasks and plain list item folding.
18528 If any function in this hook returns t, any other actions that
18529 would have been caused by TAB (such as table field motion or visibility
18530 cycling) will not occur.")
18532 (defvar org-tab-after-check-for-table-hook nil
18533 "Hook for functions to attach themselves to TAB.
18534 See `org-ctrl-c-ctrl-c-hook' for more information.
18535 This hook runs after it has been established that the cursor is not in a
18536 table, but before checking if the cursor is in a headline or if global cycling
18537 should be done.
18538 If any function in this hook returns t, not other actions like visibility
18539 cycling will be done.")
18541 (defvar org-tab-after-check-for-cycling-hook nil
18542 "Hook for functions to attach themselves to TAB.
18543 See `org-ctrl-c-ctrl-c-hook' for more information.
18544 This hook runs after it has been established that not table field motion and
18545 not visibility should be done because of current context. This is probably
18546 the place where a package like yasnippets can hook in.")
18548 (defvar org-tab-before-tab-emulation-hook nil
18549 "Hook for functions to attach themselves to TAB.
18550 See `org-ctrl-c-ctrl-c-hook' for more information.
18551 This hook runs after every other options for TAB have been exhausted, but
18552 before indentation and \t insertion takes place.")
18554 (defvar org-metaleft-hook nil
18555 "Hook for functions attaching themselves to `M-left'.
18556 See `org-ctrl-c-ctrl-c-hook' for more information.")
18557 (defvar org-metaright-hook nil
18558 "Hook for functions attaching themselves to `M-right'.
18559 See `org-ctrl-c-ctrl-c-hook' for more information.")
18560 (defvar org-metaup-hook nil
18561 "Hook for functions attaching themselves to `M-up'.
18562 See `org-ctrl-c-ctrl-c-hook' for more information.")
18563 (defvar org-metadown-hook nil
18564 "Hook for functions attaching themselves to `M-down'.
18565 See `org-ctrl-c-ctrl-c-hook' for more information.")
18566 (defvar org-shiftmetaleft-hook nil
18567 "Hook for functions attaching themselves to `M-S-left'.
18568 See `org-ctrl-c-ctrl-c-hook' for more information.")
18569 (defvar org-shiftmetaright-hook nil
18570 "Hook for functions attaching themselves to `M-S-right'.
18571 See `org-ctrl-c-ctrl-c-hook' for more information.")
18572 (defvar org-shiftmetaup-hook nil
18573 "Hook for functions attaching themselves to `M-S-up'.
18574 See `org-ctrl-c-ctrl-c-hook' for more information.")
18575 (defvar org-shiftmetadown-hook nil
18576 "Hook for functions attaching themselves to `M-S-down'.
18577 See `org-ctrl-c-ctrl-c-hook' for more information.")
18578 (defvar org-metareturn-hook nil
18579 "Hook for functions attaching themselves to `M-RET'.
18580 See `org-ctrl-c-ctrl-c-hook' for more information.")
18581 (defvar org-shiftup-hook nil
18582 "Hook for functions attaching themselves to `S-up'.
18583 See `org-ctrl-c-ctrl-c-hook' for more information.")
18584 (defvar org-shiftup-final-hook nil
18585 "Hook for functions attaching themselves to `S-up'.
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-shiftdown-hook nil
18589 "Hook for functions attaching themselves to `S-down'.
18590 See `org-ctrl-c-ctrl-c-hook' for more information.")
18591 (defvar org-shiftdown-final-hook nil
18592 "Hook for functions attaching themselves to `S-down'.
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.")
18595 (defvar org-shiftleft-hook nil
18596 "Hook for functions attaching themselves to `S-left'.
18597 See `org-ctrl-c-ctrl-c-hook' for more information.")
18598 (defvar org-shiftleft-final-hook nil
18599 "Hook for functions attaching themselves to `S-left'.
18600 This one runs after all other options except shift-select have been excluded.
18601 See `org-ctrl-c-ctrl-c-hook' for more information.")
18602 (defvar org-shiftright-hook nil
18603 "Hook for functions attaching themselves to `S-right'.
18604 See `org-ctrl-c-ctrl-c-hook' for more information.")
18605 (defvar org-shiftright-final-hook nil
18606 "Hook for functions attaching themselves to `S-right'.
18607 This one runs after all other options except shift-select have been excluded.
18608 See `org-ctrl-c-ctrl-c-hook' for more information.")
18610 (defun org-modifier-cursor-error ()
18611 "Throw an error, a modified cursor command was applied in wrong context."
18612 (error "This command is active in special context like tables, headlines or items"))
18614 (defun org-shiftselect-error ()
18615 "Throw an error because Shift-Cursor command was applied in wrong context."
18616 (if (and (boundp 'shift-select-mode) shift-select-mode)
18617 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18618 (error "This command works only in special context like headlines or timestamps")))
18620 (defun org-call-for-shift-select (cmd)
18621 (let ((this-command-keys-shift-translated t))
18622 (call-interactively cmd)))
18624 (defun org-shifttab (&optional arg)
18625 "Global visibility cycling or move to previous table field.
18626 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18627 on context.
18628 See the individual commands for more information."
18629 (interactive "P")
18630 (cond
18631 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18632 ((integerp arg)
18633 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18634 (message "Content view to level: %d" arg)
18635 (org-content (prefix-numeric-value arg2))
18636 (setq org-cycle-global-status 'overview)))
18637 (t (call-interactively 'org-global-cycle))))
18639 (defun org-shiftmetaleft ()
18640 "Promote subtree or delete table column.
18641 Calls `org-promote-subtree', `org-outdent-item-tree', or
18642 `org-table-delete-column', depending on context. See the
18643 individual commands for more information."
18644 (interactive)
18645 (cond
18646 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18647 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18648 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18649 ((if (not (org-region-active-p)) (org-at-item-p)
18650 (save-excursion (goto-char (region-beginning))
18651 (org-at-item-p)))
18652 (call-interactively 'org-outdent-item-tree))
18653 (t (org-modifier-cursor-error))))
18655 (defun org-shiftmetaright ()
18656 "Demote subtree or insert table column.
18657 Calls `org-demote-subtree', `org-indent-item-tree', or
18658 `org-table-insert-column', depending on context. See the
18659 individual commands for more information."
18660 (interactive)
18661 (cond
18662 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18663 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18664 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18665 ((if (not (org-region-active-p)) (org-at-item-p)
18666 (save-excursion (goto-char (region-beginning))
18667 (org-at-item-p)))
18668 (call-interactively 'org-indent-item-tree))
18669 (t (org-modifier-cursor-error))))
18671 (defun org-shiftmetaup (&optional arg)
18672 "Move subtree up or kill table row.
18673 Calls `org-move-subtree-up' or `org-table-kill-row' or
18674 `org-move-item-up' or `org-timestamp-up', depending on context.
18675 See the individual commands for more information."
18676 (interactive "P")
18677 (cond
18678 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18679 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18680 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18681 ((org-at-item-p) (call-interactively 'org-move-item-up))
18682 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18683 (call-interactively 'org-timestamp-up)))
18684 (t (org-modifier-cursor-error))))
18686 (defun org-shiftmetadown (&optional arg)
18687 "Move subtree down or insert table row.
18688 Calls `org-move-subtree-down' or `org-table-insert-row' or
18689 `org-move-item-down' or `org-timestamp-up', depending on context.
18690 See the individual commands for more information."
18691 (interactive "P")
18692 (cond
18693 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18694 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18695 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18696 ((org-at-item-p) (call-interactively 'org-move-item-down))
18697 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18698 (call-interactively 'org-timestamp-down)))
18699 (t (org-modifier-cursor-error))))
18701 (defsubst org-hidden-tree-error ()
18702 (error
18703 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18705 (defun org-metaleft (&optional arg)
18706 "Promote heading or move table column to left.
18707 Calls `org-do-promote' or `org-table-move-column', depending on context.
18708 With no specific context, calls the Emacs default `backward-word'.
18709 See the individual commands for more information."
18710 (interactive "P")
18711 (cond
18712 ((run-hook-with-args-until-success 'org-metaleft-hook))
18713 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18714 ((org-with-limited-levels
18715 (or (org-at-heading-p)
18716 (and (org-region-active-p)
18717 (save-excursion
18718 (goto-char (region-beginning))
18719 (org-at-heading-p)))))
18720 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18721 (call-interactively 'org-do-promote))
18722 ;; At an inline task.
18723 ((org-at-heading-p)
18724 (call-interactively 'org-inlinetask-promote))
18725 ((or (org-at-item-p)
18726 (and (org-region-active-p)
18727 (save-excursion
18728 (goto-char (region-beginning))
18729 (org-at-item-p))))
18730 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18731 (call-interactively 'org-outdent-item))
18732 (t (call-interactively 'backward-word))))
18734 (defun org-metaright (&optional arg)
18735 "Demote a subtree, a list item or move table column to right.
18736 In front of a drawer or a block keyword, indent it correctly.
18737 With no specific context, calls the Emacs default `forward-word'.
18738 See the individual commands for more information."
18739 (interactive "P")
18740 (cond
18741 ((run-hook-with-args-until-success 'org-metaright-hook))
18742 ((org-at-table-p) (call-interactively 'org-table-move-column))
18743 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18744 ((org-at-block-p) (call-interactively 'org-indent-block))
18745 ((org-with-limited-levels
18746 (or (org-at-heading-p)
18747 (and (org-region-active-p)
18748 (save-excursion
18749 (goto-char (region-beginning))
18750 (org-at-heading-p)))))
18751 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18752 (call-interactively 'org-do-demote))
18753 ;; At an inline task.
18754 ((org-at-heading-p)
18755 (call-interactively 'org-inlinetask-demote))
18756 ((or (org-at-item-p)
18757 (and (org-region-active-p)
18758 (save-excursion
18759 (goto-char (region-beginning))
18760 (org-at-item-p))))
18761 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18762 (call-interactively 'org-indent-item))
18763 (t (call-interactively 'forward-word))))
18765 (defun org-check-for-hidden (what)
18766 "Check if there are hidden headlines/items in the current visual line.
18767 WHAT can be either `headlines' or `items'. If the current line is
18768 an outline or item heading and it has a folded subtree below it,
18769 this function returns t, nil otherwise."
18770 (let ((re (cond
18771 ((eq what 'headlines) org-outline-regexp-bol)
18772 ((eq what 'items) (org-item-beginning-re))
18773 (t (error "This should not happen"))))
18774 beg end)
18775 (save-excursion
18776 (catch 'exit
18777 (unless (org-region-active-p)
18778 (setq beg (point-at-bol))
18779 (beginning-of-line 2)
18780 (while (and (not (eobp)) ;; this is like `next-line'
18781 (get-char-property (1- (point)) 'invisible))
18782 (beginning-of-line 2))
18783 (setq end (point))
18784 (goto-char beg)
18785 (goto-char (point-at-eol))
18786 (setq end (max end (point)))
18787 (while (re-search-forward re end t)
18788 (if (get-char-property (match-beginning 0) 'invisible)
18789 (throw 'exit t))))
18790 nil))))
18792 (autoload 'org-element-at-point "org-element")
18794 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18795 (declare-function org-element-type "org-element" (element))
18796 (declare-function org-element-context "org-element" ())
18797 (declare-function org-element-contents "org-element" (element))
18798 (declare-function org-element-property "org-element" (property element))
18799 (declare-function org-element-paragraph-parser "org-element" (limit))
18800 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18801 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18802 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18803 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18804 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18806 (defun org-metaup (&optional arg)
18807 "Move subtree up or move table row up.
18808 Calls `org-move-subtree-up' or `org-table-move-row' or
18809 `org-move-item-up', depending on context. See the individual commands
18810 for more information."
18811 (interactive "P")
18812 (cond
18813 ((run-hook-with-args-until-success 'org-metaup-hook))
18814 ((org-region-active-p)
18815 (let* ((a (min (region-beginning) (region-end)))
18816 (b (1- (max (region-beginning) (region-end))))
18817 (c (save-excursion (goto-char a)
18818 (move-beginning-of-line 0)))
18819 (d (save-excursion (goto-char a)
18820 (move-end-of-line 0) (point))))
18821 (transpose-regions a b c d)
18822 (goto-char c)))
18823 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18824 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18825 ((org-at-item-p) (call-interactively 'org-move-item-up))
18826 (t (org-drag-element-backward))))
18828 (defun org-metadown (&optional arg)
18829 "Move subtree down or move table row down.
18830 Calls `org-move-subtree-down' or `org-table-move-row' or
18831 `org-move-item-down', depending on context. See the individual
18832 commands for more information."
18833 (interactive "P")
18834 (cond
18835 ((run-hook-with-args-until-success 'org-metadown-hook))
18836 ((org-region-active-p)
18837 (let* ((a (min (region-beginning) (region-end)))
18838 (b (max (region-beginning) (region-end)))
18839 (c (save-excursion (goto-char b)
18840 (move-beginning-of-line 1)))
18841 (d (save-excursion (goto-char b)
18842 (move-end-of-line 1) (1+ (point)))))
18843 (transpose-regions a b c d)
18844 (goto-char d)))
18845 ((org-at-table-p) (call-interactively 'org-table-move-row))
18846 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18847 ((org-at-item-p) (call-interactively 'org-move-item-down))
18848 (t (org-drag-element-forward))))
18850 (defun org-shiftup (&optional arg)
18851 "Increase item in timestamp or increase priority of current headline.
18852 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18853 depending on context. See the individual commands for more information."
18854 (interactive "P")
18855 (cond
18856 ((run-hook-with-args-until-success 'org-shiftup-hook))
18857 ((and org-support-shift-select (org-region-active-p))
18858 (org-call-for-shift-select 'previous-line))
18859 ((org-at-timestamp-p t)
18860 (call-interactively (if org-edit-timestamp-down-means-later
18861 'org-timestamp-down 'org-timestamp-up)))
18862 ((and (not (eq org-support-shift-select 'always))
18863 org-enable-priority-commands
18864 (org-at-heading-p))
18865 (call-interactively 'org-priority-up))
18866 ((and (not org-support-shift-select) (org-at-item-p))
18867 (call-interactively 'org-previous-item))
18868 ((org-clocktable-try-shift 'up arg))
18869 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18870 (org-support-shift-select
18871 (org-call-for-shift-select 'previous-line))
18872 (t (org-shiftselect-error))))
18874 (defun org-shiftdown (&optional arg)
18875 "Decrease item in timestamp or decrease priority of current headline.
18876 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18877 depending on context. See the individual commands for more information."
18878 (interactive "P")
18879 (cond
18880 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18881 ((and org-support-shift-select (org-region-active-p))
18882 (org-call-for-shift-select 'next-line))
18883 ((org-at-timestamp-p t)
18884 (call-interactively (if org-edit-timestamp-down-means-later
18885 'org-timestamp-up 'org-timestamp-down)))
18886 ((and (not (eq org-support-shift-select 'always))
18887 org-enable-priority-commands
18888 (org-at-heading-p))
18889 (call-interactively 'org-priority-down))
18890 ((and (not org-support-shift-select) (org-at-item-p))
18891 (call-interactively 'org-next-item))
18892 ((org-clocktable-try-shift 'down arg))
18893 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18894 (org-support-shift-select
18895 (org-call-for-shift-select 'next-line))
18896 (t (org-shiftselect-error))))
18898 (defun org-shiftright (&optional arg)
18899 "Cycle the thing at point or in the current line, depending on context.
18900 Depending on context, this does one of the following:
18902 - switch a timestamp at point one day into the future
18903 - on a headline, switch to the next TODO keyword.
18904 - on an item, switch entire list to the next bullet type
18905 - on a property line, switch to the next allowed value
18906 - on a clocktable definition line, move time block into the future"
18907 (interactive "P")
18908 (cond
18909 ((run-hook-with-args-until-success 'org-shiftright-hook))
18910 ((and org-support-shift-select (org-region-active-p))
18911 (org-call-for-shift-select 'forward-char))
18912 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18913 ((and (not (eq org-support-shift-select 'always))
18914 (org-at-heading-p))
18915 (let ((org-inhibit-logging
18916 (not org-treat-S-cursor-todo-selection-as-state-change))
18917 (org-inhibit-blocking
18918 (not org-treat-S-cursor-todo-selection-as-state-change)))
18919 (org-call-with-arg 'org-todo 'right)))
18920 ((or (and org-support-shift-select
18921 (not (eq org-support-shift-select 'always))
18922 (org-at-item-bullet-p))
18923 (and (not org-support-shift-select) (org-at-item-p)))
18924 (org-call-with-arg 'org-cycle-list-bullet nil))
18925 ((and (not (eq org-support-shift-select 'always))
18926 (org-at-property-p))
18927 (call-interactively 'org-property-next-allowed-value))
18928 ((org-clocktable-try-shift 'right arg))
18929 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18930 (org-support-shift-select
18931 (org-call-for-shift-select 'forward-char))
18932 (t (org-shiftselect-error))))
18934 (defun org-shiftleft (&optional arg)
18935 "Cycle the thing at point or in the current line, depending on context.
18936 Depending on context, this does one of the following:
18938 - switch a timestamp at point one day into the past
18939 - on a headline, switch to the previous TODO keyword.
18940 - on an item, switch entire list to the previous bullet type
18941 - on a property line, switch to the previous allowed value
18942 - on a clocktable definition line, move time block into the past"
18943 (interactive "P")
18944 (cond
18945 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18946 ((and org-support-shift-select (org-region-active-p))
18947 (org-call-for-shift-select 'backward-char))
18948 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18949 ((and (not (eq org-support-shift-select 'always))
18950 (org-at-heading-p))
18951 (let ((org-inhibit-logging
18952 (not org-treat-S-cursor-todo-selection-as-state-change))
18953 (org-inhibit-blocking
18954 (not org-treat-S-cursor-todo-selection-as-state-change)))
18955 (org-call-with-arg 'org-todo 'left)))
18956 ((or (and org-support-shift-select
18957 (not (eq org-support-shift-select 'always))
18958 (org-at-item-bullet-p))
18959 (and (not org-support-shift-select) (org-at-item-p)))
18960 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18961 ((and (not (eq org-support-shift-select 'always))
18962 (org-at-property-p))
18963 (call-interactively 'org-property-previous-allowed-value))
18964 ((org-clocktable-try-shift 'left arg))
18965 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18966 (org-support-shift-select
18967 (org-call-for-shift-select 'backward-char))
18968 (t (org-shiftselect-error))))
18970 (defun org-shiftcontrolright ()
18971 "Switch to next TODO set."
18972 (interactive)
18973 (cond
18974 ((and org-support-shift-select (org-region-active-p))
18975 (org-call-for-shift-select 'forward-word))
18976 ((and (not (eq org-support-shift-select 'always))
18977 (org-at-heading-p))
18978 (org-call-with-arg 'org-todo 'nextset))
18979 (org-support-shift-select
18980 (org-call-for-shift-select 'forward-word))
18981 (t (org-shiftselect-error))))
18983 (defun org-shiftcontrolleft ()
18984 "Switch to previous TODO set."
18985 (interactive)
18986 (cond
18987 ((and org-support-shift-select (org-region-active-p))
18988 (org-call-for-shift-select 'backward-word))
18989 ((and (not (eq org-support-shift-select 'always))
18990 (org-at-heading-p))
18991 (org-call-with-arg 'org-todo 'previousset))
18992 (org-support-shift-select
18993 (org-call-for-shift-select 'backward-word))
18994 (t (org-shiftselect-error))))
18996 (defun org-shiftcontrolup ()
18997 "Change timestamps synchronously up in CLOCK log lines."
18998 (interactive)
18999 (cond ((and (not org-support-shift-select)
19000 (org-at-clock-log-p)
19001 (org-at-timestamp-p t))
19002 (org-clock-timestamps-up))
19003 (t (org-shiftselect-error))))
19005 (defun org-shiftcontroldown ()
19006 "Change timestamps synchronously down in CLOCK log lines."
19007 (interactive)
19008 (cond ((and (not org-support-shift-select)
19009 (org-at-clock-log-p)
19010 (org-at-timestamp-p t))
19011 (org-clock-timestamps-down))
19012 (t (org-shiftselect-error))))
19014 (defun org-ctrl-c-ret ()
19015 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19016 (interactive)
19017 (cond
19018 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19019 (t (call-interactively 'org-insert-heading))))
19021 (defun org-find-visible ()
19022 (let ((s (point)))
19023 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19024 (get-char-property s 'invisible)))
19026 (defun org-find-invisible ()
19027 (let ((s (point)))
19028 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19029 (not (get-char-property s 'invisible))))
19032 (defun org-copy-visible (beg end)
19033 "Copy the visible parts of the region."
19034 (interactive "r")
19035 (let (snippets s)
19036 (save-excursion
19037 (save-restriction
19038 (narrow-to-region beg end)
19039 (setq s (goto-char (point-min)))
19040 (while (not (= (point) (point-max)))
19041 (goto-char (org-find-invisible))
19042 (push (buffer-substring s (point)) snippets)
19043 (setq s (goto-char (org-find-visible))))))
19044 (kill-new (apply 'concat (nreverse snippets)))))
19046 (defun org-copy-special ()
19047 "Copy region in table or copy current subtree.
19048 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19049 See the individual commands for more information."
19050 (interactive)
19051 (call-interactively
19052 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19054 (defun org-cut-special ()
19055 "Cut region in table or cut current subtree.
19056 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19057 See the individual commands for more information."
19058 (interactive)
19059 (call-interactively
19060 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19062 (defun org-paste-special (arg)
19063 "Paste rectangular region into table, or past subtree relative to level.
19064 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19065 See the individual commands for more information."
19066 (interactive "P")
19067 (if (org-at-table-p)
19068 (org-table-paste-rectangle)
19069 (org-paste-subtree arg)))
19071 (defun org-edit-special (&optional arg)
19072 "Call a special editor for the stuff at point.
19073 When at a table, call the formula editor with `org-table-edit-formulas'.
19074 When at the first line of an src example, call `org-edit-src-code'.
19075 When in an #+include line, visit the include file. Otherwise call
19076 `ffap' to visit the file at point."
19077 (interactive)
19078 ;; possibly prep session before editing source
19079 (when arg
19080 (let* ((info (org-babel-get-src-block-info))
19081 (lang (nth 0 info))
19082 (params (nth 2 info))
19083 (session (cdr (assoc :session params))))
19084 (when (and info session) ;; we are in a source-code block with a session
19085 (funcall
19086 (intern (concat "org-babel-prep-session:" lang)) session params))))
19087 (cond ;; proceed with `org-edit-special'
19088 ((save-excursion
19089 (beginning-of-line 1)
19090 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19091 (find-file (org-trim (match-string 1))))
19092 ((org-edit-src-code))
19093 ((org-edit-fixed-width-region))
19094 ((org-at-table.el-p)
19095 (org-edit-src-code))
19096 ((or (org-at-table-p)
19097 (save-excursion
19098 (beginning-of-line 1)
19099 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19100 (call-interactively 'org-table-edit-formulas))
19101 (t (call-interactively 'ffap))))
19103 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19104 (defun org-ctrl-c-ctrl-c (&optional arg)
19105 "Set tags in headline, or update according to changed information at point.
19107 This command does many different things, depending on context:
19109 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19110 this is what we do.
19112 - If the cursor is on a statistics cookie, update it.
19114 - If the cursor is in a headline, prompt for tags and insert them
19115 into the current line, aligned to `org-tags-column'. When called
19116 with prefix arg, realign all tags in the current buffer.
19118 - If the cursor is in one of the special #+KEYWORD lines, this
19119 triggers scanning the buffer for these lines and updating the
19120 information.
19122 - If the cursor is inside a table, realign the table. This command
19123 works even if the automatic table editor has been turned off.
19125 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19126 the entire table.
19128 - If the cursor is at a footnote reference or definition, jump to
19129 the corresponding definition or references, respectively.
19131 - If the cursor is a the beginning of a dynamic block, update it.
19133 - If the current buffer is a capture buffer, close note and file it.
19135 - If the cursor is on a <<<target>>>, update radio targets and
19136 corresponding links in this buffer.
19138 - If the cursor is on a numbered item in a plain list, renumber the
19139 ordered list.
19141 - If the cursor is on a checkbox, toggle it.
19143 - If the cursor is on a code block, evaluate it. The variable
19144 `org-confirm-babel-evaluate' can be used to control prompting
19145 before code block evaluation, by default every code block
19146 evaluation requires confirmation. Code block evaluation can be
19147 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19148 (interactive "P")
19149 (let ((org-enable-table-editor t))
19150 (cond
19151 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19152 org-occur-highlights
19153 org-latex-fragment-image-overlays)
19154 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19155 (org-remove-occur-highlights)
19156 (org-remove-latex-fragment-image-overlays)
19157 (message "Temporary highlights/overlays removed from current buffer"))
19158 ((and (local-variable-p 'org-finish-function (current-buffer))
19159 (fboundp org-finish-function))
19160 (funcall org-finish-function))
19161 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19162 ((org-in-regexp org-ts-regexp-both)
19163 (org-timestamp-change 0 'day))
19164 ((or (looking-at org-property-start-re)
19165 (org-at-property-p))
19166 (call-interactively 'org-property-action))
19167 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19168 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19169 (or (org-at-heading-p) (org-at-item-p)))
19170 (call-interactively 'org-update-statistics-cookies))
19171 ((org-at-heading-p) (call-interactively 'org-set-tags))
19172 ((org-at-table.el-p)
19173 (message "Use C-c ' to edit table.el tables"))
19174 ((org-at-table-p)
19175 (org-table-maybe-eval-formula)
19176 (if arg
19177 (call-interactively 'org-table-recalculate)
19178 (org-table-maybe-recalculate-line))
19179 (call-interactively 'org-table-align)
19180 (orgtbl-send-table 'maybe))
19181 ((or (org-footnote-at-reference-p)
19182 (org-footnote-at-definition-p))
19183 (call-interactively 'org-footnote-action))
19184 ((org-at-item-checkbox-p)
19185 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19186 ;; list only if at top item.
19187 (let* ((cbox (match-string 1))
19188 (struct (org-list-struct))
19189 (old-struct (copy-tree struct))
19190 (parents (org-list-parents-alist struct))
19191 (orderedp (org-entry-get nil "ORDERED"))
19192 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19193 block-item)
19194 ;; Use a light version of `org-toggle-checkbox' to avoid
19195 ;; computing list structure twice.
19196 (let ((new-box (cond
19197 ((equal arg '(16)) "[-]")
19198 ((equal arg '(4)) nil)
19199 ((equal "[X]" cbox) "[ ]")
19200 (t "[X]"))))
19201 (if (and firstp arg)
19202 ;; If at first item of sub-list, remove check-box from
19203 ;; every item at the same level.
19204 (mapc
19205 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19206 (org-list-get-all-items
19207 (point-at-bol) struct (org-list-prevs-alist struct)))
19208 (org-list-set-checkbox (point-at-bol) struct new-box)))
19209 ;; Replicate `org-list-write-struct', while grabbing a return
19210 ;; value from `org-list-struct-fix-box'.
19211 (org-list-struct-fix-ind struct parents 2)
19212 (org-list-struct-fix-item-end struct)
19213 (let ((prevs (org-list-prevs-alist struct)))
19214 (org-list-struct-fix-bul struct prevs)
19215 (org-list-struct-fix-ind struct parents)
19216 (setq block-item
19217 (org-list-struct-fix-box struct parents prevs orderedp)))
19218 (org-list-struct-apply-struct struct old-struct)
19219 (org-update-checkbox-count-maybe)
19220 (when block-item
19221 (message
19222 "Checkboxes were removed due to unchecked box at line %d"
19223 (org-current-line block-item)))
19224 (when firstp (org-list-send-list 'maybe))))
19225 ((org-at-item-p)
19226 ;; Cursor at an item: repair list. Do checkbox related actions
19227 ;; only if function was called with an argument. Send list only
19228 ;; if at top item.
19229 (let* ((struct (org-list-struct))
19230 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19231 old-struct)
19232 (when arg
19233 (setq old-struct (copy-tree struct))
19234 (if firstp
19235 ;; If at first item of sub-list, add check-box to every
19236 ;; item at the same level.
19237 (mapc
19238 (lambda (pos)
19239 (unless (org-list-get-checkbox pos struct)
19240 (org-list-set-checkbox pos struct "[ ]")))
19241 (org-list-get-all-items
19242 (point-at-bol) struct (org-list-prevs-alist struct)))
19243 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19244 (org-list-write-struct
19245 struct (org-list-parents-alist struct) old-struct)
19246 (when arg (org-update-checkbox-count-maybe))
19247 (when firstp (org-list-send-list 'maybe))))
19248 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19249 ;; Dynamic block
19250 (beginning-of-line 1)
19251 (save-excursion (org-update-dblock)))
19252 ((save-excursion
19253 (let ((case-fold-search t))
19254 (beginning-of-line 1)
19255 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19256 (cond
19257 ((or (equal (match-string 1) "TBLFM")
19258 (equal (match-string 1) "tblfm"))
19259 ;; Recalculate the table before this line
19260 (save-excursion
19261 (beginning-of-line 1)
19262 (skip-chars-backward " \r\n\t")
19263 (if (org-at-table-p)
19264 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19266 (let ((org-inhibit-startup-visibility-stuff t)
19267 (org-startup-align-all-tables nil))
19268 (when (boundp 'org-table-coordinate-overlays)
19269 (mapc 'delete-overlay org-table-coordinate-overlays)
19270 (setq org-table-coordinate-overlays nil))
19271 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19272 (message "Local setup has been refreshed"))))
19273 ((org-clock-update-time-maybe))
19275 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19276 (error "C-c C-c can do nothing useful at this location"))))))
19278 (defun org-mode-restart ()
19279 "Restart Org-mode, to scan again for special lines.
19280 Also updates the keyword regular expressions."
19281 (interactive)
19282 (org-mode)
19283 (message "Org-mode restarted"))
19285 (defun org-kill-note-or-show-branches ()
19286 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19287 (interactive)
19288 (if (not org-finish-function)
19289 (progn
19290 (hide-subtree)
19291 (call-interactively 'show-branches))
19292 (let ((org-note-abort t))
19293 (funcall org-finish-function))))
19295 (defun org-return (&optional indent)
19296 "Goto next table row or insert a newline.
19297 Calls `org-table-next-row' or `newline', depending on context.
19298 See the individual commands for more information."
19299 (interactive)
19300 (let (org-ts-what)
19301 (cond
19302 ((or (bobp) (org-in-src-block-p))
19303 (if indent (newline-and-indent) (newline)))
19304 ((org-at-table-p)
19305 (org-table-justify-field-maybe)
19306 (call-interactively 'org-table-next-row))
19307 ;; when `newline-and-indent' is called within a list, make sure
19308 ;; text moved stays inside the item.
19309 ((and (org-in-item-p) indent)
19310 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19311 (progn
19312 (save-match-data (newline))
19313 (org-indent-line-to (length (match-string 0))))
19314 (let ((ind (org-get-indentation)))
19315 (newline)
19316 (if (org-looking-back org-list-end-re)
19317 (org-indent-line)
19318 (org-indent-line-to ind)))))
19319 ((and org-return-follows-link
19320 (org-at-timestamp-p t)
19321 (not (eq org-ts-what 'after)))
19322 (org-follow-timestamp-link))
19323 ((and org-return-follows-link
19324 (let ((tprop (get-text-property (point) 'face)))
19325 (or (eq tprop 'org-link)
19326 (and (listp tprop) (memq 'org-link tprop)))))
19327 (call-interactively 'org-open-at-point))
19328 ((and (org-at-heading-p)
19329 (looking-at
19330 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19331 (org-show-entry)
19332 (end-of-line 1)
19333 (newline))
19334 (t (if indent (newline-and-indent) (newline))))))
19336 (defun org-return-indent ()
19337 "Goto next table row or insert a newline and indent.
19338 Calls `org-table-next-row' or `newline-and-indent', depending on
19339 context. See the individual commands for more information."
19340 (interactive)
19341 (org-return t))
19343 (defun org-ctrl-c-star ()
19344 "Compute table, or change heading status of lines.
19345 Calls `org-table-recalculate' or `org-toggle-heading',
19346 depending on context."
19347 (interactive)
19348 (cond
19349 ((org-at-table-p)
19350 (call-interactively 'org-table-recalculate))
19352 ;; Convert all lines in region to list items
19353 (call-interactively 'org-toggle-heading))))
19355 (defun org-ctrl-c-minus ()
19356 "Insert separator line in table or modify bullet status of line.
19357 Also turns a plain line or a region of lines into list items.
19358 Calls `org-table-insert-hline', `org-toggle-item', or
19359 `org-cycle-list-bullet', depending on context."
19360 (interactive)
19361 (cond
19362 ((org-at-table-p)
19363 (call-interactively 'org-table-insert-hline))
19364 ((org-region-active-p)
19365 (call-interactively 'org-toggle-item))
19366 ((org-in-item-p)
19367 (call-interactively 'org-cycle-list-bullet))
19369 (call-interactively 'org-toggle-item))))
19371 (defun org-toggle-item (arg)
19372 "Convert headings or normal lines to items, items to normal lines.
19373 If there is no active region, only the current line is considered.
19375 If the first non blank line in the region is an headline, convert
19376 all headlines to items, shifting text accordingly.
19378 If it is an item, convert all items to normal lines.
19380 If it is normal text, change region into an item. With a prefix
19381 argument ARG, change each line in region into an item."
19382 (interactive "P")
19383 (let ((shift-text
19384 (function
19385 ;; Shift text in current section to IND, from point to END.
19386 ;; The function leaves point to END line.
19387 (lambda (ind end)
19388 (let ((min-i 1000) (end (copy-marker end)))
19389 ;; First determine the minimum indentation (MIN-I) of
19390 ;; the text.
19391 (save-excursion
19392 (catch 'exit
19393 (while (< (point) end)
19394 (let ((i (org-get-indentation)))
19395 (cond
19396 ;; Skip blank lines and inline tasks.
19397 ((looking-at "^[ \t]*$"))
19398 ((looking-at org-outline-regexp-bol))
19399 ;; We can't find less than 0 indentation.
19400 ((zerop i) (throw 'exit (setq min-i 0)))
19401 ((< i min-i) (setq min-i i))))
19402 (forward-line))))
19403 ;; Then indent each line so that a line indented to
19404 ;; MIN-I becomes indented to IND. Ignore blank lines
19405 ;; and inline tasks in the process.
19406 (let ((delta (- ind min-i)))
19407 (while (< (point) end)
19408 (unless (or (looking-at "^[ \t]*$")
19409 (looking-at org-outline-regexp-bol))
19410 (org-indent-line-to (+ (org-get-indentation) delta)))
19411 (forward-line)))))))
19412 (skip-blanks
19413 (function
19414 ;; Return beginning of first non-blank line, starting from
19415 ;; line at POS.
19416 (lambda (pos)
19417 (save-excursion
19418 (goto-char pos)
19419 (skip-chars-forward " \r\t\n")
19420 (point-at-bol)))))
19421 beg end)
19422 ;; Determine boundaries of changes.
19423 (if (org-region-active-p)
19424 (setq beg (funcall skip-blanks (region-beginning))
19425 end (copy-marker (region-end)))
19426 (setq beg (funcall skip-blanks (point-at-bol))
19427 end (copy-marker (point-at-eol))))
19428 ;; Depending on the starting line, choose an action on the text
19429 ;; between BEG and END.
19430 (org-with-limited-levels
19431 (save-excursion
19432 (goto-char beg)
19433 (cond
19434 ;; Case 1. Start at an item: de-itemize. Note that it only
19435 ;; happens when a region is active: `org-ctrl-c-minus'
19436 ;; would call `org-cycle-list-bullet' otherwise.
19437 ((org-at-item-p)
19438 (while (< (point) end)
19439 (when (org-at-item-p)
19440 (skip-chars-forward " \t")
19441 (delete-region (point) (match-end 0)))
19442 (forward-line)))
19443 ;; Case 2. Start at an heading: convert to items.
19444 ((org-at-heading-p)
19445 (let* ((bul (org-list-bullet-string "-"))
19446 (bul-len (length bul))
19447 ;; Indentation of the first heading. It should be
19448 ;; relative to the indentation of its parent, if any.
19449 (start-ind (save-excursion
19450 (cond
19451 ((not org-adapt-indentation) 0)
19452 ((not (outline-previous-heading)) 0)
19453 (t (length (match-string 0))))))
19454 ;; Level of first heading. Further headings will be
19455 ;; compared to it to determine hierarchy in the list.
19456 (ref-level (org-reduced-level (org-outline-level))))
19457 (while (< (point) end)
19458 (let* ((level (org-reduced-level (org-outline-level)))
19459 (delta (max 0 (- level ref-level))))
19460 ;; If current headline is less indented than the first
19461 ;; one, set it as reference, in order to preserve
19462 ;; subtrees.
19463 (when (< level ref-level) (setq ref-level level))
19464 (replace-match bul t t)
19465 (org-indent-line-to (+ start-ind (* delta bul-len)))
19466 ;; Ensure all text down to END (or SECTION-END) belongs
19467 ;; to the newly created item.
19468 (let ((section-end (save-excursion
19469 (or (outline-next-heading) (point)))))
19470 (forward-line)
19471 (funcall shift-text
19472 (+ start-ind (* (1+ delta) bul-len))
19473 (min end section-end)))))))
19474 ;; Case 3. Normal line with ARG: turn each non-item line into
19475 ;; an item.
19476 (arg
19477 (while (< (point) end)
19478 (unless (or (org-at-heading-p) (org-at-item-p))
19479 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19480 (replace-match
19481 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19482 (forward-line)))
19483 ;; Case 4. Normal line without ARG: make the first line of
19484 ;; region an item, and shift indentation of others
19485 ;; lines to set them as item's body.
19486 (t (let* ((bul (org-list-bullet-string "-"))
19487 (bul-len (length bul))
19488 (ref-ind (org-get-indentation)))
19489 (skip-chars-forward " \t")
19490 (insert bul)
19491 (forward-line)
19492 (while (< (point) end)
19493 ;; Ensure that lines less indented than first one
19494 ;; still get included in item body.
19495 (funcall shift-text
19496 (+ ref-ind bul-len)
19497 (min end (save-excursion (or (outline-next-heading)
19498 (point)))))
19499 (forward-line)))))))))
19501 (defun org-toggle-heading (&optional nstars)
19502 "Convert headings to normal text, or items or text to headings.
19503 If there is no active region, only the current line is considered.
19505 With a \\[universal-argument] prefix, convert the whole list at
19506 point into heading.
19508 In a region:
19510 - If the first non blank line is an headline, remove the stars
19511 from all headlines in the region.
19513 - If it is a normal line turn each and every normal line (i.e. not an
19514 heading or an item) in the region into a heading.
19516 - If it is a plain list item, turn all plain list items into headings.
19518 When converting a line into a heading, the number of stars is chosen
19519 such that the lines become children of the current entry. However,
19520 when a prefix argument is given, its value determines the number of
19521 stars to add."
19522 (interactive "P")
19523 (let ((skip-blanks
19524 (function
19525 ;; Return beginning of first non-blank line, starting from
19526 ;; line at POS.
19527 (lambda (pos)
19528 (save-excursion
19529 (goto-char pos)
19530 (while (org-at-comment-p) (forward-line))
19531 (skip-chars-forward " \r\t\n")
19532 (point-at-bol)))))
19533 beg end toggled)
19534 ;; Determine boundaries of changes. If a universal prefix has
19535 ;; been given, put the list in a region. If region ends at a bol,
19536 ;; do not consider the last line to be in the region.
19538 (when (and current-prefix-arg (org-at-item-p))
19539 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19540 (org-mark-element))
19542 (if (org-region-active-p)
19543 (setq beg (funcall skip-blanks (region-beginning))
19544 end (copy-marker (save-excursion
19545 (goto-char (region-end))
19546 (if (bolp) (point) (point-at-eol)))))
19547 (setq beg (funcall skip-blanks (point-at-bol))
19548 end (copy-marker (point-at-eol))))
19549 ;; Ensure inline tasks don't count as headings.
19550 (org-with-limited-levels
19551 (save-excursion
19552 (goto-char beg)
19553 (cond
19554 ;; Case 1. Started at an heading: de-star headings.
19555 ((org-at-heading-p)
19556 (while (< (point) end)
19557 (when (org-at-heading-p t)
19558 (looking-at org-outline-regexp) (replace-match "")
19559 (setq toggled t))
19560 (forward-line)))
19561 ;; Case 2. Started at an item: change items into headlines.
19562 ;; One star will be added by `org-list-to-subtree'.
19563 ((org-at-item-p)
19564 (let* ((stars (make-string
19565 (if nstars
19566 ;; subtract the star that will be added again by
19567 ;; `org-list-to-subtree'
19568 (1- (prefix-numeric-value current-prefix-arg))
19569 (or (org-current-level) 0))
19570 ?*))
19571 (add-stars
19572 (cond (nstars "") ; stars from prefix only
19573 ((equal stars "") "") ; before first heading
19574 (org-odd-levels-only "*") ; inside heading, odd
19575 (t "")))) ; inside heading, oddeven
19576 (while (< (point) end)
19577 (when (org-at-item-p)
19578 ;; Pay attention to cases when region ends before list.
19579 (let* ((struct (org-list-struct))
19580 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19581 (save-restriction
19582 (narrow-to-region (point) list-end)
19583 (insert
19584 (org-list-to-subtree
19585 (org-list-parse-list t)
19586 '(:istart (concat stars add-stars (funcall get-stars depth))
19587 :icount (concat stars add-stars (funcall get-stars depth)))))))
19588 (setq toggled t))
19589 (forward-line))))
19590 ;; Case 3. Started at normal text: make every line an heading,
19591 ;; skipping headlines and items.
19592 (t (let* ((stars (make-string
19593 (if nstars
19594 (prefix-numeric-value current-prefix-arg)
19595 (or (org-current-level) 0))
19596 ?*))
19597 (add-stars
19598 (cond (nstars "") ; stars from prefix only
19599 ((equal stars "") "*") ; before first heading
19600 (org-odd-levels-only "**") ; inside heading, odd
19601 (t "*"))) ; inside heading, oddeven
19602 (rpl (concat stars add-stars " ")))
19603 (while (< (point) end)
19604 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19605 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19606 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19607 (forward-line)))))))
19608 (unless toggled (message "Cannot toggle heading from here"))))
19610 (defun org-meta-return (&optional arg)
19611 "Insert a new heading or wrap a region in a table.
19612 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19613 See the individual commands for more information."
19614 (interactive "P")
19615 (cond
19616 ((run-hook-with-args-until-success 'org-metareturn-hook))
19617 ((or (org-at-drawer-p) (org-at-property-p))
19618 (newline-and-indent))
19619 ((org-at-table-p)
19620 (call-interactively 'org-table-wrap-region))
19621 (t (call-interactively 'org-insert-heading))))
19623 ;;; Menu entries
19625 (defsubst org-in-subtree-not-table-p ()
19626 "Are we in a subtree and not in a table?"
19627 (and (not (org-before-first-heading-p))
19628 (not (org-at-table-p))))
19630 ;; Define the Org-mode menus
19631 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19632 '("Tbl"
19633 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19634 ["Next Field" org-cycle (org-at-table-p)]
19635 ["Previous Field" org-shifttab (org-at-table-p)]
19636 ["Next Row" org-return (org-at-table-p)]
19637 "--"
19638 ["Blank Field" org-table-blank-field (org-at-table-p)]
19639 ["Edit Field" org-table-edit-field (org-at-table-p)]
19640 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19641 "--"
19642 ("Column"
19643 ["Move Column Left" org-metaleft (org-at-table-p)]
19644 ["Move Column Right" org-metaright (org-at-table-p)]
19645 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19646 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19647 ("Row"
19648 ["Move Row Up" org-metaup (org-at-table-p)]
19649 ["Move Row Down" org-metadown (org-at-table-p)]
19650 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19651 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19652 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19653 "--"
19654 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19655 ("Rectangle"
19656 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19657 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19658 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19659 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19660 "--"
19661 ("Calculate"
19662 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19663 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19664 ["Edit Formulas" org-edit-special (org-at-table-p)]
19665 "--"
19666 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19667 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19668 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19669 "--"
19670 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19671 "--"
19672 ["Sum Column/Rectangle" org-table-sum
19673 (or (org-at-table-p) (org-region-active-p))]
19674 ["Which Column?" org-table-current-column (org-at-table-p)])
19675 ["Debug Formulas"
19676 org-table-toggle-formula-debugger
19677 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19678 ["Show Col/Row Numbers"
19679 org-table-toggle-coordinate-overlays
19680 :style toggle
19681 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19682 "--"
19683 ["Create" org-table-create (and (not (org-at-table-p))
19684 org-enable-table-editor)]
19685 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19686 ["Import from File" org-table-import (not (org-at-table-p))]
19687 ["Export to File" org-table-export (org-at-table-p)]
19688 "--"
19689 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19691 (easy-menu-define org-org-menu org-mode-map "Org menu"
19692 '("Org"
19693 ("Show/Hide"
19694 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19695 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19696 ["Sparse Tree..." org-sparse-tree t]
19697 ["Reveal Context" org-reveal t]
19698 ["Show All" show-all t]
19699 "--"
19700 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19701 "--"
19702 ["New Heading" org-insert-heading t]
19703 ("Navigate Headings"
19704 ["Up" outline-up-heading t]
19705 ["Next" outline-next-visible-heading t]
19706 ["Previous" outline-previous-visible-heading t]
19707 ["Next Same Level" outline-forward-same-level t]
19708 ["Previous Same Level" outline-backward-same-level t]
19709 "--"
19710 ["Jump" org-goto t])
19711 ("Edit Structure"
19712 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19713 "--"
19714 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19715 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19716 "--"
19717 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19718 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19719 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19720 "--"
19721 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19722 "--"
19723 ["Copy visible text" org-copy-visible t]
19724 "--"
19725 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19726 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19727 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19728 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19729 "--"
19730 ["Sort Region/Children" org-sort t]
19731 "--"
19732 ["Convert to odd levels" org-convert-to-odd-levels t]
19733 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19734 ("Editing"
19735 ["Emphasis..." org-emphasize t]
19736 ["Edit Source Example" org-edit-special t]
19737 "--"
19738 ["Footnote new/jump" org-footnote-action t]
19739 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19740 ("Archive"
19741 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19742 "--"
19743 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19744 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19745 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19747 "--"
19748 ("Hyperlinks"
19749 ["Store Link (Global)" org-store-link t]
19750 ["Find existing link to here" org-occur-link-in-agenda-files t]
19751 ["Insert Link" org-insert-link t]
19752 ["Follow Link" org-open-at-point t]
19753 "--"
19754 ["Next link" org-next-link t]
19755 ["Previous link" org-previous-link t]
19756 "--"
19757 ["Descriptive Links"
19758 org-toggle-link-display
19759 :style radio
19760 :selected org-descriptive-links
19762 ["Literal Links"
19763 org-toggle-link-display
19764 :style radio
19765 :selected (not org-descriptive-links)])
19766 "--"
19767 ("TODO Lists"
19768 ["TODO/DONE/-" org-todo t]
19769 ("Select keyword"
19770 ["Next keyword" org-shiftright (org-at-heading-p)]
19771 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19772 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19773 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19774 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19775 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19776 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19777 "--"
19778 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19779 :selected org-enforce-todo-dependencies :style toggle :active t]
19780 "Settings for tree at point"
19781 ["Do Children sequentially" org-toggle-ordered-property :style radio
19782 :selected (org-entry-get nil "ORDERED")
19783 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19784 ["Do Children parallel" org-toggle-ordered-property :style radio
19785 :selected (not (org-entry-get nil "ORDERED"))
19786 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19787 "--"
19788 ["Set Priority" org-priority t]
19789 ["Priority Up" org-shiftup t]
19790 ["Priority Down" org-shiftdown t]
19791 "--"
19792 ["Get news from all feeds" org-feed-update-all t]
19793 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19794 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19795 ("TAGS and Properties"
19796 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19797 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19798 "--"
19799 ["Set property" org-set-property (not (org-before-first-heading-p))]
19800 ["Column view of properties" org-columns t]
19801 ["Insert Column View DBlock" org-insert-columns-dblock t])
19802 ("Dates and Scheduling"
19803 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19804 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19805 ("Change Date"
19806 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19807 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19808 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19809 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19810 ["Compute Time Range" org-evaluate-time-range t]
19811 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19812 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19813 "--"
19814 ["Custom time format" org-toggle-time-stamp-overlays
19815 :style radio :selected org-display-custom-times]
19816 "--"
19817 ["Goto Calendar" org-goto-calendar t]
19818 ["Date from Calendar" org-date-from-calendar t]
19819 "--"
19820 ["Start/Restart Timer" org-timer-start t]
19821 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19822 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19823 ["Insert Timer String" org-timer t]
19824 ["Insert Timer Item" org-timer-item t])
19825 ("Logging work"
19826 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19827 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19828 ["Clock out" org-clock-out t]
19829 ["Clock cancel" org-clock-cancel t]
19830 "--"
19831 ["Mark as default task" org-clock-mark-default-task t]
19832 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19833 ["Goto running clock" org-clock-goto t]
19834 "--"
19835 ["Display times" org-clock-display t]
19836 ["Create clock table" org-clock-report t]
19837 "--"
19838 ["Record DONE time"
19839 (progn (setq org-log-done (not org-log-done))
19840 (message "Switching to %s will %s record a timestamp"
19841 (car org-done-keywords)
19842 (if org-log-done "automatically" "not")))
19843 :style toggle :selected org-log-done])
19844 "--"
19845 ["Agenda Command..." org-agenda t]
19846 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19847 ("File List for Agenda")
19848 ("Special views current file"
19849 ["TODO Tree" org-show-todo-tree t]
19850 ["Check Deadlines" org-check-deadlines t]
19851 ["Timeline" org-timeline t]
19852 ["Tags/Property tree" org-match-sparse-tree t])
19853 "--"
19854 ["Export/Publish..." org-export t]
19855 ("LaTeX"
19856 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19857 :selected org-cdlatex-mode]
19858 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19859 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19860 ["Modify math symbol" org-cdlatex-math-modify
19861 (org-inside-LaTeX-fragment-p)]
19862 ["Insert citation" org-reftex-citation t]
19863 "--"
19864 ["Template for BEAMER" (progn (require 'org-beamer)
19865 (org-insert-beamer-options-template)) t])
19866 "--"
19867 ("MobileOrg"
19868 ["Push Files and Views" org-mobile-push t]
19869 ["Get Captured and Flagged" org-mobile-pull t]
19870 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19871 "--"
19872 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19873 "--"
19874 ("Documentation"
19875 ["Show Version" org-version t]
19876 ["Info Documentation" org-info t])
19877 ("Customize"
19878 ["Browse Org Group" org-customize t]
19879 "--"
19880 ["Expand This Menu" org-create-customize-menu
19881 (fboundp 'customize-menu-create)])
19882 ["Send bug report" org-submit-bug-report t]
19883 "--"
19884 ("Refresh/Reload"
19885 ["Refresh setup current buffer" org-mode-restart t]
19886 ["Reload Org (after update)" org-reload t]
19887 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19890 (defun org-info (&optional node)
19891 "Read documentation for Org-mode in the info system.
19892 With optional NODE, go directly to that node."
19893 (interactive)
19894 (info (format "(org)%s" (or node ""))))
19896 ;;;###autoload
19897 (defun org-submit-bug-report ()
19898 "Submit a bug report on Org-mode via mail.
19900 Don't hesitate to report any problems or inaccurate documentation.
19902 If you don't have setup sending mail from (X)Emacs, please copy the
19903 output buffer into your mail program, as it gives us important
19904 information about your Org-mode version and configuration."
19905 (interactive)
19906 (require 'reporter)
19907 (org-load-modules-maybe)
19908 (org-require-autoloaded-modules)
19909 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19910 (reporter-submit-bug-report
19911 "emacs-orgmode@gnu.org"
19912 (org-version nil 'full)
19913 (let (list)
19914 (save-window-excursion
19915 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19916 (delete-other-windows)
19917 (erase-buffer)
19918 (insert "You are about to submit a bug report to the Org-mode mailing list.
19920 We would like to add your full Org-mode and Outline configuration to the
19921 bug report. This greatly simplifies the work of the maintainer and
19922 other experts on the mailing list.
19924 HOWEVER, some variables you have customized may contain private
19925 information. The names of customers, colleagues, or friends, might
19926 appear in the form of file names, tags, todo states, or search strings.
19927 If you answer yes to the prompt, you might want to check and remove
19928 such private information before sending the email.")
19929 (add-text-properties (point-min) (point-max) '(face org-warning))
19930 (when (yes-or-no-p "Include your Org-mode configuration ")
19931 (mapatoms
19932 (lambda (v)
19933 (and (boundp v)
19934 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19935 (or (and (symbol-value v)
19936 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19937 (and
19938 (get v 'custom-type) (get v 'standard-value)
19939 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19940 (push v list)))))
19941 (kill-buffer (get-buffer "*Warn about privacy*"))
19942 list))
19943 nil nil
19944 "Remember to cover the basics, that is, what you expected to happen and
19945 what in fact did happen. You don't know how to make a good report? See
19947 http://orgmode.org/manual/Feedback.html#Feedback
19949 Your bug report will be posted to the Org-mode mailing list.
19950 ------------------------------------------------------------------------")
19951 (save-excursion
19952 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19953 (replace-match "\\1Bug: \\3 [\\2]")))))
19956 (defun org-install-agenda-files-menu ()
19957 (let ((bl (buffer-list)))
19958 (save-excursion
19959 (while bl
19960 (set-buffer (pop bl))
19961 (if (derived-mode-p 'org-mode) (setq bl nil)))
19962 (when (derived-mode-p 'org-mode)
19963 (easy-menu-change
19964 '("Org") "File List for Agenda"
19965 (append
19966 (list
19967 ["Edit File List" (org-edit-agenda-file-list) t]
19968 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19969 ["Remove Current File from List" org-remove-file t]
19970 ["Cycle through agenda files" org-cycle-agenda-files t]
19971 ["Occur in all agenda files" org-occur-in-agenda-files t]
19972 "--")
19973 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19975 ;;;; Documentation
19977 ;;;###autoload
19978 (defun org-require-autoloaded-modules ()
19979 (interactive)
19980 (mapc 'require
19981 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19982 org-docbook org-exp org-html org-icalendar
19983 org-id org-latex
19984 org-publish org-remember org-table
19985 org-timer org-xoxo)))
19987 ;;;###autoload
19988 (defun org-reload (&optional uncompiled)
19989 "Reload all org lisp files.
19990 With prefix arg UNCOMPILED, load the uncompiled versions."
19991 (interactive "P")
19992 (require 'find-func)
19993 (let* ((file-re "^org\\(-.*\\)?\\.el")
19994 (dir-org (file-name-directory (org-find-library-dir "org")))
19995 (dir-org-contrib (ignore-errors
19996 (file-name-directory
19997 (org-find-library-dir "org-contribdir"))))
19998 (babel-files
19999 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20000 (append (list nil "comint" "eval" "exp" "keys"
20001 "lob" "ref" "table" "tangle")
20002 (delq nil
20003 (mapcar
20004 (lambda (lang)
20005 (when (cdr lang) (symbol-name (car lang))))
20006 org-babel-load-languages)))))
20007 (files
20008 (append babel-files
20009 (and dir-org-contrib
20010 (directory-files dir-org-contrib t file-re))
20011 (directory-files dir-org t file-re)))
20012 (remove-re (concat (if (featurep 'xemacs)
20013 "org-colview" "org-colview-xemacs")
20014 "\\'")))
20015 (setq files (mapcar 'file-name-sans-extension files))
20016 (setq files (mapcar
20017 (lambda (x) (if (string-match remove-re x) nil x))
20018 files))
20019 (setq files (delq nil files))
20020 (mapc
20021 (lambda (f)
20022 (when (featurep (intern (file-name-nondirectory f)))
20023 (if (and (not uncompiled)
20024 (file-exists-p (concat f ".elc")))
20025 (load (concat f ".elc") nil nil 'nosuffix)
20026 (load (concat f ".el") nil nil 'nosuffix))))
20027 files)
20028 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20029 (org-version nil 'full 'message))
20031 ;;;###autoload
20032 (defun org-customize ()
20033 "Call the customize function with org as argument."
20034 (interactive)
20035 (org-load-modules-maybe)
20036 (org-require-autoloaded-modules)
20037 (customize-browse 'org))
20039 (defun org-create-customize-menu ()
20040 "Create a full customization menu for Org-mode, insert it into the menu."
20041 (interactive)
20042 (org-load-modules-maybe)
20043 (org-require-autoloaded-modules)
20044 (if (fboundp 'customize-menu-create)
20045 (progn
20046 (easy-menu-change
20047 '("Org") "Customize"
20048 `(["Browse Org group" org-customize t]
20049 "--"
20050 ,(customize-menu-create 'org)
20051 ["Set" Custom-set t]
20052 ["Save" Custom-save t]
20053 ["Reset to Current" Custom-reset-current t]
20054 ["Reset to Saved" Custom-reset-saved t]
20055 ["Reset to Standard Settings" Custom-reset-standard t]))
20056 (message "\"Org\"-menu now contains full customization menu"))
20057 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20059 ;;;; Miscellaneous stuff
20061 ;;; Generally useful functions
20063 (defun org-get-at-bol (property)
20064 "Get text property PROPERTY at beginning of line."
20065 (get-text-property (point-at-bol) property))
20067 (defun org-find-text-property-in-string (prop s)
20068 "Return the first non-nil value of property PROP in string S."
20069 (or (get-text-property 0 prop s)
20070 (get-text-property (or (next-single-property-change 0 prop s) 0)
20071 prop s)))
20073 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20074 "Display the given MESSAGE as a warning."
20075 (if (fboundp 'display-warning)
20076 (display-warning 'org message
20077 (if (featurep 'xemacs) 'warning :warning))
20078 (let ((buf (get-buffer-create "*Org warnings*")))
20079 (with-current-buffer buf
20080 (goto-char (point-max))
20081 (insert "Warning (Org): " message)
20082 (unless (bolp)
20083 (newline)))
20084 (display-buffer buf)
20085 (sit-for 0))))
20087 (defun org-eval (form)
20088 "Eval FORM and return result."
20089 (condition-case error
20090 (eval form)
20091 (error (format "%%![Error: %s]" error))))
20093 (defun org-in-clocktable-p ()
20094 "Check if the cursor is in a clocktable."
20095 (let ((pos (point)) start)
20096 (save-excursion
20097 (end-of-line 1)
20098 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20099 (setq start (match-beginning 0))
20100 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20101 (>= (match-end 0) pos)
20102 start))))
20104 (defun org-in-commented-line ()
20105 "Is point in a line starting with `#'?"
20106 (equal (char-after (point-at-bol)) ?#))
20108 (defun org-in-indented-comment-line ()
20109 "Is point in a line starting with `#' after some white space?"
20110 (save-excursion
20111 (save-match-data
20112 (goto-char (point-at-bol))
20113 (looking-at "[ \t]*#"))))
20115 (defun org-in-verbatim-emphasis ()
20116 (save-match-data
20117 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20119 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20120 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20121 (if (and marker (marker-buffer marker)
20122 (buffer-live-p (marker-buffer marker)))
20123 (progn
20124 (org-pop-to-buffer-same-window (marker-buffer marker))
20125 (if (or (> marker (point-max)) (< marker (point-min)))
20126 (widen))
20127 (goto-char marker)
20128 (org-show-context 'org-goto))
20129 (if bookmark
20130 (bookmark-jump bookmark)
20131 (error "Cannot find location"))))
20133 (defun org-quote-csv-field (s)
20134 "Quote field for inclusion in CSV material."
20135 (if (string-match "[\",]" s)
20136 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20139 (defun org-force-self-insert (N)
20140 "Needed to enforce self-insert under remapping."
20141 (interactive "p")
20142 (self-insert-command N))
20144 (defun org-string-width (s)
20145 "Compute width of string, ignoring invisible characters.
20146 This ignores character with invisibility property `org-link', and also
20147 characters with property `org-cwidth', because these will become invisible
20148 upon the next fontification round."
20149 (let (b l)
20150 (when (or (eq t buffer-invisibility-spec)
20151 (assq 'org-link buffer-invisibility-spec))
20152 (while (setq b (text-property-any 0 (length s)
20153 'invisible 'org-link s))
20154 (setq s (concat (substring s 0 b)
20155 (substring s (or (next-single-property-change
20156 b 'invisible s) (length s)))))))
20157 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20158 (setq s (concat (substring s 0 b)
20159 (substring s (or (next-single-property-change
20160 b 'org-cwidth s) (length s))))))
20161 (setq l (string-width s) b -1)
20162 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20163 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20166 (defun org-shorten-string (s maxlength)
20167 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20168 If the string is shorter or has length MAXLENGTH, just return the
20169 original string. If it is longer, the functions finds a space in the
20170 string, breaks this string off at that locations and adds three dots
20171 as ellipsis. Including the ellipsis, the string will not be longer
20172 than MAXLENGTH. If finding a good breaking point in the string does
20173 not work, the string is just chopped off in the middle of a word
20174 if necessary."
20175 (if (<= (length s) maxlength)
20177 (let* ((n (max (- maxlength 4) 1))
20178 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20179 (if (string-match re s)
20180 (concat (match-string 1 s) "...")
20181 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20183 (defun org-get-indentation (&optional line)
20184 "Get the indentation of the current line, interpreting tabs.
20185 When LINE is given, assume it represents a line and compute its indentation."
20186 (if line
20187 (if (string-match "^ *" (org-remove-tabs line))
20188 (match-end 0))
20189 (save-excursion
20190 (beginning-of-line 1)
20191 (skip-chars-forward " \t")
20192 (current-column))))
20194 (defun org-get-string-indentation (s)
20195 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20196 (let ((n -1) (i 0) (w tab-width) c)
20197 (catch 'exit
20198 (while (< (setq n (1+ n)) (length s))
20199 (setq c (aref s n))
20200 (cond ((= c ?\ ) (setq i (1+ i)))
20201 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20202 (t (throw 'exit t)))))
20205 (defun org-remove-tabs (s &optional width)
20206 "Replace tabulators in S with spaces.
20207 Assumes that s is a single line, starting in column 0."
20208 (setq width (or width tab-width))
20209 (while (string-match "\t" s)
20210 (setq s (replace-match
20211 (make-string
20212 (- (* width (/ (+ (match-beginning 0) width) width))
20213 (match-beginning 0)) ?\ )
20214 t t s)))
20217 (defun org-fix-indentation (line ind)
20218 "Fix indentation in LINE.
20219 IND is a cons cell with target and minimum indentation.
20220 If the current indentation in LINE is smaller than the minimum,
20221 leave it alone. If it is larger than ind, set it to the target."
20222 (let* ((l (org-remove-tabs line))
20223 (i (org-get-indentation l))
20224 (i1 (car ind)) (i2 (cdr ind)))
20225 (if (>= i i2) (setq l (substring line i2)))
20226 (if (> i1 0)
20227 (concat (make-string i1 ?\ ) l)
20228 l)))
20230 (defun org-remove-indentation (code &optional n)
20231 "Remove the maximum common indentation from the lines in CODE.
20232 N may optionally be the number of spaces to remove."
20233 (with-temp-buffer
20234 (insert code)
20235 (org-do-remove-indentation n)
20236 (buffer-string)))
20238 (defun org-do-remove-indentation (&optional n)
20239 "Remove the maximum common indentation from the buffer."
20240 (untabify (point-min) (point-max))
20241 (let ((min 10000) re)
20242 (if n
20243 (setq min n)
20244 (goto-char (point-min))
20245 (while (re-search-forward "^ *[^ \n]" nil t)
20246 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20247 (unless (or (= min 0) (= min 10000))
20248 (setq re (format "^ \\{%d\\}" min))
20249 (goto-char (point-min))
20250 (while (re-search-forward re nil t)
20251 (replace-match "")
20252 (end-of-line 1))
20253 min)))
20255 (defun org-fill-template (template alist)
20256 "Find each %key of ALIST in TEMPLATE and replace it."
20257 (let ((case-fold-search nil)
20258 entry key value)
20259 (setq alist (sort (copy-sequence alist)
20260 (lambda (a b) (< (length (car a)) (length (car b))))))
20261 (while (setq entry (pop alist))
20262 (setq template
20263 (replace-regexp-in-string
20264 (concat "%" (regexp-quote (car entry)))
20265 (or (cdr entry) "") template t t)))
20266 template))
20268 (defun org-base-buffer (buffer)
20269 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20270 (if (not buffer)
20271 buffer
20272 (or (buffer-base-buffer buffer)
20273 buffer)))
20275 (defun org-trim (s)
20276 "Remove whitespace at beginning and end of string."
20277 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20278 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20281 (defun org-wrap (string &optional width lines)
20282 "Wrap string to either a number of lines, or a width in characters.
20283 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20284 that costs. If there is a word longer than WIDTH, the text is actually
20285 wrapped to the length of that word.
20286 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20287 many lines, whatever width that takes.
20288 The return value is a list of lines, without newlines at the end."
20289 (let* ((words (org-split-string string "[ \t\n]+"))
20290 (maxword (apply 'max (mapcar 'org-string-width words)))
20291 w ll)
20292 (cond (width
20293 (org-do-wrap words (max maxword width)))
20294 (lines
20295 (setq w maxword)
20296 (setq ll (org-do-wrap words maxword))
20297 (if (<= (length ll) lines)
20299 (setq ll words)
20300 (while (> (length ll) lines)
20301 (setq w (1+ w))
20302 (setq ll (org-do-wrap words w)))
20303 ll))
20304 (t (error "Cannot wrap this")))))
20306 (defun org-do-wrap (words width)
20307 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20308 (let (lines line)
20309 (while words
20310 (setq line (pop words))
20311 (while (and words (< (+ (length line) (length (car words))) width))
20312 (setq line (concat line " " (pop words))))
20313 (setq lines (push line lines)))
20314 (nreverse lines)))
20316 (defun org-split-string (string &optional separators)
20317 "Splits STRING into substrings at SEPARATORS.
20318 No empty strings are returned if there are matches at the beginning
20319 and end of string."
20320 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20321 (start 0)
20322 notfirst
20323 (list nil))
20324 (while (and (string-match rexp string
20325 (if (and notfirst
20326 (= start (match-beginning 0))
20327 (< start (length string)))
20328 (1+ start) start))
20329 (< (match-beginning 0) (length string)))
20330 (setq notfirst t)
20331 (or (eq (match-beginning 0) 0)
20332 (and (eq (match-beginning 0) (match-end 0))
20333 (eq (match-beginning 0) start))
20334 (setq list
20335 (cons (substring string start (match-beginning 0))
20336 list)))
20337 (setq start (match-end 0)))
20338 (or (eq start (length string))
20339 (setq list
20340 (cons (substring string start)
20341 list)))
20342 (nreverse list)))
20344 (defun org-quote-vert (s)
20345 "Replace \"|\" with \"\\vert\"."
20346 (while (string-match "|" s)
20347 (setq s (replace-match "\\vert" t t s)))
20350 (defun org-uuidgen-p (s)
20351 "Is S an ID created by UUIDGEN?"
20352 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20354 (defun org-in-src-block-p nil
20355 "Whether point is in a code source block."
20356 (let (ov)
20357 (when (setq ov (overlays-at (point)))
20358 (memq 'org-block-background
20359 (overlay-properties
20360 (car ov))))))
20362 (defun org-context ()
20363 "Return a list of contexts of the current cursor position.
20364 If several contexts apply, all are returned.
20365 Each context entry is a list with a symbol naming the context, and
20366 two positions indicating start and end of the context. Possible
20367 contexts are:
20369 :headline anywhere in a headline
20370 :headline-stars on the leading stars in a headline
20371 :todo-keyword on a TODO keyword (including DONE) in a headline
20372 :tags on the TAGS in a headline
20373 :priority on the priority cookie in a headline
20374 :item on the first line of a plain list item
20375 :item-bullet on the bullet/number of a plain list item
20376 :checkbox on the checkbox in a plain list item
20377 :table in an org-mode table
20378 :table-special on a special filed in a table
20379 :table-table in a table.el table
20380 :clocktable in a clocktable
20381 :src-block in a source block
20382 :link on a hyperlink
20383 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20384 :target on a <<target>>
20385 :radio-target on a <<<radio-target>>>
20386 :latex-fragment on a LaTeX fragment
20387 :latex-preview on a LaTeX fragment with overlaid preview image
20389 This function expects the position to be visible because it uses font-lock
20390 faces as a help to recognize the following contexts: :table-special, :link,
20391 and :keyword."
20392 (let* ((f (get-text-property (point) 'face))
20393 (faces (if (listp f) f (list f)))
20394 (case-fold-search t)
20395 (p (point)) clist o)
20396 ;; First the large context
20397 (cond
20398 ((org-at-heading-p t)
20399 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20400 (when (progn
20401 (beginning-of-line 1)
20402 (looking-at org-todo-line-tags-regexp))
20403 (push (org-point-in-group p 1 :headline-stars) clist)
20404 (push (org-point-in-group p 2 :todo-keyword) clist)
20405 (push (org-point-in-group p 4 :tags) clist))
20406 (goto-char p)
20407 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20408 (if (looking-at "\\[#[A-Z0-9]\\]")
20409 (push (org-point-in-group p 0 :priority) clist)))
20411 ((org-at-item-p)
20412 (push (org-point-in-group p 2 :item-bullet) clist)
20413 (push (list :item (point-at-bol)
20414 (save-excursion (org-end-of-item) (point)))
20415 clist)
20416 (and (org-at-item-checkbox-p)
20417 (push (org-point-in-group p 0 :checkbox) clist)))
20419 ((org-at-table-p)
20420 (push (list :table (org-table-begin) (org-table-end)) clist)
20421 (if (memq 'org-formula faces)
20422 (push (list :table-special
20423 (previous-single-property-change p 'face)
20424 (next-single-property-change p 'face)) clist)))
20425 ((org-at-table-p 'any)
20426 (push (list :table-table) clist)))
20427 (goto-char p)
20429 (let ((case-fold-search t))
20430 ;; New the "medium" contexts: clocktables, source blocks
20431 (cond ((org-in-clocktable-p)
20432 (push (list :clocktable
20433 (and (or (looking-at "#\\+BEGIN: clocktable")
20434 (search-backward "#+BEGIN: clocktable" nil t))
20435 (match-beginning 0))
20436 (and (re-search-forward "#\\+END:?" nil t)
20437 (match-end 0))) clist))
20438 ((org-in-src-block-p)
20439 (push (list :src-block
20440 (and (or (looking-at "#\\+BEGIN_SRC")
20441 (search-backward "#+BEGIN_SRC" nil t))
20442 (match-beginning 0))
20443 (and (search-forward "#+END_SRC" nil t)
20444 (match-beginning 0))) clist))))
20445 (goto-char p)
20447 ;; Now the small context
20448 (cond
20449 ((org-at-timestamp-p)
20450 (push (org-point-in-group p 0 :timestamp) clist))
20451 ((memq 'org-link faces)
20452 (push (list :link
20453 (previous-single-property-change p 'face)
20454 (next-single-property-change p 'face)) clist))
20455 ((memq 'org-special-keyword faces)
20456 (push (list :keyword
20457 (previous-single-property-change p 'face)
20458 (next-single-property-change p 'face)) clist))
20459 ((org-at-target-p)
20460 (push (org-point-in-group p 0 :target) clist)
20461 (goto-char (1- (match-beginning 0)))
20462 (if (looking-at org-radio-target-regexp)
20463 (push (org-point-in-group p 0 :radio-target) clist))
20464 (goto-char p))
20465 ((setq o (car (delq nil
20466 (mapcar
20467 (lambda (x)
20468 (if (memq x org-latex-fragment-image-overlays) x))
20469 (overlays-at (point))))))
20470 (push (list :latex-fragment
20471 (overlay-start o) (overlay-end o)) clist)
20472 (push (list :latex-preview
20473 (overlay-start o) (overlay-end o)) clist))
20474 ((org-inside-LaTeX-fragment-p)
20475 ;; FIXME: positions wrong.
20476 (push (list :latex-fragment (point) (point)) clist)))
20478 (setq clist (nreverse (delq nil clist)))
20479 clist))
20481 ;; FIXME: Compare with at-regexp-p Do we need both?
20482 (defun org-in-regexp (re &optional nlines visually)
20483 "Check if point is inside a match of regexp.
20484 Normally only the current line is checked, but you can include NLINES extra
20485 lines both before and after point into the search.
20486 If VISUALLY is set, require that the cursor is not after the match but
20487 really on, so that the block visually is on the match."
20488 (catch 'exit
20489 (let ((pos (point))
20490 (eol (point-at-eol (+ 1 (or nlines 0))))
20491 (inc (if visually 1 0)))
20492 (save-excursion
20493 (beginning-of-line (- 1 (or nlines 0)))
20494 (while (re-search-forward re eol t)
20495 (if (and (<= (match-beginning 0) pos)
20496 (>= (+ inc (match-end 0)) pos))
20497 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20499 (defun org-at-regexp-p (regexp)
20500 "Is point inside a match of REGEXP in the current line?"
20501 (catch 'exit
20502 (save-excursion
20503 (let ((pos (point)) (end (point-at-eol)))
20504 (beginning-of-line 1)
20505 (while (re-search-forward regexp end t)
20506 (if (and (<= (match-beginning 0) pos)
20507 (>= (match-end 0) pos))
20508 (throw 'exit t)))
20509 nil))))
20511 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20512 "Non-nil when point is between matches of START-RE and END-RE.
20514 Also return a non-nil value when point is on one of the matches.
20516 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20517 buffer positions. Default values are the positions of headlines
20518 surrounding the point.
20520 The functions returns a cons cell whose car (resp. cdr) is the
20521 position before START-RE (resp. after END-RE)."
20522 (save-match-data
20523 (let ((pos (point))
20524 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20525 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20526 beg end)
20527 (save-excursion
20528 ;; Point is on a block when on START-RE or if START-RE can be
20529 ;; found before it...
20530 (and (or (org-at-regexp-p start-re)
20531 (re-search-backward start-re limit-up t))
20532 (setq beg (match-beginning 0))
20533 ;; ... and END-RE after it...
20534 (goto-char (match-end 0))
20535 (re-search-forward end-re limit-down t)
20536 (> (setq end (match-end 0)) pos)
20537 ;; ... without another START-RE in-between.
20538 (goto-char (match-beginning 0))
20539 (not (re-search-backward start-re (1+ beg) t))
20540 ;; Return value.
20541 (cons beg end))))))
20543 (defun org-in-block-p (names)
20544 "Non-nil when point belongs to a block whose name belongs to NAMES.
20546 NAMES is a list of strings containing names of blocks.
20548 Return first block name matched, or nil. Beware that in case of
20549 nested blocks, the returned name may not belong to the closest
20550 block from point."
20551 (save-match-data
20552 (catch 'exit
20553 (let ((case-fold-search t)
20554 (lim-up (save-excursion (outline-previous-heading)))
20555 (lim-down (save-excursion (outline-next-heading))))
20556 (mapc (lambda (name)
20557 (let ((n (regexp-quote name)))
20558 (when (org-between-regexps-p
20559 (concat "^[ \t]*#\\+begin_" n)
20560 (concat "^[ \t]*#\\+end_" n)
20561 lim-up lim-down)
20562 (throw 'exit n))))
20563 names))
20564 nil)))
20566 (defun org-occur-in-agenda-files (regexp &optional nlines)
20567 "Call `multi-occur' with buffers for all agenda files."
20568 (interactive "sOrg-files matching: \np")
20569 (let* ((files (org-agenda-files))
20570 (tnames (mapcar 'file-truename files))
20571 (extra org-agenda-text-search-extra-files)
20573 (when (eq (car extra) 'agenda-archives)
20574 (setq extra (cdr extra))
20575 (setq files (org-add-archive-files files)))
20576 (while (setq f (pop extra))
20577 (unless (member (file-truename f) tnames)
20578 (add-to-list 'files f 'append)
20579 (add-to-list 'tnames (file-truename f) 'append)))
20580 (multi-occur
20581 (mapcar (lambda (x)
20582 (with-current-buffer
20583 (or (get-file-buffer x) (find-file-noselect x))
20584 (widen)
20585 (current-buffer)))
20586 files)
20587 regexp)))
20589 (if (boundp 'occur-mode-find-occurrence-hook)
20590 ;; Emacs 23
20591 (add-hook 'occur-mode-find-occurrence-hook
20592 (lambda ()
20593 (when (derived-mode-p 'org-mode)
20594 (org-reveal))))
20595 ;; Emacs 22
20596 (defadvice occur-mode-goto-occurrence
20597 (after org-occur-reveal activate)
20598 (and (derived-mode-p 'org-mode) (org-reveal)))
20599 (defadvice occur-mode-goto-occurrence-other-window
20600 (after org-occur-reveal activate)
20601 (and (derived-mode-p 'org-mode) (org-reveal)))
20602 (defadvice occur-mode-display-occurrence
20603 (after org-occur-reveal activate)
20604 (when (derived-mode-p 'org-mode)
20605 (let ((pos (occur-mode-find-occurrence)))
20606 (with-current-buffer (marker-buffer pos)
20607 (save-excursion
20608 (goto-char pos)
20609 (org-reveal)))))))
20611 (defun org-occur-link-in-agenda-files ()
20612 "Create a link and search for it in the agendas.
20613 The link is not stored in `org-stored-links', it is just created
20614 for the search purpose."
20615 (interactive)
20616 (let ((link (condition-case nil
20617 (org-store-link nil)
20618 (error "Unable to create a link to here"))))
20619 (org-occur-in-agenda-files (regexp-quote link))))
20621 (defun org-uniquify (list)
20622 "Remove duplicate elements from LIST."
20623 (let (res)
20624 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20625 res))
20627 (defun org-delete-all (elts list)
20628 "Remove all elements in ELTS from LIST."
20629 (while elts
20630 (setq list (delete (pop elts) list)))
20631 list)
20633 (defun org-count (cl-item cl-seq)
20634 "Count the number of occurrences of ITEM in SEQ.
20635 Taken from `count' in cl-seq.el with all keyword arguments removed."
20636 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20637 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20638 (while (< cl-start cl-end)
20639 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20640 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20641 (setq cl-start (1+ cl-start)))
20642 cl-count))
20644 (defun org-remove-if (predicate seq)
20645 "Remove everything from SEQ that fulfills PREDICATE."
20646 (let (res e)
20647 (while seq
20648 (setq e (pop seq))
20649 (if (not (funcall predicate e)) (push e res)))
20650 (nreverse res)))
20652 (defun org-remove-if-not (predicate seq)
20653 "Remove everything from SEQ that does not fulfill PREDICATE."
20654 (let (res e)
20655 (while seq
20656 (setq e (pop seq))
20657 (if (funcall predicate e) (push e res)))
20658 (nreverse res)))
20660 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20661 "Reduce two-argument FUNCTION across SEQ.
20662 Taken from `reduce' in cl-seq.el with all keyword arguments but
20663 \":initial-value\" removed."
20664 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20665 (cadr (memq :initial-value cl-keys)))
20666 (cl-seq (pop cl-seq))
20667 (t (funcall cl-func)))))
20668 (while cl-seq
20669 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20670 cl-accum))
20672 (defun org-back-over-empty-lines ()
20673 "Move backwards over whitespace, to the beginning of the first empty line.
20674 Returns the number of empty lines passed."
20675 (let ((pos (point)))
20676 (if (cdr (assoc 'heading org-blank-before-new-entry))
20677 (skip-chars-backward " \t\n\r")
20678 (unless (eobp)
20679 (forward-line -1)))
20680 (beginning-of-line 2)
20681 (goto-char (min (point) pos))
20682 (count-lines (point) pos)))
20684 (defun org-skip-whitespace ()
20685 (skip-chars-forward " \t\n\r"))
20687 (defun org-point-in-group (point group &optional context)
20688 "Check if POINT is in match-group GROUP.
20689 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20690 match. If the match group does not exist or point is not inside it,
20691 return nil."
20692 (and (match-beginning group)
20693 (>= point (match-beginning group))
20694 (<= point (match-end group))
20695 (if context
20696 (list context (match-beginning group) (match-end group))
20697 t)))
20699 (defun org-switch-to-buffer-other-window (&rest args)
20700 "Switch to buffer in a second window on the current frame.
20701 In particular, do not allow pop-up frames.
20702 Returns the newly created buffer."
20703 (let (pop-up-frames special-display-buffer-names special-display-regexps
20704 special-display-function)
20705 (apply 'switch-to-buffer-other-window args)))
20707 (defun org-combine-plists (&rest plists)
20708 "Create a single property list from all plists in PLISTS.
20709 The process starts by copying the first list, and then setting properties
20710 from the other lists. Settings in the last list are the most significant
20711 ones and overrule settings in the other lists."
20712 (let ((rtn (copy-sequence (pop plists)))
20713 p v ls)
20714 (while plists
20715 (setq ls (pop plists))
20716 (while ls
20717 (setq p (pop ls) v (pop ls))
20718 (setq rtn (plist-put rtn p v))))
20719 rtn))
20721 (defun org-replace-escapes (string table)
20722 "Replace %-escapes in STRING with values in TABLE.
20723 TABLE is an association list with keys like \"%a\" and string values.
20724 The sequences in STRING may contain normal field width and padding information,
20725 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20726 so values can contain further %-escapes if they are define later in TABLE."
20727 (let ((tbl (copy-alist table))
20728 (case-fold-search nil)
20729 (pchg 0)
20730 e re rpl)
20731 (while (setq e (pop tbl))
20732 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20733 (when (and (cdr e) (string-match re (cdr e)))
20734 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20735 (safe "SREF"))
20736 (add-text-properties 0 3 (list 'sref sref) safe)
20737 (setcdr e (replace-match safe t t (cdr e)))))
20738 (while (string-match re string)
20739 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20740 (cdr e)))
20741 (setq string (replace-match rpl t t string))))
20742 (while (setq pchg (next-property-change pchg string))
20743 (let ((sref (get-text-property pchg 'sref string)))
20744 (when (and sref (string-match "SREF" string pchg))
20745 (setq string (replace-match sref t t string)))))
20746 string))
20748 (defun org-sublist (list start end)
20749 "Return a section of LIST, from START to END.
20750 Counting starts at 1."
20751 (let (rtn (c start))
20752 (setq list (nthcdr (1- start) list))
20753 (while (and list (<= c end))
20754 (push (pop list) rtn)
20755 (setq c (1+ c)))
20756 (nreverse rtn)))
20758 (defun org-find-base-buffer-visiting (file)
20759 "Like `find-buffer-visiting' but always return the base buffer and
20760 not an indirect buffer."
20761 (let ((buf (or (get-file-buffer file)
20762 (find-buffer-visiting file))))
20763 (if buf
20764 (or (buffer-base-buffer buf) buf)
20765 nil)))
20767 (defun org-image-file-name-regexp (&optional extensions)
20768 "Return regexp matching the file names of images.
20769 If EXTENSIONS is given, only match these."
20770 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20771 (image-file-name-regexp)
20772 (let ((image-file-name-extensions
20773 (or extensions
20774 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20775 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20776 (concat "\\."
20777 (regexp-opt (nconc (mapcar 'upcase
20778 image-file-name-extensions)
20779 image-file-name-extensions)
20781 "\\'"))))
20783 (defun org-file-image-p (file &optional extensions)
20784 "Return non-nil if FILE is an image."
20785 (save-match-data
20786 (string-match (org-image-file-name-regexp extensions) file)))
20788 (defun org-get-cursor-date ()
20789 "Return the date at cursor in as a time.
20790 This works in the calendar and in the agenda, anywhere else it just
20791 returns the current time."
20792 (let (date day defd)
20793 (cond
20794 ((eq major-mode 'calendar-mode)
20795 (setq date (calendar-cursor-to-date)
20796 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20797 ((eq major-mode 'org-agenda-mode)
20798 (setq day (get-text-property (point) 'day))
20799 (if day
20800 (setq date (calendar-gregorian-from-absolute day)
20801 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20802 (nth 2 date))))))
20803 (or defd (current-time))))
20805 (defun org-mark-subtree (&optional up)
20806 "Mark the current subtree.
20807 This puts point at the start of the current subtree, and mark at
20808 the end. If a numeric prefix UP is given, move up into the
20809 hierarchy of headlines by UP levels before marking the subtree."
20810 (interactive "P")
20811 (org-with-limited-levels
20812 (cond ((org-at-heading-p) (beginning-of-line))
20813 ((org-before-first-heading-p) (error "Not in a subtree"))
20814 (t (outline-previous-visible-heading 1))))
20815 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20816 (if (org-called-interactively-p 'any)
20817 (call-interactively 'org-mark-element)
20818 (org-mark-element)))
20820 ;;; Indentation
20822 (defun org-indent-line ()
20823 "Indent line depending on context."
20824 (interactive)
20825 (let* ((pos (point))
20826 (itemp (org-at-item-p))
20827 (case-fold-search t)
20828 (org-drawer-regexp (or org-drawer-regexp "\000"))
20829 (inline-task-p (and (featurep 'org-inlinetask)
20830 (org-inlinetask-in-task-p)))
20831 (inline-re (and inline-task-p
20832 (org-inlinetask-outline-regexp)))
20833 column)
20834 (if (and orgstruct-is-++ (eq pos (point)))
20835 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20836 (indent-according-to-mode))
20837 (beginning-of-line 1)
20838 (cond
20839 ;; Headings
20840 ((looking-at org-outline-regexp) (setq column 0))
20841 ;; Included files
20842 ((looking-at "#\\+include:") (setq column 0))
20843 ;; Footnote definition
20844 ((looking-at org-footnote-definition-re) (setq column 0))
20845 ;; Literal examples
20846 ((looking-at "[ \t]*:\\( \\|$\\)")
20847 (setq column (org-get-indentation))) ; do nothing
20848 ;; Lists
20849 ((ignore-errors (goto-char (org-in-item-p)))
20850 (setq column (if itemp
20851 (org-get-indentation)
20852 (org-list-item-body-column (point))))
20853 (goto-char pos))
20854 ;; Drawers
20855 ((and (looking-at "[ \t]*:END:")
20856 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20857 (save-excursion
20858 (goto-char (1- (match-beginning 1)))
20859 (setq column (current-column))))
20860 ;; Special blocks
20861 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20862 (save-excursion
20863 (re-search-backward
20864 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20865 (setq column (org-get-indentation (match-string 0))))
20866 ((and (not (looking-at "[ \t]*#\\+begin_"))
20867 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20868 (save-excursion
20869 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20870 (setq column
20871 (cond ((equal (downcase (match-string 1)) "src")
20872 ;; src blocks: let `org-edit-src-exit' handle them
20873 (org-get-indentation))
20874 ((equal (downcase (match-string 1)) "example")
20875 (max (org-get-indentation)
20876 (org-get-indentation (match-string 0))))
20878 (org-get-indentation (match-string 0))))))
20879 ;; This line has nothing special, look at the previous relevant
20880 ;; line to compute indentation
20882 (beginning-of-line 0)
20883 (while (and (not (bobp))
20884 (not (looking-at org-drawer-regexp))
20885 ;; When point started in an inline task, do not move
20886 ;; above task starting line.
20887 (not (and inline-task-p (looking-at inline-re)))
20888 ;; Skip drawers, blocks, empty lines, verbatim,
20889 ;; comments, tables, footnotes definitions, lists,
20890 ;; inline tasks.
20891 (or (and (looking-at "[ \t]*:END:")
20892 (re-search-backward org-drawer-regexp nil t))
20893 (and (looking-at "[ \t]*#\\+end_")
20894 (re-search-backward "[ \t]*#\\+begin_"nil t))
20895 (looking-at "[ \t]*[\n:#|]")
20896 (looking-at org-footnote-definition-re)
20897 (and (ignore-errors (goto-char (org-in-item-p)))
20898 (goto-char
20899 (org-list-get-top-point (org-list-struct))))
20900 (and (not inline-task-p)
20901 (featurep 'org-inlinetask)
20902 (org-inlinetask-in-task-p)
20903 (or (org-inlinetask-goto-beginning) t))))
20904 (beginning-of-line 0))
20905 (cond
20906 ;; There was an heading above.
20907 ((looking-at "\\*+[ \t]+")
20908 (if (not org-adapt-indentation)
20909 (setq column 0)
20910 (goto-char (match-end 0))
20911 (setq column (current-column))))
20912 ;; A drawer had started and is unfinished
20913 ((looking-at org-drawer-regexp)
20914 (goto-char (1- (match-beginning 1)))
20915 (setq column (current-column)))
20916 ;; Else, nothing noticeable found: get indentation and go on.
20917 (t (setq column (org-get-indentation))))))
20918 ;; Now apply indentation and move cursor accordingly
20919 (goto-char pos)
20920 (if (<= (current-column) (current-indentation))
20921 (org-indent-line-to column)
20922 (save-excursion (org-indent-line-to column)))
20923 ;; Special polishing for properties, see `org-property-format'
20924 (setq column (current-column))
20925 (beginning-of-line 1)
20926 (if (looking-at
20927 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20928 (replace-match (concat (match-string 1)
20929 (format org-property-format
20930 (match-string 2) (match-string 3)))
20931 t t))
20932 (org-move-to-column column))))
20934 (defun org-indent-drawer ()
20935 "Indent the drawer at point."
20936 (interactive)
20937 (let ((p (point))
20938 (e (and (save-excursion (re-search-forward ":END:" nil t))
20939 (match-end 0)))
20940 (folded
20941 (save-excursion
20942 (end-of-line)
20943 (when (overlays-at (point))
20944 (member 'invisible (overlay-properties
20945 (car (overlays-at (point)))))))))
20946 (when folded (org-cycle))
20947 (indent-for-tab-command)
20948 (while (and (move-beginning-of-line 2) (< (point) e))
20949 (indent-for-tab-command))
20950 (goto-char p)
20951 (when folded (org-cycle)))
20952 (message "Drawer at point indented"))
20954 (defun org-indent-block ()
20955 "Indent the block at point."
20956 (interactive)
20957 (let ((p (point))
20958 (case-fold-search t)
20959 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20960 (match-end 0)))
20961 (folded
20962 (save-excursion
20963 (end-of-line)
20964 (when (overlays-at (point))
20965 (member 'invisible (overlay-properties
20966 (car (overlays-at (point)))))))))
20967 (when folded (org-cycle))
20968 (indent-for-tab-command)
20969 (while (and (move-beginning-of-line 2) (< (point) e))
20970 (indent-for-tab-command))
20971 (goto-char p)
20972 (when folded (org-cycle)))
20973 (message "Block at point indented"))
20975 (defun org-indent-region (start end)
20976 "Indent region."
20977 (interactive "r")
20978 (save-excursion
20979 (let ((line-end (org-current-line end)))
20980 (goto-char start)
20981 (while (< (org-current-line) line-end)
20982 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20983 (t (call-interactively 'org-indent-line)))
20984 (move-beginning-of-line 2)))))
20987 ;;; Filling
20989 ;; We use our own fill-paragraph and auto-fill functions.
20991 ;; `org-fill-paragraph' relies on adaptive filling and context
20992 ;; checking. Appropriate `fill-prefix' is computed with
20993 ;; `org-adaptive-fill-function'.
20995 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20996 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20997 ;; `org-adaptive-fill-function' value. Internally,
20998 ;; `org-comment-line-break-function' breaks the line.
21000 ;; `org-setup-filling' installs filling and auto-filling related
21001 ;; variables during `org-mode' initialization.
21003 (defun org-setup-filling ()
21004 (interactive)
21005 ;; Prevent auto-fill from inserting unwanted new items.
21006 (when (boundp 'fill-nobreak-predicate)
21007 (org-set-local
21008 'fill-nobreak-predicate
21009 (org-uniquify
21010 (append fill-nobreak-predicate
21011 '(org-fill-paragraph-separate-nobreak-p
21012 org-fill-line-break-nobreak-p)))))
21013 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21014 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21015 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21016 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21018 (defvar org-element-paragraph-separate) ; org-element.el
21019 (defun org-fill-paragraph-separate-nobreak-p ()
21020 "Non-nil when a line break at point would insert a new item."
21021 (looking-at (substring org-element-paragraph-separate 1)))
21023 (defun org-fill-line-break-nobreak-p ()
21024 "Non-nil when a line break at point would create an Org line break."
21025 (save-excursion
21026 (skip-chars-backward "[ \t]")
21027 (skip-chars-backward "\\\\")
21028 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21030 (declare-function message-in-body-p "message" ())
21031 (defvar org-element--affiliated-re) ; From org-element.el
21032 (defun org-adaptive-fill-function ()
21033 "Compute a fill prefix for the current line.
21034 Return fill prefix, as a string, or nil if current line isn't
21035 meant to be filled."
21036 (org-with-wide-buffer
21037 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21038 ;; FIXME: This is really the job of orgstruct++-mode
21039 (let* ((p (line-beginning-position))
21040 (element (save-excursion (beginning-of-line)
21041 (org-element-at-point)))
21042 (type (org-element-type element))
21043 (post-affiliated
21044 (save-excursion
21045 (goto-char (org-element-property :begin element))
21046 (while (looking-at org-element--affiliated-re) (forward-line))
21047 (point))))
21048 (unless (< p post-affiliated)
21049 (case type
21050 (comment (looking-at "[ \t]*# ?") (match-string 0))
21051 (footnote-definition "")
21052 ((item plain-list)
21053 (make-string (org-list-item-body-column post-affiliated) ? ))
21054 (paragraph
21055 ;; Fill prefix is usually the same as the current line,
21056 ;; except if the paragraph is at the beginning of an item.
21057 (let ((parent (org-element-property :parent element)))
21058 (cond ((eq (org-element-type parent) 'item)
21059 (make-string (org-list-item-body-column
21060 (org-element-property :begin parent))
21061 ? ))
21062 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21063 (match-string 0))
21064 (t ""))))
21065 (comment-block
21066 ;; Only fill contents if P is within block boundaries.
21067 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21068 (forward-line)
21069 (point)))
21070 (cend (save-excursion
21071 (goto-char (org-element-property :end element))
21072 (skip-chars-backward " \r\t\n")
21073 (line-beginning-position))))
21074 (when (and (>= p cbeg) (< p cend))
21075 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21076 (match-string 0)
21077 ""))))))))))
21079 (declare-function message-goto-body "message" ())
21080 (defvar message-cite-prefix-regexp) ; From message.el
21081 (defvar org-element-all-objects) ; From org-element.el
21082 (defun org-fill-paragraph (&optional justify)
21083 "Fill element at point, when applicable.
21085 This function only applies to comment blocks, comments, example
21086 blocks and paragraphs. Also, as a special case, re-align table
21087 when point is at one.
21089 If JUSTIFY is non-nil (interactively, with prefix argument),
21090 justify as well. If `sentence-end-double-space' is non-nil, then
21091 period followed by one space does not end a sentence, so don't
21092 break a line there. The variable `fill-column' controls the
21093 width for filling.
21095 For convenience, when point is at a plain list, an item or
21096 a footnote definition, try to fill the first paragraph within."
21097 ;; Falls back on message-fill-paragraph when necessary
21098 (interactive)
21099 (if (and (derived-mode-p 'message-mode)
21100 (or (not (message-in-body-p))
21101 (save-excursion (move-beginning-of-line 1)
21102 (looking-at message-cite-prefix-regexp))))
21103 (let ((fill-paragraph-function
21104 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21105 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21106 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21107 (paragraph-separate
21108 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21109 (fill-paragraph nil))
21110 (save-excursion
21111 ;; Move to end of line in order to get the first paragraph
21112 ;; within a plain list or a footnote definition.
21113 (end-of-line)
21114 (let ((element (org-element-at-point)))
21115 ;; First check if point is in a blank line at the beginning of
21116 ;; the buffer. In that case, ignore filling.
21117 (if (< (point) (org-element-property :begin element)) t
21118 (case (org-element-type element)
21119 ;; Align Org tables, leave table.el tables as-is.
21120 (table-row (org-table-align) t)
21121 (table
21122 (when (eq (org-element-property :type element) 'org)
21123 (org-table-align))
21125 (paragraph
21126 ;; Paragraphs may contain `line-break' type objects.
21127 (let ((beg (max (point-min)
21128 (org-element-property :contents-begin element)))
21129 (end (min (point-max)
21130 (org-element-property :contents-end element))))
21131 ;; Do nothing if point is at an affiliated keyword.
21132 (if (< (point) beg) t
21133 (when (derived-mode-p 'message-mode)
21134 ;; In `message-mode', do not fill following
21135 ;; citation in current paragraph nor text before
21136 ;; message body.
21137 (let ((body-start (save-excursion (message-goto-body))))
21138 (when body-start (setq beg (max body-start beg))))
21139 (when (save-excursion
21140 (re-search-forward
21141 (concat "^" message-cite-prefix-regexp) end t))
21142 (setq end (match-beginning 0))))
21143 ;; Fill paragraph, taking line breaks into
21144 ;; consideration. For that, slice the paragraph
21145 ;; using line breaks as separators, and fill the
21146 ;; parts in reverse order to avoid messing with
21147 ;; markers.
21148 (save-excursion
21149 (goto-char end)
21150 (mapc
21151 (lambda (pos)
21152 (fill-region-as-paragraph pos (point) justify)
21153 (goto-char pos))
21154 ;; Find the list of ending positions for line
21155 ;; breaks in the current paragraph. Add paragraph
21156 ;; beginning to include first slice.
21157 (nreverse
21158 (cons
21160 (org-element-map
21161 (org-element--parse-objects
21162 beg end nil org-element-all-objects)
21163 'line-break
21164 (lambda (lb) (org-element-property :end lb)))))))
21165 t)))
21166 ;; Contents of `comment-block' type elements should be
21167 ;; filled as plain text, but only if point is within block
21168 ;; markers.
21169 (comment-block
21170 (let* ((case-fold-search t)
21171 (beg (save-excursion
21172 (goto-char (org-element-property :begin element))
21173 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21174 (forward-line)
21175 (point)))
21176 (end (save-excursion
21177 (goto-char (org-element-property :end element))
21178 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21179 (line-beginning-position))))
21180 (when (and (>= (point) beg) (< (point) end))
21181 (fill-region-as-paragraph
21182 (save-excursion
21183 (end-of-line)
21184 (re-search-backward "^[ \t]*$" beg 'move)
21185 (line-beginning-position))
21186 (save-excursion
21187 (beginning-of-line)
21188 (re-search-forward "^[ \t]*$" end 'move)
21189 (line-beginning-position))
21190 justify)))
21192 ;; Fill comments.
21193 (comment (fill-comment-paragraph justify))
21194 ;; Ignore every other element.
21195 (otherwise t)))))))
21197 (defun org-auto-fill-function ()
21198 "Auto-fill function."
21199 ;; Check if auto-filling is meaningful.
21200 (let ((fc (current-fill-column)))
21201 (when (and fc (> (current-column) fc))
21202 (let ((fill-prefix (org-adaptive-fill-function)))
21203 (when fill-prefix (do-auto-fill))))))
21205 (defun org-comment-line-break-function (&optional soft)
21206 "Break line at point and indent, continuing comment if within one.
21207 The inserted newline is marked hard if variable
21208 `use-hard-newlines' is true, unless optional argument SOFT is
21209 non-nil."
21210 (if soft (insert-and-inherit ?\n) (newline 1))
21211 (save-excursion (forward-char -1) (delete-horizontal-space))
21212 (delete-horizontal-space)
21213 (indent-to-left-margin)
21214 (insert-before-markers-and-inherit fill-prefix))
21217 ;;; Comments
21219 ;; Org comments syntax is quite complex. It requires the entire line
21220 ;; to be just a comment. Also, even with the right syntax at the
21221 ;; beginning of line, some some elements (i.e. verse-block or
21222 ;; example-block) don't accept comments. Usual Emacs comment commands
21223 ;; cannot cope with those requirements. Therefore, Org replaces them.
21225 ;; Org still relies on `comment-dwim', but cannot trust
21226 ;; `comment-only-p'. So, `comment-region-function' and
21227 ;; `uncomment-region-function' both point
21228 ;; to`org-comment-or-uncomment-region'. Eventually,
21229 ;; `org-insert-comment' takes care of insertion of comments at the
21230 ;; beginning of line.
21232 ;; `org-setup-comments-handling' install comments related variables
21233 ;; during `org-mode' initialization.
21235 (defun org-setup-comments-handling ()
21236 (interactive)
21237 (org-set-local 'comment-use-syntax nil)
21238 (org-set-local 'comment-start "# ")
21239 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21240 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21241 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21242 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21244 (defun org-insert-comment ()
21245 "Insert an empty comment above current line.
21246 If the line is empty, insert comment at its beginning."
21247 (beginning-of-line)
21248 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21249 (org-indent-line)
21250 (insert "# "))
21252 (defvar comment-empty-lines) ; From newcomment.el.
21253 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21254 "Comment or uncomment each non-blank line in the region.
21255 Uncomment each non-blank line between BEG and END if it only
21256 contains commented lines. Otherwise, comment them."
21257 (save-restriction
21258 ;; Restrict region
21259 (narrow-to-region (save-excursion (goto-char beg)
21260 (skip-chars-forward " \r\t\n" end)
21261 (line-beginning-position))
21262 (save-excursion (goto-char end)
21263 (skip-chars-backward " \r\t\n" beg)
21264 (line-end-position)))
21265 (let ((uncommentp
21266 ;; UNCOMMENTP is non-nil when every non blank line between
21267 ;; BEG and END is a comment.
21268 (save-excursion
21269 (goto-char (point-min))
21270 (while (and (not (eobp))
21271 (let ((element (org-element-at-point)))
21272 (and (eq (org-element-type element) 'comment)
21273 (goto-char (min (point-max)
21274 (org-element-property
21275 :end element)))))))
21276 (eobp))))
21277 (if uncommentp
21278 ;; Only blank lines and comments in region: uncomment it.
21279 (save-excursion
21280 (goto-char (point-min))
21281 (while (not (eobp))
21282 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21283 (replace-match "" nil nil nil 1))
21284 (forward-line)))
21285 ;; Comment each line in region.
21286 (let ((min-indent (point-max)))
21287 ;; First find the minimum indentation across all lines.
21288 (save-excursion
21289 (goto-char (point-min))
21290 (while (and (not (eobp)) (not (zerop min-indent)))
21291 (unless (looking-at "[ \t]*$")
21292 (setq min-indent (min min-indent (current-indentation))))
21293 (forward-line)))
21294 ;; Then loop over all lines.
21295 (save-excursion
21296 (goto-char (point-min))
21297 (while (not (eobp))
21298 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21299 (org-move-to-column min-indent t)
21300 (insert comment-start))
21301 (forward-line))))))))
21304 ;;; Other stuff.
21306 (defun org-toggle-fixed-width-section (arg)
21307 "Toggle the fixed-width export.
21308 If there is no active region, the QUOTE keyword at the current headline is
21309 inserted or removed. When present, it causes the text between this headline
21310 and the next to be exported as fixed-width text, and unmodified.
21311 If there is an active region, this command adds or removes a colon as the
21312 first character of this line. If the first character of a line is a colon,
21313 this line is also exported in fixed-width font."
21314 (interactive "P")
21315 (let* ((cc 0)
21316 (regionp (org-region-active-p))
21317 (beg (if regionp (region-beginning) (point)))
21318 (end (if regionp (region-end)))
21319 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21320 (case-fold-search nil)
21321 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21322 off)
21323 (if regionp
21324 (save-excursion
21325 (goto-char beg)
21326 (setq cc (current-column))
21327 (beginning-of-line 1)
21328 (setq off (looking-at re))
21329 (while (> nlines 0)
21330 (setq nlines (1- nlines))
21331 (beginning-of-line 1)
21332 (cond
21333 (arg
21334 (org-move-to-column cc t)
21335 (insert ": \n")
21336 (forward-line -1))
21337 ((and off (looking-at re))
21338 (replace-match "" t t nil 1))
21339 ((not off) (org-move-to-column cc t) (insert ": ")))
21340 (forward-line 1)))
21341 (save-excursion
21342 (org-back-to-heading)
21343 (cond
21344 ((looking-at (format org-heading-keyword-regexp-format
21345 org-quote-string))
21346 (goto-char (match-end 1))
21347 (looking-at (concat " +" org-quote-string))
21348 (replace-match "" t t)
21349 (when (eolp) (insert " ")))
21350 ((looking-at org-outline-regexp)
21351 (goto-char (match-end 0))
21352 (insert org-quote-string " ")))))))
21354 (defun org-reftex-citation ()
21355 "Use reftex-citation to insert a citation into the buffer.
21356 This looks for a line like
21358 #+BIBLIOGRAPHY: foo plain option:-d
21360 and derives from it that foo.bib is the bibliography file relevant
21361 for this document. It then installs the necessary environment for RefTeX
21362 to work in this buffer and calls `reftex-citation' to insert a citation
21363 into the buffer.
21365 Export of such citations to both LaTeX and HTML is handled by the contributed
21366 package org-exp-bibtex by Taru Karttunen."
21367 (interactive)
21368 (let ((reftex-docstruct-symbol 'rds)
21369 (reftex-cite-format "\\cite{%l}")
21370 rds bib)
21371 (save-excursion
21372 (save-restriction
21373 (widen)
21374 (let ((case-fold-search t)
21375 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21376 (if (not (save-excursion
21377 (or (re-search-forward re nil t)
21378 (re-search-backward re nil t))))
21379 (error "No bibliography defined in file")
21380 (setq bib (concat (match-string 1) ".bib")
21381 rds (list (list 'bib bib)))))))
21382 (call-interactively 'reftex-citation)))
21384 ;;;; Functions extending outline functionality
21386 (defun org-beginning-of-line (&optional arg)
21387 "Go to the beginning of the current line. If that is invisible, continue
21388 to a visible line beginning. This makes the function of C-a more intuitive.
21389 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21390 first attempt, and only move to after the tags when the cursor is already
21391 beyond the end of the headline."
21392 (interactive "P")
21393 (let ((pos (point))
21394 (special (if (consp org-special-ctrl-a/e)
21395 (car org-special-ctrl-a/e)
21396 org-special-ctrl-a/e))
21397 refpos)
21398 (if (org-bound-and-true-p line-move-visual)
21399 (beginning-of-visual-line 1)
21400 (beginning-of-line 1))
21401 (if (and arg (fboundp 'move-beginning-of-line))
21402 (call-interactively 'move-beginning-of-line)
21403 (if (bobp)
21405 (backward-char 1)
21406 (if (org-truely-invisible-p)
21407 (while (and (not (bobp)) (org-truely-invisible-p))
21408 (backward-char 1)
21409 (beginning-of-line 1))
21410 (forward-char 1))))
21411 (when special
21412 (cond
21413 ((and (looking-at org-complex-heading-regexp)
21414 (= (char-after (match-end 1)) ?\ ))
21415 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21416 (point-at-eol)))
21417 (goto-char
21418 (if (eq special t)
21419 (cond ((> pos refpos) refpos)
21420 ((= pos (point)) refpos)
21421 (t (point)))
21422 (cond ((> pos (point)) (point))
21423 ((not (eq last-command this-command)) (point))
21424 (t refpos)))))
21425 ((org-at-item-p)
21426 ;; Being at an item and not looking at an the item means point
21427 ;; was previously moved to beginning of a visual line, which
21428 ;; doesn't contain the item. Therefore, do nothing special,
21429 ;; just stay here.
21430 (when (looking-at org-list-full-item-re)
21431 ;; Set special position at first white space character after
21432 ;; bullet, and check-box, if any.
21433 (let ((after-bullet
21434 (let ((box (match-end 3)))
21435 (if (not box) (match-end 1)
21436 (let ((after (char-after box)))
21437 (if (and after (= after ? )) (1+ box) box))))))
21438 ;; Special case: Move point to special position when
21439 ;; currently after it or at beginning of line.
21440 (if (eq special t)
21441 (when (or (> pos after-bullet) (= (point) pos))
21442 (goto-char after-bullet))
21443 ;; Reversed case: Move point to special position when
21444 ;; point was already at beginning of line and command is
21445 ;; repeated.
21446 (when (and (= (point) pos) (eq last-command this-command))
21447 (goto-char after-bullet))))))))
21448 (org-no-warnings
21449 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21451 (defun org-end-of-line (&optional arg)
21452 "Go to the end of the line.
21453 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21454 first attempt, and only move to after the tags when the cursor is already
21455 beyond the end of the headline."
21456 (interactive "P")
21457 (let ((special (if (consp org-special-ctrl-a/e)
21458 (cdr org-special-ctrl-a/e)
21459 org-special-ctrl-a/e)))
21460 (cond
21461 ((or (not special) arg
21462 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21463 (call-interactively
21464 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21465 ((fboundp 'move-end-of-line) 'move-end-of-line)
21466 (t 'end-of-line))))
21467 ((org-at-heading-p)
21468 (let ((pos (point)))
21469 (beginning-of-line 1)
21470 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21471 (if (eq special t)
21472 (if (or (< pos (match-beginning 1))
21473 (= pos (match-end 0)))
21474 (goto-char (match-beginning 1))
21475 (goto-char (match-end 0)))
21476 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21477 (goto-char (match-end 0))
21478 (goto-char (match-beginning 1))))
21479 (call-interactively (if (fboundp 'move-end-of-line)
21480 'move-end-of-line
21481 'end-of-line)))))
21482 ((org-at-drawer-p)
21483 (move-end-of-line 1)
21484 (when (overlays-at (1- (point))) (backward-char 1)))
21485 ;; At an item: Move before any hidden text.
21486 (t (call-interactively
21487 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21488 ((fboundp 'move-end-of-line) 'move-end-of-line)
21489 (t 'end-of-line)))))
21490 (org-no-warnings
21491 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21493 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21494 (define-key org-mode-map "\C-e" 'org-end-of-line)
21496 (defun org-backward-sentence (&optional arg)
21497 "Go to beginning of sentence, or beginning of table field.
21498 This will call `backward-sentence' or `org-table-beginning-of-field',
21499 depending on context."
21500 (interactive "P")
21501 (cond
21502 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21503 (t (call-interactively 'backward-sentence))))
21505 (defun org-forward-sentence (&optional arg)
21506 "Go to end of sentence, or end of table field.
21507 This will call `forward-sentence' or `org-table-end-of-field',
21508 depending on context."
21509 (interactive "P")
21510 (cond
21511 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21512 (t (call-interactively 'forward-sentence))))
21514 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21515 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21517 (defun org-kill-line (&optional arg)
21518 "Kill line, to tags or end of line."
21519 (interactive "P")
21520 (cond
21521 ((or (not org-special-ctrl-k)
21522 (bolp)
21523 (not (org-at-heading-p)))
21524 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21525 org-ctrl-k-protect-subtree)
21526 (if (or (eq org-ctrl-k-protect-subtree 'error)
21527 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21528 (error "C-k aborted - would kill hidden subtree")))
21529 (call-interactively
21530 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21531 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21532 (kill-region (point) (match-beginning 1))
21533 (org-set-tags nil t))
21534 (t (kill-region (point) (point-at-eol)))))
21536 (define-key org-mode-map "\C-k" 'org-kill-line)
21538 (defun org-yank (&optional arg)
21539 "Yank. If the kill is a subtree, treat it specially.
21540 This command will look at the current kill and check if is a single
21541 subtree, or a series of subtrees[1]. If it passes the test, and if the
21542 cursor is at the beginning of a line or after the stars of a currently
21543 empty headline, then the yank is handled specially. How exactly depends
21544 on the value of the following variables, both set by default.
21546 org-yank-folded-subtrees
21547 When set, the subtree(s) will be folded after insertion, but only
21548 if doing so would now swallow text after the yanked text.
21550 org-yank-adjusted-subtrees
21551 When set, the subtree will be promoted or demoted in order to
21552 fit into the local outline tree structure, which means that the level
21553 will be adjusted so that it becomes the smaller one of the two
21554 *visible* surrounding headings.
21556 Any prefix to this command will cause `yank' to be called directly with
21557 no special treatment. In particular, a simple \\[universal-argument] prefix \
21558 will just
21559 plainly yank the text as it is.
21561 \[1] The test checks if the first non-white line is a heading
21562 and if there are no other headings with fewer stars."
21563 (interactive "P")
21564 (org-yank-generic 'yank arg))
21566 (defun org-yank-generic (command arg)
21567 "Perform some yank-like command.
21569 This function implements the behavior described in the `org-yank'
21570 documentation. However, it has been generalized to work for any
21571 interactive command with similar behavior."
21573 ;; pretend to be command COMMAND
21574 (setq this-command command)
21576 (if arg
21577 (call-interactively command)
21579 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21580 (and (org-kill-is-subtree-p)
21581 (or (bolp)
21582 (and (looking-at "[ \t]*$")
21583 (string-match
21584 "\\`\\*+\\'"
21585 (buffer-substring (point-at-bol) (point)))))))
21586 swallowp)
21587 (cond
21588 ((and subtreep org-yank-folded-subtrees)
21589 (let ((beg (point))
21590 end)
21591 (if (and subtreep org-yank-adjusted-subtrees)
21592 (org-paste-subtree nil nil 'for-yank)
21593 (call-interactively command))
21595 (setq end (point))
21596 (goto-char beg)
21597 (when (and (bolp) subtreep
21598 (not (setq swallowp
21599 (org-yank-folding-would-swallow-text beg end))))
21600 (org-with-limited-levels
21601 (or (looking-at org-outline-regexp)
21602 (re-search-forward org-outline-regexp-bol end t))
21603 (while (and (< (point) end) (looking-at org-outline-regexp))
21604 (hide-subtree)
21605 (org-cycle-show-empty-lines 'folded)
21606 (condition-case nil
21607 (outline-forward-same-level 1)
21608 (error (goto-char end))))))
21609 (when swallowp
21610 (message
21611 "Inserted text not folded because that would swallow text"))
21613 (goto-char end)
21614 (skip-chars-forward " \t\n\r")
21615 (beginning-of-line 1)
21616 (push-mark beg 'nomsg)))
21617 ((and subtreep org-yank-adjusted-subtrees)
21618 (let ((beg (point-at-bol)))
21619 (org-paste-subtree nil nil 'for-yank)
21620 (push-mark beg 'nomsg)))
21622 (call-interactively command))))))
21624 (defun org-yank-folding-would-swallow-text (beg end)
21625 "Would hide-subtree at BEG swallow any text after END?"
21626 (let (level)
21627 (org-with-limited-levels
21628 (save-excursion
21629 (goto-char beg)
21630 (when (or (looking-at org-outline-regexp)
21631 (re-search-forward org-outline-regexp-bol end t))
21632 (setq level (org-outline-level)))
21633 (goto-char end)
21634 (skip-chars-forward " \t\r\n\v\f")
21635 (if (or (eobp)
21636 (and (bolp) (looking-at org-outline-regexp)
21637 (<= (org-outline-level) level)))
21638 nil ; Nothing would be swallowed
21639 t))))) ; something would swallow
21641 (define-key org-mode-map "\C-y" 'org-yank)
21643 (defun org-truely-invisible-p ()
21644 "Check if point is at a character currently not visible.
21645 This version does not only check the character property, but also
21646 `visible-mode'."
21647 ;; Early versions of noutline don't have `outline-invisible-p'.
21648 (if (org-bound-and-true-p visible-mode)
21650 (outline-invisible-p)))
21652 (defun org-invisible-p2 ()
21653 "Check if point is at a character currently not visible."
21654 (save-excursion
21655 (if (and (eolp) (not (bobp))) (backward-char 1))
21656 ;; Early versions of noutline don't have `outline-invisible-p'.
21657 (outline-invisible-p)))
21659 (defun org-back-to-heading (&optional invisible-ok)
21660 "Call `outline-back-to-heading', but provide a better error message."
21661 (condition-case nil
21662 (outline-back-to-heading invisible-ok)
21663 (error (error "Before first headline at position %d in buffer %s"
21664 (point) (current-buffer)))))
21666 (defun org-before-first-heading-p ()
21667 "Before first heading?"
21668 (save-excursion
21669 (end-of-line)
21670 (null (re-search-backward org-outline-regexp-bol nil t))))
21672 (defun org-at-heading-p (&optional ignored)
21673 (outline-on-heading-p t))
21674 ;; Compatibility alias with Org versions < 7.8.03
21675 (defalias 'org-on-heading-p 'org-at-heading-p)
21677 (defun org-at-comment-p nil
21678 "Is cursor in a line starting with a # character?"
21679 (save-excursion
21680 (beginning-of-line)
21681 (looking-at "^#")))
21683 (defun org-at-drawer-p nil
21684 "Is cursor at a drawer keyword?"
21685 (save-excursion
21686 (move-beginning-of-line 1)
21687 (looking-at org-drawer-regexp)))
21689 (defun org-at-block-p nil
21690 "Is cursor at a block keyword?"
21691 (save-excursion
21692 (move-beginning-of-line 1)
21693 (looking-at org-block-regexp)))
21695 (defun org-point-at-end-of-empty-headline ()
21696 "If point is at the end of an empty headline, return t, else nil.
21697 If the heading only contains a TODO keyword, it is still still considered
21698 empty."
21699 (and (looking-at "[ \t]*$")
21700 (when org-todo-line-regexp
21701 (save-excursion
21702 (beginning-of-line 1)
21703 (let ((case-fold-search nil))
21704 (looking-at org-todo-line-regexp)
21705 (string= (match-string 3) ""))))))
21707 (defun org-at-heading-or-item-p ()
21708 (or (org-at-heading-p) (org-at-item-p)))
21710 (defun org-at-target-p ()
21711 (or (org-in-regexp org-radio-target-regexp)
21712 (org-in-regexp org-target-regexp)))
21713 ;; Compatibility alias with Org versions < 7.8.03
21714 (defalias 'org-on-target-p 'org-at-target-p)
21716 (defun org-up-heading-all (arg)
21717 "Move to the heading line of which the present line is a subheading.
21718 This function considers both visible and invisible heading lines.
21719 With argument, move up ARG levels."
21720 (if (fboundp 'outline-up-heading-all)
21721 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21722 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21724 (defun org-up-heading-safe ()
21725 "Move to the heading line of which the present line is a subheading.
21726 This version will not throw an error. It will return the level of the
21727 headline found, or nil if no higher level is found.
21729 Also, this function will be a lot faster than `outline-up-heading',
21730 because it relies on stars being the outline starters. This can really
21731 make a significant difference in outlines with very many siblings."
21732 (let (start-level re)
21733 (org-back-to-heading t)
21734 (setq start-level (funcall outline-level))
21735 (if (equal start-level 1)
21737 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21738 (if (re-search-backward re nil t)
21739 (funcall outline-level)))))
21741 (defun org-first-sibling-p ()
21742 "Is this heading the first child of its parents?"
21743 (interactive)
21744 (let ((re org-outline-regexp-bol)
21745 level l)
21746 (unless (org-at-heading-p t)
21747 (error "Not at a heading"))
21748 (setq level (funcall outline-level))
21749 (save-excursion
21750 (if (not (re-search-backward re nil t))
21752 (setq l (funcall outline-level))
21753 (< l level)))))
21755 (defun org-goto-sibling (&optional previous)
21756 "Goto the next sibling, even if it is invisible.
21757 When PREVIOUS is set, go to the previous sibling instead. Returns t
21758 when a sibling was found. When none is found, return nil and don't
21759 move point."
21760 (let ((fun (if previous 're-search-backward 're-search-forward))
21761 (pos (point))
21762 (re org-outline-regexp-bol)
21763 level l)
21764 (when (condition-case nil (org-back-to-heading t) (error nil))
21765 (setq level (funcall outline-level))
21766 (catch 'exit
21767 (or previous (forward-char 1))
21768 (while (funcall fun re nil t)
21769 (setq l (funcall outline-level))
21770 (when (< l level) (goto-char pos) (throw 'exit nil))
21771 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21772 (goto-char pos)
21773 nil))))
21775 (defun org-show-siblings ()
21776 "Show all siblings of the current headline."
21777 (save-excursion
21778 (while (org-goto-sibling) (org-flag-heading nil)))
21779 (save-excursion
21780 (while (org-goto-sibling 'previous)
21781 (org-flag-heading nil))))
21783 (defun org-goto-first-child ()
21784 "Goto the first child, even if it is invisible.
21785 Return t when a child was found. Otherwise don't move point and
21786 return nil."
21787 (let (level (pos (point)) (re org-outline-regexp-bol))
21788 (when (condition-case nil (org-back-to-heading t) (error nil))
21789 (setq level (outline-level))
21790 (forward-char 1)
21791 (if (and (re-search-forward re nil t) (> (outline-level) level))
21792 (progn (goto-char (match-beginning 0)) t)
21793 (goto-char pos) nil))))
21795 (defun org-show-hidden-entry ()
21796 "Show an entry where even the heading is hidden."
21797 (save-excursion
21798 (org-show-entry)))
21800 (defun org-flag-heading (flag &optional entry)
21801 "Flag the current heading. FLAG non-nil means make invisible.
21802 When ENTRY is non-nil, show the entire entry."
21803 (save-excursion
21804 (org-back-to-heading t)
21805 ;; Check if we should show the entire entry
21806 (if entry
21807 (progn
21808 (org-show-entry)
21809 (save-excursion
21810 (and (outline-next-heading)
21811 (org-flag-heading nil))))
21812 (outline-flag-region (max (point-min) (1- (point)))
21813 (save-excursion (outline-end-of-heading) (point))
21814 flag))))
21816 (defun org-get-next-sibling ()
21817 "Move to next heading of the same level, and return point.
21818 If there is no such heading, return nil.
21819 This is like outline-next-sibling, but invisible headings are ok."
21820 (let ((level (funcall outline-level)))
21821 (outline-next-heading)
21822 (while (and (not (eobp)) (> (funcall outline-level) level))
21823 (outline-next-heading))
21824 (if (or (eobp) (< (funcall outline-level) level))
21826 (point))))
21828 (defun org-get-last-sibling ()
21829 "Move to previous heading of the same level, and return point.
21830 If there is no such heading, return nil."
21831 (let ((opoint (point))
21832 (level (funcall outline-level)))
21833 (outline-previous-heading)
21834 (when (and (/= (point) opoint) (outline-on-heading-p t))
21835 (while (and (> (funcall outline-level) level)
21836 (not (bobp)))
21837 (outline-previous-heading))
21838 (if (< (funcall outline-level) level)
21840 (point)))))
21842 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21843 "Goto to the end of a subtree."
21844 ;; This contains an exact copy of the original function, but it uses
21845 ;; `org-back-to-heading', to make it work also in invisible
21846 ;; trees. And is uses an invisible-ok argument.
21847 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21848 ;; Furthermore, when used inside Org, finding the end of a large subtree
21849 ;; with many children and grandchildren etc, this can be much faster
21850 ;; than the outline version.
21851 (org-back-to-heading invisible-ok)
21852 (let ((first t)
21853 (level (funcall outline-level)))
21854 (if (and (derived-mode-p 'org-mode) (< level 1000))
21855 ;; A true heading (not a plain list item), in Org-mode
21856 ;; This means we can easily find the end by looking
21857 ;; only for the right number of stars. Using a regexp to do
21858 ;; this is so much faster than using a Lisp loop.
21859 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21860 (forward-char 1)
21861 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21862 ;; something else, do it the slow way
21863 (while (and (not (eobp))
21864 (or first (> (funcall outline-level) level)))
21865 (setq first nil)
21866 (outline-next-heading)))
21867 (unless to-heading
21868 (if (memq (preceding-char) '(?\n ?\^M))
21869 (progn
21870 ;; Go to end of line before heading
21871 (forward-char -1)
21872 (if (memq (preceding-char) '(?\n ?\^M))
21873 ;; leave blank line before heading
21874 (forward-char -1))))))
21875 (point))
21877 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21878 "Use Org version in org-mode, for dramatic speed-up."
21879 (if (derived-mode-p 'org-mode)
21880 (progn
21881 (org-end-of-subtree nil t)
21882 (unless (eobp) (backward-char 1)))
21883 ad-do-it))
21885 (defun org-end-of-meta-data-and-drawers ()
21886 "Jump to the first text after meta data and drawers in the current entry.
21887 This will move over empty lines, lines with planning time stamps,
21888 clocking lines, and drawers."
21889 (org-back-to-heading t)
21890 (let ((end (save-excursion (outline-next-heading) (point)))
21891 (re (concat "\\(" org-drawer-regexp "\\)"
21892 "\\|" "[ \t]*" org-keyword-time-regexp)))
21893 (forward-line 1)
21894 (while (re-search-forward re end t)
21895 (if (not (match-end 1))
21896 ;; empty or planning line
21897 (forward-line 1)
21898 ;; a drawer, find the end
21899 (re-search-forward "^[ \t]*:END:" end 'move)
21900 (forward-line 1)))
21901 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21902 (point)))
21904 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21905 "Move forward to the arg'th subheading at same level as this one.
21906 Stop at the first and last subheadings of a superior heading.
21907 Normally this only looks at visible headings, but when INVISIBLE-OK is
21908 non-nil it will also look at invisible ones."
21909 (interactive "p")
21910 (org-back-to-heading invisible-ok)
21911 (org-at-heading-p)
21912 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21913 (re (format "^\\*\\{1,%d\\} " level))
21915 (forward-char 1)
21916 (while (> arg 0)
21917 (while (and (re-search-forward re nil 'move)
21918 (setq l (- (match-end 0) (match-beginning 0) 1))
21919 (= l level)
21920 (not invisible-ok)
21921 (progn (backward-char 1) (outline-invisible-p)))
21922 (if (< l level) (setq arg 1)))
21923 (setq arg (1- arg)))
21924 (beginning-of-line 1)))
21926 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21927 "Move backward to the arg'th subheading at same level as this one.
21928 Stop at the first and last subheadings of a superior heading."
21929 (interactive "p")
21930 (org-back-to-heading)
21931 (org-at-heading-p)
21932 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21933 (re (format "^\\*\\{1,%d\\} " level))
21935 (while (> arg 0)
21936 (while (and (re-search-backward re nil 'move)
21937 (setq l (- (match-end 0) (match-beginning 0) 1))
21938 (= l level)
21939 (not invisible-ok)
21940 (outline-invisible-p))
21941 (if (< l level) (setq arg 1)))
21942 (setq arg (1- arg)))))
21944 ;;;###autoload
21945 (defun org-forward-element ()
21946 "Move forward by one element.
21947 Move to the next element at the same level, when possible."
21948 (interactive)
21949 (cond ((eobp) (error "Cannot move further down"))
21950 ((org-with-limited-levels (org-at-heading-p))
21951 (let ((origin (point)))
21952 (org-forward-heading-same-level 1)
21953 (unless (org-with-limited-levels (org-at-heading-p))
21954 (goto-char origin)
21955 (error "Cannot move further down"))))
21957 (let* ((elem (org-element-at-point))
21958 (end (org-element-property :end elem))
21959 (parent (org-element-property :parent elem)))
21960 (if (and parent (= (org-element-property :contents-end parent) end))
21961 (goto-char (org-element-property :end parent))
21962 (goto-char end))))))
21964 ;;;###autoload
21965 (defun org-backward-element ()
21966 "Move backward by one element.
21967 Move to the previous element at the same level, when possible."
21968 (interactive)
21969 (cond ((bobp) (error "Cannot move further up"))
21970 ((org-with-limited-levels (org-at-heading-p))
21971 ;; At an headline, move to the previous one, if any, or stay
21972 ;; here.
21973 (let ((origin (point)))
21974 (org-backward-heading-same-level 1)
21975 (unless (org-with-limited-levels (org-at-heading-p))
21976 (goto-char origin)
21977 (error "Cannot move further up"))))
21979 (let* ((trail (org-element-at-point 'keep-trail))
21980 (elem (car trail))
21981 (prev-elem (nth 1 trail))
21982 (beg (org-element-property :begin elem)))
21983 (cond
21984 ;; Move to beginning of current element if point isn't
21985 ;; there already.
21986 ((/= (point) beg) (goto-char beg))
21987 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21988 ((org-before-first-heading-p) (goto-char (point-min)))
21989 (t (org-back-to-heading)))))))
21991 ;;;###autoload
21992 (defun org-up-element ()
21993 "Move to upper element."
21994 (interactive)
21995 (if (org-with-limited-levels (org-at-heading-p))
21996 (unless (org-up-heading-safe) (error "No surrounding element"))
21997 (let* ((elem (org-element-at-point))
21998 (parent (org-element-property :parent elem)))
21999 (if parent (goto-char (org-element-property :begin parent))
22000 (if (org-with-limited-levels (org-before-first-heading-p))
22001 (error "No surrounding element")
22002 (org-with-limited-levels (org-back-to-heading)))))))
22004 ;;;###autoload
22005 (defvar org-element-greater-elements)
22006 (defun org-down-element ()
22007 "Move to inner element."
22008 (interactive)
22009 (let ((element (org-element-at-point)))
22010 (cond
22011 ((memq (org-element-type element) '(plain-list table))
22012 (goto-char (org-element-property :contents-begin element))
22013 (forward-char))
22014 ((memq (org-element-type element) org-element-greater-elements)
22015 ;; If contents are hidden, first disclose them.
22016 (when (org-element-property :hiddenp element) (org-cycle))
22017 (goto-char (or (org-element-property :contents-begin element)
22018 (error "No content for this element"))))
22019 (t (error "No inner element")))))
22021 ;;;###autoload
22022 (defun org-drag-element-backward ()
22023 "Move backward element at point."
22024 (interactive)
22025 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22026 (let* ((trail (org-element-at-point 'keep-trail))
22027 (elem (car trail))
22028 (prev-elem (nth 1 trail)))
22029 ;; Error out if no previous element or previous element is
22030 ;; a parent of the current one.
22031 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22032 (error "Cannot drag element backward")
22033 (let ((pos (point)))
22034 (org-element-swap-A-B prev-elem elem)
22035 (goto-char (+ (org-element-property :begin prev-elem)
22036 (- pos (org-element-property :begin elem)))))))))
22038 ;;;###autoload
22039 (defun org-drag-element-forward ()
22040 "Move forward element at point."
22041 (interactive)
22042 (let* ((pos (point))
22043 (elem (org-element-at-point)))
22044 (when (= (point-max) (org-element-property :end elem))
22045 (error "Cannot drag element forward"))
22046 (goto-char (org-element-property :end elem))
22047 (let ((next-elem (org-element-at-point)))
22048 (when (or (org-element-nested-p elem next-elem)
22049 (and (eq (org-element-type next-elem) 'headline)
22050 (not (eq (org-element-type elem) 'headline))))
22051 (goto-char pos)
22052 (error "Cannot drag element forward"))
22053 ;; Compute new position of point: it's shifted by NEXT-ELEM
22054 ;; body's length (without final blanks) and by the length of
22055 ;; blanks between ELEM and NEXT-ELEM.
22056 (let ((size-next (- (save-excursion
22057 (goto-char (org-element-property :end next-elem))
22058 (skip-chars-backward " \r\t\n")
22059 (forward-line)
22060 ;; Small correction if buffer doesn't end
22061 ;; with a newline character.
22062 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22063 (org-element-property :begin next-elem)))
22064 (size-blank (- (org-element-property :end elem)
22065 (save-excursion
22066 (goto-char (org-element-property :end elem))
22067 (skip-chars-backward " \r\t\n")
22068 (forward-line)
22069 (point)))))
22070 (org-element-swap-A-B elem next-elem)
22071 (goto-char (+ pos size-next size-blank))))))
22073 ;;;###autoload
22074 (defun org-mark-element ()
22075 "Put point at beginning of this element, mark at end.
22077 Interactively, if this command is repeated or (in Transient Mark
22078 mode) if the mark is active, it marks the next element after the
22079 ones already marked."
22080 (interactive)
22081 (let (deactivate-mark)
22082 (if (and (org-called-interactively-p 'any)
22083 (or (and (eq last-command this-command) (mark t))
22084 (and transient-mark-mode mark-active)))
22085 (set-mark
22086 (save-excursion
22087 (goto-char (mark))
22088 (goto-char (org-element-property :end (org-element-at-point)))))
22089 (let ((element (org-element-at-point)))
22090 (end-of-line)
22091 (push-mark (org-element-property :end element) t t)
22092 (goto-char (org-element-property :begin element))))))
22094 ;;;###autoload
22095 (defun org-narrow-to-element ()
22096 "Narrow buffer to current element."
22097 (interactive)
22098 (let ((elem (org-element-at-point)))
22099 (cond
22100 ((eq (car elem) 'headline)
22101 (narrow-to-region
22102 (org-element-property :begin elem)
22103 (org-element-property :end elem)))
22104 ((memq (car elem) org-element-greater-elements)
22105 (narrow-to-region
22106 (org-element-property :contents-begin elem)
22107 (org-element-property :contents-end elem)))
22109 (narrow-to-region
22110 (org-element-property :begin elem)
22111 (org-element-property :end elem))))))
22113 ;;;###autoload
22114 (defun org-transpose-element ()
22115 "Transpose current and previous elements, keeping blank lines between.
22116 Point is moved after both elements."
22117 (interactive)
22118 (org-skip-whitespace)
22119 (let ((end (org-element-property :end (org-element-at-point))))
22120 (org-drag-element-backward)
22121 (goto-char end)))
22123 ;;;###autoload
22124 (defun org-unindent-buffer ()
22125 "Un-indent the visible part of the buffer.
22126 Relative indentation (between items, inside blocks, etc.) isn't
22127 modified."
22128 (interactive)
22129 (unless (eq major-mode 'org-mode)
22130 (error "Cannot un-indent a buffer not in Org mode"))
22131 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22132 unindent-tree ; For byte-compiler.
22133 (unindent-tree
22134 (function
22135 (lambda (contents)
22136 (mapc
22137 (lambda (element)
22138 (if (memq (org-element-type element) '(headline section))
22139 (funcall unindent-tree (org-element-contents element))
22140 (save-excursion
22141 (save-restriction
22142 (narrow-to-region
22143 (org-element-property :begin element)
22144 (org-element-property :end element))
22145 (org-do-remove-indentation)))))
22146 (reverse contents))))))
22147 (funcall unindent-tree (org-element-contents parse-tree))))
22149 (defun org-show-subtree ()
22150 "Show everything after this heading at deeper levels."
22151 (interactive)
22152 (outline-flag-region
22153 (point)
22154 (save-excursion
22155 (org-end-of-subtree t t))
22156 nil))
22158 (defun org-show-entry ()
22159 "Show the body directly following this heading.
22160 Show the heading too, if it is currently invisible."
22161 (interactive)
22162 (save-excursion
22163 (condition-case nil
22164 (progn
22165 (org-back-to-heading t)
22166 (outline-flag-region
22167 (max (point-min) (1- (point)))
22168 (save-excursion
22169 (if (re-search-forward
22170 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22171 (match-beginning 1)
22172 (point-max)))
22173 nil)
22174 (org-cycle-hide-drawers 'children))
22175 (error nil))))
22177 (defun org-make-options-regexp (kwds &optional extra)
22178 "Make a regular expression for keyword lines."
22179 (concat
22180 "^#\\+\\("
22181 (mapconcat 'regexp-quote kwds "\\|")
22182 (if extra (concat "\\|" extra))
22183 "\\):[ \t]*\\(.*\\)"))
22185 ;; Make isearch reveal the necessary context
22186 (defun org-isearch-end ()
22187 "Reveal context after isearch exits."
22188 (when isearch-success ; only if search was successful
22189 (if (featurep 'xemacs)
22190 ;; Under XEmacs, the hook is run in the correct place,
22191 ;; we directly show the context.
22192 (org-show-context 'isearch)
22193 ;; In Emacs the hook runs *before* restoring the overlays.
22194 ;; So we have to use a one-time post-command-hook to do this.
22195 ;; (Emacs 22 has a special variable, see function `org-mode')
22196 (unless (and (boundp 'isearch-mode-end-hook-quit)
22197 isearch-mode-end-hook-quit)
22198 ;; Only when the isearch was not quitted.
22199 (org-add-hook 'post-command-hook 'org-isearch-post-command
22200 'append 'local)))))
22202 (defun org-isearch-post-command ()
22203 "Remove self from hook, and show context."
22204 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22205 (org-show-context 'isearch))
22208 ;;;; Integration with and fixes for other packages
22210 ;;; Imenu support
22212 (defvar org-imenu-markers nil
22213 "All markers currently used by Imenu.")
22214 (make-variable-buffer-local 'org-imenu-markers)
22216 (defun org-imenu-new-marker (&optional pos)
22217 "Return a new marker for use by Imenu, and remember the marker."
22218 (let ((m (make-marker)))
22219 (move-marker m (or pos (point)))
22220 (push m org-imenu-markers)
22223 (defun org-imenu-get-tree ()
22224 "Produce the index for Imenu."
22225 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22226 (setq org-imenu-markers nil)
22227 (let* ((n org-imenu-depth)
22228 (re (concat "^" (org-get-limited-outline-regexp)))
22229 (subs (make-vector (1+ n) nil))
22230 (last-level 0)
22231 m level head)
22232 (save-excursion
22233 (save-restriction
22234 (widen)
22235 (goto-char (point-max))
22236 (while (re-search-backward re nil t)
22237 (setq level (org-reduced-level (funcall outline-level)))
22238 (when (and (<= level n)
22239 (looking-at org-complex-heading-regexp))
22240 (setq head (org-link-display-format
22241 (org-match-string-no-properties 4))
22242 m (org-imenu-new-marker))
22243 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22244 (if (>= level last-level)
22245 (push (cons head m) (aref subs level))
22246 (push (cons head (aref subs (1+ level))) (aref subs level))
22247 (loop for i from (1+ level) to n do (aset subs i nil)))
22248 (setq last-level level)))))
22249 (aref subs 1)))
22251 (eval-after-load "imenu"
22252 '(progn
22253 (add-hook 'imenu-after-jump-hook
22254 (lambda ()
22255 (if (derived-mode-p 'org-mode)
22256 (org-show-context 'org-goto))))))
22258 (defun org-link-display-format (link)
22259 "Replace a link with either the description, or the link target
22260 if no description is present"
22261 (save-match-data
22262 (if (string-match org-bracket-link-analytic-regexp link)
22263 (replace-match (if (match-end 5)
22264 (match-string 5 link)
22265 (concat (match-string 1 link)
22266 (match-string 3 link)))
22267 nil t link)
22268 link)))
22270 (defun org-toggle-link-display ()
22271 "Toggle the literal or descriptive display of links."
22272 (interactive)
22273 (if org-descriptive-links
22274 (progn (org-remove-from-invisibility-spec '(org-link))
22275 (org-restart-font-lock)
22276 (setq org-descriptive-links nil))
22277 (progn (add-to-invisibility-spec '(org-link))
22278 (org-restart-font-lock)
22279 (setq org-descriptive-links t))))
22281 ;; Speedbar support
22283 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22284 "Overlay marking the agenda restriction line in speedbar.")
22285 (overlay-put org-speedbar-restriction-lock-overlay
22286 'face 'org-agenda-restriction-lock)
22287 (overlay-put org-speedbar-restriction-lock-overlay
22288 'help-echo "Agendas are currently limited to this item.")
22289 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22291 (defun org-speedbar-set-agenda-restriction ()
22292 "Restrict future agenda commands to the location at point in speedbar.
22293 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22294 (interactive)
22295 (require 'org-agenda)
22296 (let (p m tp np dir txt)
22297 (cond
22298 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22299 'org-imenu t))
22300 (setq m (get-text-property p 'org-imenu-marker))
22301 (with-current-buffer (marker-buffer m)
22302 (goto-char m)
22303 (org-agenda-set-restriction-lock 'subtree)))
22304 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22305 'speedbar-function 'speedbar-find-file))
22306 (setq tp (previous-single-property-change
22307 (1+ p) 'speedbar-function)
22308 np (next-single-property-change
22309 tp 'speedbar-function)
22310 dir (speedbar-line-directory)
22311 txt (buffer-substring-no-properties (or tp (point-min))
22312 (or np (point-max))))
22313 (with-current-buffer (find-file-noselect
22314 (let ((default-directory dir))
22315 (expand-file-name txt)))
22316 (unless (derived-mode-p 'org-mode)
22317 (error "Cannot restrict to non-Org-mode file"))
22318 (org-agenda-set-restriction-lock 'file)))
22319 (t (error "Don't know how to restrict Org-mode's agenda")))
22320 (move-overlay org-speedbar-restriction-lock-overlay
22321 (point-at-bol) (point-at-eol))
22322 (setq current-prefix-arg nil)
22323 (org-agenda-maybe-redo)))
22325 (eval-after-load "speedbar"
22326 '(progn
22327 (speedbar-add-supported-extension ".org")
22328 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22329 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22330 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22331 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22332 (add-hook 'speedbar-visiting-tag-hook
22333 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22335 ;;; Fixes and Hacks for problems with other packages
22337 ;; Make flyspell not check words in links, to not mess up our keymap
22338 (defun org-mode-flyspell-verify ()
22339 "Don't let flyspell put overlays at active buttons, or on
22340 {todo,all-time,additional-option-like}-keywords."
22341 (let ((pos (max (1- (point)) (point-min)))
22342 (word (thing-at-point 'word)))
22343 (and (not (get-text-property pos 'keymap))
22344 (not (get-text-property pos 'org-no-flyspell))
22345 (not (member word org-todo-keywords-1))
22346 (not (member word org-all-time-keywords))
22347 (not (member word org-options-keywords))
22348 (not (member word (mapcar 'car org-startup-options)))
22349 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22351 (defun org-remove-flyspell-overlays-in (beg end)
22352 "Remove flyspell overlays in region."
22353 (and (org-bound-and-true-p flyspell-mode)
22354 (fboundp 'flyspell-delete-region-overlays)
22355 (flyspell-delete-region-overlays beg end))
22356 (add-text-properties beg end '(org-no-flyspell t)))
22358 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22359 (eval-after-load "bookmark"
22360 '(if (boundp 'bookmark-after-jump-hook)
22361 ;; We can use the hook
22362 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22363 ;; Hook not available, use advice
22364 (defadvice bookmark-jump (after org-make-visible activate)
22365 "Make the position visible."
22366 (org-bookmark-jump-unhide))))
22368 ;; Make sure saveplace shows the location if it was hidden
22369 (eval-after-load "saveplace"
22370 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22371 "Make the position visible."
22372 (org-bookmark-jump-unhide)))
22374 ;; Make sure ecb shows the location if it was hidden
22375 (eval-after-load "ecb"
22376 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22377 "Make hierarchy visible when jumping into location from ECB tree buffer."
22378 (if (derived-mode-p 'org-mode)
22379 (org-show-context))))
22381 (defun org-bookmark-jump-unhide ()
22382 "Unhide the current position, to show the bookmark location."
22383 (and (derived-mode-p 'org-mode)
22384 (or (outline-invisible-p)
22385 (save-excursion (goto-char (max (point-min) (1- (point))))
22386 (outline-invisible-p)))
22387 (org-show-context 'bookmark-jump)))
22389 ;; Make session.el ignore our circular variable
22390 (eval-after-load "session"
22391 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22393 ;;;; Experimental code
22395 (defun org-closed-in-range ()
22396 "Sparse tree of items closed in a certain time range.
22397 Still experimental, may disappear in the future."
22398 (interactive)
22399 ;; Get the time interval from the user.
22400 (let* ((time1 (org-float-time
22401 (org-read-date nil 'to-time nil "Starting date: ")))
22402 (time2 (org-float-time
22403 (org-read-date nil 'to-time nil "End date:")))
22404 ;; callback function
22405 (callback (lambda ()
22406 (let ((time
22407 (org-float-time
22408 (apply 'encode-time
22409 (org-parse-time-string
22410 (match-string 1))))))
22411 ;; check if time in interval
22412 (and (>= time time1) (<= time time2))))))
22413 ;; make tree, check each match with the callback
22414 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22416 ;;;; Finish up
22418 (provide 'org)
22420 (run-hooks 'org-load-hook)
22422 ;;; org.el ends here