New command `org-inc-effort' to increment the effort value.
[org-mode.git] / lisp / org.el
blob018926be6788e8773969350e06e29f3ac6c660ad
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.")
90 (defconst org-outline-regexp-bol "^\\*+ "
91 "Regexp to match Org headlines.
92 This is similar to `org-outline-regexp' but additionally makes
93 sure that we are at the beginning of the line.")
95 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
96 "Matches an headline, putting stars and text into groups.
97 Stars are put in group 1 and the trimmed body in group 2.")
99 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
100 (when (fboundp 'defvaralias)
101 (unless (boundp 'calendar-view-holidays-initially-flag)
102 (defvaralias 'calendar-view-holidays-initially-flag
103 'view-calendar-holidays-initially))
104 (unless (boundp 'calendar-view-diary-initially-flag)
105 (defvaralias 'calendar-view-diary-initially-flag
106 'view-diary-entries-initially))
107 (unless (boundp 'diary-fancy-buffer)
108 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
110 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
111 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
112 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
113 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
114 (declare-function org-at-clock-log-p "org-clock" ())
115 (declare-function org-clock-timestamps-up "org-clock" ())
116 (declare-function org-clock-timestamps-down "org-clock" ())
118 ;; load languages based on value of `org-babel-load-languages'
119 (defvar org-babel-load-languages)
120 ;;;###autoload
121 (defun org-babel-do-load-languages (sym value)
122 "Load the languages defined in `org-babel-load-languages'."
123 (set-default sym value)
124 (mapc (lambda (pair)
125 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
126 (if active
127 (progn
128 (require (intern (concat "ob-" lang))))
129 (progn
130 (funcall 'fmakunbound
131 (intern (concat "org-babel-execute:" lang)))
132 (funcall 'fmakunbound
133 (intern (concat "org-babel-expand-body:" lang)))))))
134 org-babel-load-languages))
136 (defcustom org-babel-load-languages '((emacs-lisp . t))
137 "Languages which can be evaluated in Org-mode buffers.
138 This list can be used to load support for any of the languages
139 below, note that each language will depend on a different set of
140 system executables and/or Emacs modes. When a language is
141 \"loaded\", then code blocks in that language can be evaluated
142 with `org-babel-execute-src-block' bound by default to C-c
143 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
144 be set to remove code block evaluation from the C-c C-c
145 keybinding. By default only Emacs Lisp (which has no
146 requirements) is loaded."
147 :group 'org-babel
148 :set 'org-babel-do-load-languages
149 :version "24.1"
150 :type '(alist :tag "Babel Languages"
151 :key-type
152 (choice
153 (const :tag "Awk" awk)
154 (const :tag "C" C)
155 (const :tag "R" R)
156 (const :tag "Asymptote" asymptote)
157 (const :tag "Calc" calc)
158 (const :tag "Clojure" clojure)
159 (const :tag "CSS" css)
160 (const :tag "Ditaa" ditaa)
161 (const :tag "Dot" dot)
162 (const :tag "Emacs Lisp" emacs-lisp)
163 (const :tag "Fortran" fortran)
164 (const :tag "Gnuplot" gnuplot)
165 (const :tag "Haskell" haskell)
166 (const :tag "IO" io)
167 (const :tag "Java" java)
168 (const :tag "Javascript" js)
169 (const :tag "LaTeX" latex)
170 (const :tag "Ledger" ledger)
171 (const :tag "Lilypond" lilypond)
172 (const :tag "Maxima" maxima)
173 (const :tag "Matlab" matlab)
174 (const :tag "Mscgen" mscgen)
175 (const :tag "Ocaml" ocaml)
176 (const :tag "Octave" octave)
177 (const :tag "Org" org)
178 (const :tag "Perl" perl)
179 (const :tag "Pico Lisp" picolisp)
180 (const :tag "PlantUML" plantuml)
181 (const :tag "Python" python)
182 (const :tag "Ruby" ruby)
183 (const :tag "Sass" sass)
184 (const :tag "Scala" scala)
185 (const :tag "Scheme" scheme)
186 (const :tag "Screen" screen)
187 (const :tag "Shell Script" sh)
188 (const :tag "Shen" shen)
189 (const :tag "Sql" sql)
190 (const :tag "Sqlite" sqlite))
191 :value-type (boolean :tag "Activate" :value t)))
193 ;;;; Customization variables
194 (defcustom org-clone-delete-id nil
195 "Remove ID property of clones of a subtree.
196 When non-nil, clones of a subtree don't inherit the ID property.
197 Otherwise they inherit the ID property with a new unique
198 identifier."
199 :type 'boolean
200 :version "24.1"
201 :group 'org-id)
203 ;;; Version
204 (org-check-version)
205 ;;;###autoload
206 (defun org-version (&optional here full message)
207 "Show the org-mode version in the echo area.
208 With prefix arg HERE, insert it at point."
209 (interactive "P")
210 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
211 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
212 (org-trash (or
213 (and (fboundp 'org-release) (fboundp 'org-git-version))
214 (load (concat org-dir "org-version.el")
215 'noerror 'nomessage 'nosuffix)))
216 (org-version (org-release))
217 (git-version (org-git-version))
218 (version (format "Org-mode version %s (%s @ %s)"
219 org-version
220 git-version
221 (if org-install-dir
222 (if (string= org-dir org-install-dir)
223 org-install-dir
224 (concat "mixed installation! " org-install-dir " and " org-dir))
225 "org-install.el can not be found!")))
226 (_version (if full version org-version)))
227 (if (org-called-interactively-p 'interactive)
228 (if here
229 (insert version)
230 (message version))
231 (if message (message _version))
232 _version)))
234 ;;; Compatibility constants
236 ;;; The custom variables
238 (defgroup org nil
239 "Outline-based notes management and organizer."
240 :tag "Org"
241 :group 'outlines
242 :group 'calendar)
244 (defcustom org-mode-hook nil
245 "Mode hook for Org-mode, run after the mode was turned on."
246 :group 'org
247 :type 'hook)
249 (defcustom org-load-hook nil
250 "Hook that is run after org.el has been loaded."
251 :group 'org
252 :type 'hook)
254 (defcustom org-log-buffer-setup-hook nil
255 "Hook that is run after an Org log buffer is created."
256 :group 'org
257 :version "24.1"
258 :type 'hook)
260 (defvar org-modules) ; defined below
261 (defvar org-modules-loaded nil
262 "Have the modules been loaded already?")
264 (defun org-load-modules-maybe (&optional force)
265 "Load all extensions listed in `org-modules'."
266 (when (or force (not org-modules-loaded))
267 (mapc (lambda (ext)
268 (condition-case nil (require ext)
269 (error (message "Problems while trying to load feature `%s'" ext))))
270 org-modules)
271 (setq org-modules-loaded t)))
273 (defun org-set-modules (var value)
274 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
275 (set var value)
276 (when (featurep 'org)
277 (org-load-modules-maybe 'force)))
279 (when (org-bound-and-true-p org-modules)
280 (let ((a (member 'org-infojs org-modules)))
281 (and a (setcar a 'org-jsinfo))))
283 (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)
284 "Modules that should always be loaded together with org.el.
285 If a description starts with <C>, the file is not part of Emacs
286 and loading it will require that you have downloaded and properly installed
287 the org-mode distribution.
289 You can also use this system to load external packages (i.e. neither Org
290 core modules, nor modules from the CONTRIB directory). Just add symbols
291 to the end of the list. If the package is called org-xyz.el, then you need
292 to add the symbol `xyz', and the package must have a call to
294 (provide 'org-xyz)"
295 :group 'org
296 :set 'org-set-modules
297 :type
298 '(set :greedy t
299 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
300 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
301 (const :tag " crypt: Encryption of subtrees" org-crypt)
302 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
303 (const :tag " docview: Links to doc-view buffers" org-docview)
304 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
305 (const :tag " id: Global IDs for identifying entries" org-id)
306 (const :tag " info: Links to Info nodes" org-info)
307 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
308 (const :tag " habit: Track your consistency with habits" org-habit)
309 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
310 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
311 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
312 (const :tag " mew Links to Mew folders/messages" org-mew)
313 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
314 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
315 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
316 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
317 (const :tag " vm: Links to VM folders/messages" org-vm)
318 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
319 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
320 (const :tag " mouse: Additional mouse support" org-mouse)
321 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
323 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
324 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
325 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
326 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
327 (const :tag "C collector: Collect properties into tables" org-collector)
328 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
329 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
330 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
331 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
332 (const :tag "C eval: Include command output as text" org-eval)
333 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
334 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
335 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
336 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
337 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
339 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
341 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
342 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
343 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
344 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
345 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
346 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
347 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
348 (const :tag "C mtags: Support for muse-like tags" org-mtags)
349 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
350 (const :tag "C registry: A registry for Org-mode links" org-registry)
351 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
352 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
353 (const :tag "C secretary: Team management with org-mode" org-secretary)
354 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
355 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
356 (const :tag "C track: Keep up with Org-mode development" org-track)
357 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
358 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
359 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
361 (defcustom org-support-shift-select nil
362 "Non-nil means make shift-cursor commands select text when possible.
364 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
365 start selecting a region, or enlarge regions started in this way.
366 In Org-mode, in special contexts, these same keys are used for
367 other purposes, important enough to compete with shift selection.
368 Org tries to balance these needs by supporting `shift-select-mode'
369 outside these special contexts, under control of this variable.
371 The default of this variable is nil, to avoid confusing behavior. Shifted
372 cursor keys will then execute Org commands in the following contexts:
373 - on a headline, changing TODO state (left/right) and priority (up/down)
374 - on a time stamp, changing the time
375 - in a plain list item, changing the bullet type
376 - in a property definition line, switching between allowed values
377 - in the BEGIN line of a clock table (changing the time block).
378 Outside these contexts, the commands will throw an error.
380 When this variable is t and the cursor is not in a special
381 context, Org-mode will support shift-selection for making and
382 enlarging regions. To make this more effective, the bullet
383 cycling will no longer happen anywhere in an item line, but only
384 if the cursor is exactly on the bullet.
386 If you set this variable to the symbol `always', then the keys
387 will not be special in headlines, property lines, and item lines,
388 to make shift selection work there as well. If this is what you
389 want, you can use the following alternative commands: `C-c C-t'
390 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
391 can be used to switch TODO sets, `C-c -' to cycle item bullet
392 types, and properties can be edited by hand or in column view.
394 However, when the cursor is on a timestamp, shift-cursor commands
395 will still edit the time stamp - this is just too good to give up.
397 XEmacs user should have this variable set to nil, because
398 `shift-select-mode' is in Emacs 23 or later only."
399 :group 'org
400 :type '(choice
401 (const :tag "Never" nil)
402 (const :tag "When outside special context" t)
403 (const :tag "Everywhere except timestamps" always)))
405 (defcustom org-loop-over-headlines-in-active-region nil
406 "Shall some commands act upon headlines in the active region?
408 When set to `t', some commands will be performed in all headlines
409 within the active region.
411 When set to `start-level', some commands will be performed in all
412 headlines within the active region, provided that these headlines
413 are of the same level than the first one.
415 When set to a string, those commands will be performed on the
416 matching headlines within the active region. Such string must be
417 a tags/property/todo match as it is used in the agenda tags view.
419 The list of commands is: `org-schedule', `org-deadline',
420 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
421 `org-archive-to-archive-sibling'. The archiving commands skip
422 already archived entries."
423 :type '(choice (const :tag "Don't loop" nil)
424 (const :tag "All headlines in active region" t)
425 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
426 (string :tag "Tags/Property/Todo matcher"))
427 :version "24.1"
428 :group 'org-todo
429 :group 'org-archive)
431 (defgroup org-startup nil
432 "Options concerning startup of Org-mode."
433 :tag "Org Startup"
434 :group 'org)
436 (defcustom org-startup-folded t
437 "Non-nil means entering Org-mode will switch to OVERVIEW.
438 This can also be configured on a per-file basis by adding one of
439 the following lines anywhere in the buffer:
441 #+STARTUP: fold (or `overview', this is equivalent)
442 #+STARTUP: nofold (or `showall', this is equivalent)
443 #+STARTUP: content
444 #+STARTUP: showeverything"
445 :group 'org-startup
446 :type '(choice
447 (const :tag "nofold: show all" nil)
448 (const :tag "fold: overview" t)
449 (const :tag "content: all headlines" content)
450 (const :tag "show everything, even drawers" showeverything)))
452 (defcustom org-startup-truncated t
453 "Non-nil means entering Org-mode will set `truncate-lines'.
454 This is useful since some lines containing links can be very long and
455 uninteresting. Also tables look terrible when wrapped."
456 :group 'org-startup
457 :type 'boolean)
459 (defcustom org-startup-indented nil
460 "Non-nil means turn on `org-indent-mode' on startup.
461 This can also be configured on a per-file basis by adding one of
462 the following lines anywhere in the buffer:
464 #+STARTUP: indent
465 #+STARTUP: noindent"
466 :group 'org-structure
467 :type '(choice
468 (const :tag "Not" nil)
469 (const :tag "Globally (slow on startup in large files)" t)))
471 (defcustom org-use-sub-superscripts t
472 "Non-nil means interpret \"_\" and \"^\" for export.
473 When this option is turned on, you can use TeX-like syntax for sub- and
474 superscripts. Several characters after \"_\" or \"^\" will be
475 considered as a single item - so grouping with {} is normally not
476 needed. For example, the following things will be parsed as single
477 sub- or superscripts.
479 10^24 or 10^tau several digits will be considered 1 item.
480 10^-12 or 10^-tau a leading sign with digits or a word
481 x^2-y^3 will be read as x^2 - y^3, because items are
482 terminated by almost any nonword/nondigit char.
483 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
485 Still, ambiguity is possible - so when in doubt use {} to enclose the
486 sub/superscript. If you set this variable to the symbol `{}',
487 the braces are *required* in order to trigger interpretations as
488 sub/superscript. This can be helpful in documents that need \"_\"
489 frequently in plain text.
491 Not all export backends support this, but HTML does.
493 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
494 :group 'org-startup
495 :group 'org-export-translation
496 :version "24.1"
497 :type '(choice
498 (const :tag "Always interpret" t)
499 (const :tag "Only with braces" {})
500 (const :tag "Never interpret" nil)))
502 (if (fboundp 'defvaralias)
503 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
506 (defcustom org-startup-with-beamer-mode nil
507 "Non-nil means turn on `org-beamer-mode' on startup.
508 This can also be configured on a per-file basis by adding one of
509 the following lines anywhere in the buffer:
511 #+STARTUP: beamer"
512 :group 'org-startup
513 :version "24.1"
514 :type 'boolean)
516 (defcustom org-startup-align-all-tables nil
517 "Non-nil means align all tables when visiting a file.
518 This is useful when the column width in tables is forced with <N> cookies
519 in table fields. Such tables will look correct only after the first re-align.
520 This can also be configured on a per-file basis by adding one of
521 the following lines anywhere in the buffer:
522 #+STARTUP: align
523 #+STARTUP: noalign"
524 :group 'org-startup
525 :type 'boolean)
527 (defcustom org-startup-with-inline-images nil
528 "Non-nil means show inline images when loading a new Org file.
529 This can also be configured on a per-file basis by adding one of
530 the following lines anywhere in the buffer:
531 #+STARTUP: inlineimages
532 #+STARTUP: noinlineimages"
533 :group 'org-startup
534 :version "24.1"
535 :type 'boolean)
537 (defcustom org-insert-mode-line-in-empty-file nil
538 "Non-nil means insert the first line setting Org-mode in empty files.
539 When the function `org-mode' is called interactively in an empty file, this
540 normally means that the file name does not automatically trigger Org-mode.
541 To ensure that the file will always be in Org-mode in the future, a
542 line enforcing Org-mode will be inserted into the buffer, if this option
543 has been set."
544 :group 'org-startup
545 :type 'boolean)
547 (defcustom org-replace-disputed-keys nil
548 "Non-nil means use alternative key bindings for some keys.
549 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
550 These keys are also used by other packages like shift-selection-mode'
551 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
552 If you want to use Org-mode together with one of these other modes,
553 or more generally if you would like to move some Org-mode commands to
554 other keys, set this variable and configure the keys with the variable
555 `org-disputed-keys'.
557 This option is only relevant at load-time of Org-mode, and must be set
558 *before* org.el is loaded. Changing it requires a restart of Emacs to
559 become effective."
560 :group 'org-startup
561 :type 'boolean)
563 (defcustom org-use-extra-keys nil
564 "Non-nil means use extra key sequence definitions for certain commands.
565 This happens automatically if you run XEmacs or if `window-system'
566 is nil. This variable lets you do the same manually. You must
567 set it before loading org.
569 Example: on Carbon Emacs 22 running graphically, with an external
570 keyboard on a Powerbook, the default way of setting M-left might
571 not work for either Alt or ESC. Setting this variable will make
572 it work for ESC."
573 :group 'org-startup
574 :type 'boolean)
576 (if (fboundp 'defvaralias)
577 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
579 (defcustom org-disputed-keys
580 '(([(shift up)] . [(meta p)])
581 ([(shift down)] . [(meta n)])
582 ([(shift left)] . [(meta -)])
583 ([(shift right)] . [(meta +)])
584 ([(control shift right)] . [(meta shift +)])
585 ([(control shift left)] . [(meta shift -)]))
586 "Keys for which Org-mode and other modes compete.
587 This is an alist, cars are the default keys, second element specifies
588 the alternative to use when `org-replace-disputed-keys' is t.
590 Keys can be specified in any syntax supported by `define-key'.
591 The value of this option takes effect only at Org-mode's startup,
592 therefore you'll have to restart Emacs to apply it after changing."
593 :group 'org-startup
594 :type 'alist)
596 (defun org-key (key)
597 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
598 Or return the original if not disputed.
599 Also apply the translations defined in `org-xemacs-key-equivalents'."
600 (when org-replace-disputed-keys
601 (let* ((nkey (key-description key))
602 (x (org-find-if (lambda (x)
603 (equal (key-description (car x)) nkey))
604 org-disputed-keys)))
605 (setq key (if x (cdr x) key))))
606 (when (featurep 'xemacs)
607 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
608 key)
610 (defun org-find-if (predicate seq)
611 (catch 'exit
612 (while seq
613 (if (funcall predicate (car seq))
614 (throw 'exit (car seq))
615 (pop seq)))))
617 (defun org-defkey (keymap key def)
618 "Define a key, possibly translated, as returned by `org-key'."
619 (define-key keymap (org-key key) def))
621 (defcustom org-ellipsis nil
622 "The ellipsis to use in the Org-mode outline.
623 When nil, just use the standard three dots. When a string, use that instead,
624 When a face, use the standard 3 dots, but with the specified face.
625 The change affects only Org-mode (which will then use its own display table).
626 Changing this requires executing `M-x org-mode' in a buffer to become
627 effective."
628 :group 'org-startup
629 :type '(choice (const :tag "Default" nil)
630 (face :tag "Face" :value org-warning)
631 (string :tag "String" :value "...#")))
633 (defvar org-display-table nil
634 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
636 (defgroup org-keywords nil
637 "Keywords in Org-mode."
638 :tag "Org Keywords"
639 :group 'org)
641 (defcustom org-deadline-string "DEADLINE:"
642 "String to mark deadline entries.
643 A deadline is this string, followed by a time stamp. Should be a word,
644 terminated by a colon. You can insert a schedule keyword and
645 a timestamp with \\[org-deadline].
646 Changes become only effective after restarting Emacs."
647 :group 'org-keywords
648 :type 'string)
650 (defcustom org-scheduled-string "SCHEDULED:"
651 "String to mark scheduled TODO entries.
652 A schedule is this string, followed by a time stamp. Should be a word,
653 terminated by a colon. You can insert a schedule keyword and
654 a timestamp with \\[org-schedule].
655 Changes become only effective after restarting Emacs."
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-closed-string "CLOSED:"
660 "String used as the prefix for timestamps logging closing a TODO entry."
661 :group 'org-keywords
662 :type 'string)
664 (defcustom org-clock-string "CLOCK:"
665 "String used as prefix for timestamps clocking work hours on an item."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-comment-string "COMMENT"
670 "Entries starting with this keyword will never be exported.
671 An entry can be toggled between COMMENT and normal with
672 \\[org-toggle-comment].
673 Changes become only effective after restarting Emacs."
674 :group 'org-keywords
675 :type 'string)
677 (defcustom org-quote-string "QUOTE"
678 "Entries starting with this keyword will be exported in fixed-width font.
679 Quoting applies only to the text in the entry following the headline, and does
680 not extend beyond the next headline, even if that is lower level.
681 An entry can be toggled between QUOTE and normal with
682 \\[org-toggle-fixed-width-section]."
683 :group 'org-keywords
684 :type 'string)
686 (defconst org-repeat-re
687 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
688 "Regular expression for specifying repeated events.
689 After a match, group 1 contains the repeat expression.")
691 (defgroup org-structure nil
692 "Options concerning the general structure of Org-mode files."
693 :tag "Org Structure"
694 :group 'org)
696 (defgroup org-reveal-location nil
697 "Options about how to make context of a location visible."
698 :tag "Org Reveal Location"
699 :group 'org-structure)
701 (defconst org-context-choice
702 '(choice
703 (const :tag "Always" t)
704 (const :tag "Never" nil)
705 (repeat :greedy t :tag "Individual contexts"
706 (cons
707 (choice :tag "Context"
708 (const agenda)
709 (const org-goto)
710 (const occur-tree)
711 (const tags-tree)
712 (const link-search)
713 (const mark-goto)
714 (const bookmark-jump)
715 (const isearch)
716 (const default))
717 (boolean))))
718 "Contexts for the reveal options.")
720 (defcustom org-show-hierarchy-above '((default . t))
721 "Non-nil means show full hierarchy when revealing a location.
722 Org-mode often shows locations in an org-mode file which might have
723 been invisible before. When this is set, the hierarchy of headings
724 above the exposed location is shown.
725 Turning this off for example for sparse trees makes them very compact.
726 Instead of t, this can also be an alist specifying this option for different
727 contexts. Valid contexts are
728 agenda when exposing an entry from the agenda
729 org-goto when using the command `org-goto' on key C-c C-j
730 occur-tree when using the command `org-occur' on key C-c /
731 tags-tree when constructing a sparse tree based on tags matches
732 link-search when exposing search matches associated with a link
733 mark-goto when exposing the jump goal of a mark
734 bookmark-jump when exposing a bookmark location
735 isearch when exiting from an incremental search
736 default default for all contexts not set explicitly"
737 :group 'org-reveal-location
738 :type org-context-choice)
740 (defcustom org-show-following-heading '((default . nil))
741 "Non-nil means show following heading when revealing a location.
742 Org-mode often shows locations in an org-mode file which might have
743 been invisible before. When this is set, the heading following the
744 match is shown.
745 Turning this off for example for sparse trees makes them very compact,
746 but makes it harder to edit the location of the match. In such a case,
747 use the command \\[org-reveal] to show more context.
748 Instead of t, this can also be an alist specifying this option for different
749 contexts. See `org-show-hierarchy-above' for valid contexts."
750 :group 'org-reveal-location
751 :type org-context-choice)
753 (defcustom org-show-siblings '((default . nil) (isearch t))
754 "Non-nil means show all sibling heading when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the sibling of the current entry
757 heading are all made visible. If `org-show-hierarchy-above' is t,
758 the same happens on each level of the hierarchy above the current entry.
760 By default this is on for the isearch context, off for all other contexts.
761 Turning this off for example for sparse trees makes them very compact,
762 but makes it harder to edit the location of the match. In such a case,
763 use the command \\[org-reveal] to show more context.
764 Instead of t, this can also be an alist specifying this option for different
765 contexts. See `org-show-hierarchy-above' for valid contexts."
766 :group 'org-reveal-location
767 :type org-context-choice)
769 (defcustom org-show-entry-below '((default . nil))
770 "Non-nil means show the entry below a headline when revealing a location.
771 Org-mode often shows locations in an org-mode file which might have
772 been invisible before. When this is set, the text below the headline that is
773 exposed is also shown.
775 By default this is off for all contexts.
776 Instead of t, this can also be an alist specifying this option for different
777 contexts. See `org-show-hierarchy-above' for valid contexts."
778 :group 'org-reveal-location
779 :type org-context-choice)
781 (defcustom org-indirect-buffer-display 'other-window
782 "How should indirect tree buffers be displayed?
783 This applies to indirect buffers created with the commands
784 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
785 Valid values are:
786 current-window Display in the current window
787 other-window Just display in another window.
788 dedicated-frame Create one new frame, and re-use it each time.
789 new-frame Make a new frame each time. Note that in this case
790 previously-made indirect buffers are kept, and you need to
791 kill these buffers yourself."
792 :group 'org-structure
793 :group 'org-agenda-windows
794 :type '(choice
795 (const :tag "In current window" current-window)
796 (const :tag "In current frame, other window" other-window)
797 (const :tag "Each time a new frame" new-frame)
798 (const :tag "One dedicated frame" dedicated-frame)))
800 (defcustom org-use-speed-commands nil
801 "Non-nil means activate single letter commands at beginning of a headline.
802 This may also be a function to test for appropriate locations where speed
803 commands should be active."
804 :group 'org-structure
805 :type '(choice
806 (const :tag "Never" nil)
807 (const :tag "At beginning of headline stars" t)
808 (function)))
810 (defcustom org-speed-commands-user nil
811 "Alist of additional speed commands.
812 This list will be checked before `org-speed-commands-default'
813 when the variable `org-use-speed-commands' is non-nil
814 and when the cursor is at the beginning of a headline.
815 The car if each entry is a string with a single letter, which must
816 be assigned to `self-insert-command' in the global map.
817 The cdr is either a command to be called interactively, a function
818 to be called, or a form to be evaluated.
819 An entry that is just a list with a single string will be interpreted
820 as a descriptive headline that will be added when listing the speed
821 commands in the Help buffer using the `?' speed command."
822 :group 'org-structure
823 :type '(repeat :value ("k" . ignore)
824 (choice :value ("k" . ignore)
825 (list :tag "Descriptive Headline" (string :tag "Headline"))
826 (cons :tag "Letter and Command"
827 (string :tag "Command letter")
828 (choice
829 (function)
830 (sexp))))))
832 (defgroup org-cycle nil
833 "Options concerning visibility cycling in Org-mode."
834 :tag "Org Cycle"
835 :group 'org-structure)
837 (defcustom org-cycle-skip-children-state-if-no-children t
838 "Non-nil means skip CHILDREN state in entries that don't have any."
839 :group 'org-cycle
840 :type 'boolean)
842 (defcustom org-cycle-max-level nil
843 "Maximum level which should still be subject to visibility cycling.
844 Levels higher than this will, for cycling, be treated as text, not a headline.
845 When `org-odd-levels-only' is set, a value of N in this variable actually
846 means 2N-1 stars as the limiting headline.
847 When nil, cycle all levels.
848 Note that the limiting level of cycling is also influenced by
849 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
850 `org-inlinetask-min-level' is, cycling will be limited to levels one less
851 than its value."
852 :group 'org-cycle
853 :type '(choice
854 (const :tag "No limit" nil)
855 (integer :tag "Maximum level")))
857 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
858 "Names of drawers. Drawers are not opened by cycling on the headline above.
859 Drawers only open with a TAB on the drawer line itself. A drawer looks like
860 this:
861 :DRAWERNAME:
862 .....
863 :END:
864 The drawer \"PROPERTIES\" is special for capturing properties through
865 the property API.
867 Drawers can be defined on the per-file basis with a line like:
869 #+DRAWERS: HIDDEN STATE PROPERTIES"
870 :group 'org-structure
871 :group 'org-cycle
872 :type '(repeat (string :tag "Drawer Name")))
874 (defcustom org-hide-block-startup nil
875 "Non-nil means entering Org-mode will fold all blocks.
876 This can also be set in on a per-file basis with
878 #+STARTUP: hideblocks
879 #+STARTUP: showblocks"
880 :group 'org-startup
881 :group 'org-cycle
882 :type 'boolean)
884 (defcustom org-cycle-global-at-bob nil
885 "Cycle globally if cursor is at beginning of buffer and not at a headline.
886 This makes it possible to do global cycling without having to use S-TAB or
887 \\[universal-argument] TAB. For this special case to work, the first line \
888 of the buffer
889 must not be a headline - it may be empty or some other text. When used in
890 this way, `org-cycle-hook' is disables temporarily, to make sure the
891 cursor stays at the beginning of the buffer.
892 When this option is nil, don't do anything special at the beginning
893 of the buffer."
894 :group 'org-cycle
895 :type 'boolean)
897 (defcustom org-cycle-level-after-item/entry-creation t
898 "Non-nil means cycle entry level or item indentation in new empty entries.
900 When the cursor is at the end of an empty headline, i.e with only stars
901 and maybe a TODO keyword, TAB will then switch the entry to become a child,
902 and then all possible ancestor states, before returning to the original state.
903 This makes data entry extremely fast: M-RET to create a new headline,
904 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
906 When the cursor is at the end of an empty plain list item, one TAB will
907 make it a subitem, two or more tabs will back up to make this an item
908 higher up in the item hierarchy."
909 :group 'org-cycle
910 :type 'boolean)
912 (defcustom org-cycle-emulate-tab t
913 "Where should `org-cycle' emulate TAB.
914 nil Never
915 white Only in completely white lines
916 whitestart Only at the beginning of lines, before the first non-white char
917 t Everywhere except in headlines
918 exc-hl-bol Everywhere except at the start of a headline
919 If TAB is used in a place where it does not emulate TAB, the current subtree
920 visibility is cycled."
921 :group 'org-cycle
922 :type '(choice (const :tag "Never" nil)
923 (const :tag "Only in completely white lines" white)
924 (const :tag "Before first char in a line" whitestart)
925 (const :tag "Everywhere except in headlines" t)
926 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
929 (defcustom org-cycle-separator-lines 2
930 "Number of empty lines needed to keep an empty line between collapsed trees.
931 If you leave an empty line between the end of a subtree and the following
932 headline, this empty line is hidden when the subtree is folded.
933 Org-mode will leave (exactly) one empty line visible if the number of
934 empty lines is equal or larger to the number given in this variable.
935 So the default 2 means at least 2 empty lines after the end of a subtree
936 are needed to produce free space between a collapsed subtree and the
937 following headline.
939 If the number is negative, and the number of empty lines is at least -N,
940 all empty lines are shown.
942 Special case: when 0, never leave empty lines in collapsed view."
943 :group 'org-cycle
944 :type 'integer)
945 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
947 (defcustom org-pre-cycle-hook nil
948 "Hook that is run before visibility cycling is happening.
949 The function(s) in this hook must accept a single argument which indicates
950 the new state that will be set right after running this hook. The
951 argument is a symbol. Before a global state change, it can have the values
952 `overview', `content', or `all'. Before a local state change, it can have
953 the values `folded', `children', or `subtree'."
954 :group 'org-cycle
955 :type 'hook)
957 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
958 org-cycle-hide-drawers
959 org-cycle-show-empty-lines
960 org-optimize-window-after-visibility-change)
961 "Hook that is run after `org-cycle' has changed the buffer visibility.
962 The function(s) in this hook must accept a single argument which indicates
963 the new state that was set by the most recent `org-cycle' command. The
964 argument is a symbol. After a global state change, it can have the values
965 `overview', `content', or `all'. After a local state change, it can have
966 the values `folded', `children', or `subtree'."
967 :group 'org-cycle
968 :type 'hook)
970 (defgroup org-edit-structure nil
971 "Options concerning structure editing in Org-mode."
972 :tag "Org Edit Structure"
973 :group 'org-structure)
975 (defcustom org-odd-levels-only nil
976 "Non-nil means skip even levels and only use odd levels for the outline.
977 This has the effect that two stars are being added/taken away in
978 promotion/demotion commands. It also influences how levels are
979 handled by the exporters.
980 Changing it requires restart of `font-lock-mode' to become effective
981 for fontification also in regions already fontified.
982 You may also set this on a per-file basis by adding one of the following
983 lines to the buffer:
985 #+STARTUP: odd
986 #+STARTUP: oddeven"
987 :group 'org-edit-structure
988 :group 'org-appearance
989 :type 'boolean)
991 (defcustom org-adapt-indentation t
992 "Non-nil means adapt indentation to outline node level.
994 When this variable is set, Org assumes that you write outlines by
995 indenting text in each node to align with the headline (after the stars).
996 The following issues are influenced by this variable:
998 - When this is set and the *entire* text in an entry is indented, the
999 indentation is increased by one space in a demotion command, and
1000 decreased by one in a promotion command. If any line in the entry
1001 body starts with text at column 0, indentation is not changed at all.
1003 - Property drawers and planning information is inserted indented when
1004 this variable s set. When nil, they will not be indented.
1006 - TAB indents a line relative to context. The lines below a headline
1007 will be indented when this variable is set.
1009 Note that this is all about true indentation, by adding and removing
1010 space characters. See also `org-indent.el' which does level-dependent
1011 indentation in a virtual way, i.e. at display time in Emacs."
1012 :group 'org-edit-structure
1013 :type 'boolean)
1015 (defcustom org-special-ctrl-a/e nil
1016 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1018 When t, `C-a' will bring back the cursor to the beginning of the
1019 headline text, i.e. after the stars and after a possible TODO
1020 keyword. In an item, this will be the position after bullet and
1021 check-box, if any. When the cursor is already at that position,
1022 another `C-a' will bring it to the beginning of the line.
1024 `C-e' will jump to the end of the headline, ignoring the presence
1025 of tags in the headline. A second `C-e' will then jump to the
1026 true end of the line, after any tags. This also means that, when
1027 this variable is non-nil, `C-e' also will never jump beyond the
1028 end of the heading of a folded section, i.e. not after the
1029 ellipses.
1031 When set to the symbol `reversed', the first `C-a' or `C-e' works
1032 normally, going to the true line boundary first. Only a directly
1033 following, identical keypress will bring the cursor to the
1034 special positions.
1036 This may also be a cons cell where the behavior for `C-a' and
1037 `C-e' is set separately."
1038 :group 'org-edit-structure
1039 :type '(choice
1040 (const :tag "off" nil)
1041 (const :tag "on: after stars/bullet and before tags first" t)
1042 (const :tag "reversed: true line boundary first" reversed)
1043 (cons :tag "Set C-a and C-e separately"
1044 (choice :tag "Special C-a"
1045 (const :tag "off" nil)
1046 (const :tag "on: after stars/bullet first" t)
1047 (const :tag "reversed: before stars/bullet first" reversed))
1048 (choice :tag "Special C-e"
1049 (const :tag "off" nil)
1050 (const :tag "on: before tags first" t)
1051 (const :tag "reversed: after tags first" reversed)))))
1052 (if (fboundp 'defvaralias)
1053 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1055 (defcustom org-special-ctrl-k nil
1056 "Non-nil means `C-k' will behave specially in headlines.
1057 When nil, `C-k' will call the default `kill-line' command.
1058 When t, the following will happen while the cursor is in the headline:
1060 - When the cursor is at the beginning of a headline, kill the entire
1061 line and possible the folded subtree below the line.
1062 - When in the middle of the headline text, kill the headline up to the tags.
1063 - When after the headline text, kill the tags."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-ctrl-k-protect-subtree nil
1068 "Non-nil means, do not delete a hidden subtree with C-k.
1069 When set to the symbol `error', simply throw an error when C-k is
1070 used to kill (part-of) a headline that has hidden text behind it.
1071 Any other non-nil value will result in a query to the user, if it is
1072 OK to kill that hidden subtree. When nil, kill without remorse."
1073 :group 'org-edit-structure
1074 :version "24.1"
1075 :type '(choice
1076 (const :tag "Do not protect hidden subtrees" nil)
1077 (const :tag "Protect hidden subtrees with a security query" t)
1078 (const :tag "Never kill a hidden subtree with C-k" error)))
1080 (defcustom org-catch-invisible-edits nil
1081 "Check if in invisible region before inserting or deleting a character.
1082 Valid values are:
1084 nil Do not check, so just do invisible edits.
1085 error Throw an error and do nothing.
1086 show Make point visible, and do the requested edit.
1087 show-and-error Make point visible, then throw an error and abort the edit.
1088 smart Make point visible, and do insertion/deletion if it is
1089 adjacent to visible text and the change feels predictable.
1090 Never delete a previously invisible character or add in the
1091 middle or right after an invisible region. Basically, this
1092 allows insertion and backward-delete right before ellipses.
1093 FIXME: maybe in this case we should not even show?"
1094 :group 'org-edit-structure
1095 :version "24.1"
1096 :type '(choice
1097 (const :tag "Do not check" nil)
1098 (const :tag "Throw error when trying to edit" error)
1099 (const :tag "Unhide, but do not do the edit" show-and-error)
1100 (const :tag "Show invisible part and do the edit" show)
1101 (const :tag "Be smart and do the right thing" smart)))
1103 (defcustom org-yank-folded-subtrees t
1104 "Non-nil means when yanking subtrees, fold them.
1105 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1106 it starts with a heading and all other headings in it are either children
1107 or siblings, then fold all the subtrees. However, do this only if no
1108 text after the yank would be swallowed into a folded tree by this action."
1109 :group 'org-edit-structure
1110 :type 'boolean)
1112 (defcustom org-yank-adjusted-subtrees nil
1113 "Non-nil means when yanking subtrees, adjust the level.
1114 With this setting, `org-paste-subtree' is used to insert the subtree, see
1115 this function for details."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-M-RET-may-split-line '((default . t))
1120 "Non-nil means M-RET will split the line at the cursor position.
1121 When nil, it will go to the end of the line before making a
1122 new line.
1123 You may also set this option in a different way for different
1124 contexts. Valid contexts are:
1126 headline when creating a new headline
1127 item when creating a new item
1128 table in a table field
1129 default the value to be used for all contexts not explicitly
1130 customized"
1131 :group 'org-structure
1132 :group 'org-table
1133 :type '(choice
1134 (const :tag "Always" t)
1135 (const :tag "Never" nil)
1136 (repeat :greedy t :tag "Individual contexts"
1137 (cons
1138 (choice :tag "Context"
1139 (const headline)
1140 (const item)
1141 (const table)
1142 (const default))
1143 (boolean)))))
1146 (defcustom org-insert-heading-respect-content nil
1147 "Non-nil means insert new headings after the current subtree.
1148 When nil, the new heading is created directly after the current line.
1149 The commands \\[org-insert-heading-respect-content] and
1150 \\[org-insert-todo-heading-respect-content] turn this variable on
1151 for the duration of the command."
1152 :group 'org-structure
1153 :type 'boolean)
1155 (defcustom org-blank-before-new-entry '((heading . auto)
1156 (plain-list-item . auto))
1157 "Should `org-insert-heading' leave a blank line before new heading/item?
1158 The value is an alist, with `heading' and `plain-list-item' as CAR,
1159 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1160 which case Org will look at the surrounding headings/items and try to
1161 make an intelligent decision whether to insert a blank line or not.
1163 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1164 set, the setting here is ignored and no empty line is inserted, to avoid
1165 breaking the list structure."
1166 :group 'org-edit-structure
1167 :type '(list
1168 (cons (const heading)
1169 (choice (const :tag "Never" nil)
1170 (const :tag "Always" t)
1171 (const :tag "Auto" auto)))
1172 (cons (const plain-list-item)
1173 (choice (const :tag "Never" nil)
1174 (const :tag "Always" t)
1175 (const :tag "Auto" auto)))))
1177 (defcustom org-insert-heading-hook nil
1178 "Hook being run after inserting a new heading."
1179 :group 'org-edit-structure
1180 :type 'hook)
1182 (defcustom org-enable-fixed-width-editor t
1183 "Non-nil means lines starting with \":\" are treated as fixed-width.
1184 This currently only means they are never auto-wrapped.
1185 When nil, such lines will be treated like ordinary lines.
1186 See also the QUOTE keyword."
1187 :group 'org-edit-structure
1188 :type 'boolean)
1190 (defcustom org-goto-auto-isearch t
1191 "Non-nil means typing characters in `org-goto' starts incremental search."
1192 :group 'org-edit-structure
1193 :type 'boolean)
1195 (defgroup org-sparse-trees nil
1196 "Options concerning sparse trees in Org-mode."
1197 :tag "Org Sparse Trees"
1198 :group 'org-structure)
1200 (defcustom org-highlight-sparse-tree-matches t
1201 "Non-nil means highlight all matches that define a sparse tree.
1202 The highlights will automatically disappear the next time the buffer is
1203 changed by an edit command."
1204 :group 'org-sparse-trees
1205 :type 'boolean)
1207 (defcustom org-remove-highlights-with-change t
1208 "Non-nil means any change to the buffer will remove temporary highlights.
1209 Such highlights are created by `org-occur' and `org-clock-display'.
1210 When nil, `C-c C-c needs to be used to get rid of the highlights.
1211 The highlights created by `org-preview-latex-fragment' always need
1212 `C-c C-c' to be removed."
1213 :group 'org-sparse-trees
1214 :group 'org-time
1215 :type 'boolean)
1218 (defcustom org-occur-hook '(org-first-headline-recenter)
1219 "Hook that is run after `org-occur' has constructed a sparse tree.
1220 This can be used to recenter the window to show as much of the structure
1221 as possible."
1222 :group 'org-sparse-trees
1223 :type 'hook)
1225 (defgroup org-imenu-and-speedbar nil
1226 "Options concerning imenu and speedbar in Org-mode."
1227 :tag "Org Imenu and Speedbar"
1228 :group 'org-structure)
1230 (defcustom org-imenu-depth 2
1231 "The maximum level for Imenu access to Org-mode headlines.
1232 This also applied for speedbar access."
1233 :group 'org-imenu-and-speedbar
1234 :type 'integer)
1236 (defgroup org-table nil
1237 "Options concerning tables in Org-mode."
1238 :tag "Org Table"
1239 :group 'org)
1241 (defcustom org-enable-table-editor 'optimized
1242 "Non-nil means lines starting with \"|\" are handled by the table editor.
1243 When nil, such lines will be treated like ordinary lines.
1245 When equal to the symbol `optimized', the table editor will be optimized to
1246 do the following:
1247 - Automatic overwrite mode in front of whitespace in table fields.
1248 This makes the structure of the table stay in tact as long as the edited
1249 field does not exceed the column width.
1250 - Minimize the number of realigns. Normally, the table is aligned each time
1251 TAB or RET are pressed to move to another field. With optimization this
1252 happens only if changes to a field might have changed the column width.
1253 Optimization requires replacing the functions `self-insert-command',
1254 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1255 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1256 very good at guessing when a re-align will be necessary, but you can always
1257 force one with \\[org-ctrl-c-ctrl-c].
1259 If you would like to use the optimized version in Org-mode, but the
1260 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1262 This variable can be used to turn on and off the table editor during a session,
1263 but in order to toggle optimization, a restart is required.
1265 See also the variable `org-table-auto-blank-field'."
1266 :group 'org-table
1267 :type '(choice
1268 (const :tag "off" nil)
1269 (const :tag "on" t)
1270 (const :tag "on, optimized" optimized)))
1272 (defcustom org-self-insert-cluster-for-undo t
1273 "Non-nil means cluster self-insert commands for undo when possible.
1274 If this is set, then, like in the Emacs command loop, 20 consecutive
1275 characters will be undone together.
1276 This is configurable, because there is some impact on typing performance."
1277 :group 'org-table
1278 :type 'boolean)
1280 (defcustom org-table-tab-recognizes-table.el t
1281 "Non-nil means TAB will automatically notice a table.el table.
1282 When it sees such a table, it moves point into it and - if necessary -
1283 calls `table-recognize-table'."
1284 :group 'org-table-editing
1285 :type 'boolean)
1287 (defgroup org-link nil
1288 "Options concerning links in Org-mode."
1289 :tag "Org Link"
1290 :group 'org)
1292 (defvar org-link-abbrev-alist-local nil
1293 "Buffer-local version of `org-link-abbrev-alist', which see.
1294 The value of this is taken from the #+LINK lines.")
1295 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1297 (defcustom org-link-abbrev-alist nil
1298 "Alist of link abbreviations.
1299 The car of each element is a string, to be replaced at the start of a link.
1300 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1301 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1303 [[linkkey:tag][description]]
1305 The 'linkkey' must be a word word, starting with a letter, followed
1306 by letters, numbers, '-' or '_'.
1308 If REPLACE is a string, the tag will simply be appended to create the link.
1309 If the string contains \"%s\", the tag will be inserted there. If the string
1310 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1311 at that point (see the function `url-hexify-string'). If the string contains
1312 the specifier \"%(my-function)\", then the custom function `my-function' will
1313 be invoked: this function takes the tag as its only argument and must return
1314 a string.
1316 REPLACE may also be a function that will be called with the tag as the
1317 only argument to create the link, which should be returned as a string.
1319 See the manual for examples."
1320 :group 'org-link
1321 :type '(repeat
1322 (cons
1323 (string :tag "Protocol")
1324 (choice
1325 (string :tag "Format")
1326 (function)))))
1328 (defcustom org-descriptive-links t
1329 "Non-nil means Org will display descriptive links.
1330 E.g. [[http://orgmode.org][Org website]] will be displayed as
1331 \"Org Website\", hiding the link itself and just displaying its
1332 description. When set to `nil', Org will display the full links
1333 literally.
1335 You can interactively set the value of this variable by calling
1336 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1337 :group 'org-link
1338 :type 'boolean)
1340 (defcustom org-link-file-path-type 'adaptive
1341 "How the path name in file links should be stored.
1342 Valid values are:
1344 relative Relative to the current directory, i.e. the directory of the file
1345 into which the link is being inserted.
1346 absolute Absolute path, if possible with ~ for home directory.
1347 noabbrev Absolute path, no abbreviation of home directory.
1348 adaptive Use relative path for files in the current directory and sub-
1349 directories of it. For other files, use an absolute path."
1350 :group 'org-link
1351 :type '(choice
1352 (const relative)
1353 (const absolute)
1354 (const noabbrev)
1355 (const adaptive)))
1357 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1358 "Types of links that should be activated in Org-mode files.
1359 This is a list of symbols, each leading to the activation of a certain link
1360 type. In principle, it does not hurt to turn on most link types - there may
1361 be a small gain when turning off unused link types. The types are:
1363 bracket The recommended [[link][description]] or [[link]] links with hiding.
1364 angle Links in angular brackets that may contain whitespace like
1365 <bbdb:Carsten Dominik>.
1366 plain Plain links in normal text, no whitespace, like http://google.com.
1367 radio Text that is matched by a radio target, see manual for details.
1368 tag Tag settings in a headline (link to tag search).
1369 date Time stamps (link to calendar).
1370 footnote Footnote labels.
1372 Changing this variable requires a restart of Emacs to become effective."
1373 :group 'org-link
1374 :type '(set :greedy t
1375 (const :tag "Double bracket links" bracket)
1376 (const :tag "Angular bracket links" angle)
1377 (const :tag "Plain text links" plain)
1378 (const :tag "Radio target matches" radio)
1379 (const :tag "Tags" tag)
1380 (const :tag "Timestamps" date)
1381 (const :tag "Footnotes" footnote)))
1383 (defcustom org-make-link-description-function nil
1384 "Function to use to generate link descriptions from links.
1385 If nil the link location will be used. This function must take
1386 two parameters; the first is the link and the second the
1387 description `org-insert-link' has generated, and should return the
1388 description to use."
1389 :group 'org-link
1390 :type 'function)
1392 (defgroup org-link-store nil
1393 "Options concerning storing links in Org-mode."
1394 :tag "Org Store Link"
1395 :group 'org-link)
1397 (defcustom org-email-link-description-format "Email %c: %.30s"
1398 "Format of the description part of a link to an email or usenet message.
1399 The following %-escapes will be replaced by corresponding information:
1401 %F full \"From\" field
1402 %f name, taken from \"From\" field, address if no name
1403 %T full \"To\" field
1404 %t first name in \"To\" field, address if no name
1405 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1406 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1407 %s subject
1408 %d date
1409 %m message-id.
1411 You may use normal field width specification between the % and the letter.
1412 This is for example useful to limit the length of the subject.
1414 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1415 :group 'org-link-store
1416 :type 'string)
1418 (defcustom org-from-is-user-regexp
1419 (let (r1 r2)
1420 (when (and user-mail-address (not (string= user-mail-address "")))
1421 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1422 (when (and user-full-name (not (string= user-full-name "")))
1423 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1424 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1425 "Regexp matched against the \"From:\" header of an email or usenet message.
1426 It should match if the message is from the user him/herself."
1427 :group 'org-link-store
1428 :type 'regexp)
1430 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1431 "Non-nil means storing a link to an Org file will use entry IDs.
1433 Note that before this variable is even considered, org-id must be loaded,
1434 so please customize `org-modules' and turn it on.
1436 The variable can have the following values:
1438 t Create an ID if needed to make a link to the current entry.
1440 create-if-interactive
1441 If `org-store-link' is called directly (interactively, as a user
1442 command), do create an ID to support the link. But when doing the
1443 job for remember, only use the ID if it already exists. The
1444 purpose of this setting is to avoid proliferation of unwanted
1445 IDs, just because you happen to be in an Org file when you
1446 call `org-remember' that automatically and preemptively
1447 creates a link. If you do want to get an ID link in a remember
1448 template to an entry not having an ID, create it first by
1449 explicitly creating a link to it, using `C-c C-l' first.
1451 create-if-interactive-and-no-custom-id
1452 Like create-if-interactive, but do not create an ID if there is
1453 a CUSTOM_ID property defined in the entry. This is the default.
1455 use-existing
1456 Use existing ID, do not create one.
1458 nil Never use an ID to make a link, instead link using a text search for
1459 the headline text."
1460 :group 'org-link-store
1461 :type '(choice
1462 (const :tag "Create ID to make link" t)
1463 (const :tag "Create if storing link interactively"
1464 create-if-interactive)
1465 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1466 create-if-interactive-and-no-custom-id)
1467 (const :tag "Only use existing" use-existing)
1468 (const :tag "Do not use ID to create link" nil)))
1470 (defcustom org-context-in-file-links t
1471 "Non-nil means file links from `org-store-link' contain context.
1472 A search string will be added to the file name with :: as separator and
1473 used to find the context when the link is activated by the command
1474 `org-open-at-point'. When this option is t, the entire active region
1475 will be placed in the search string of the file link. If set to a
1476 positive integer, only the first n lines of context will be stored.
1478 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1479 negates this setting for the duration of the command."
1480 :group 'org-link-store
1481 :type '(choice boolean integer))
1483 (defcustom org-keep-stored-link-after-insertion nil
1484 "Non-nil means keep link in list for entire session.
1486 The command `org-store-link' adds a link pointing to the current
1487 location to an internal list. These links accumulate during a session.
1488 The command `org-insert-link' can be used to insert links into any
1489 Org-mode file (offering completion for all stored links). When this
1490 option is nil, every link which has been inserted once using \\[org-insert-link]
1491 will be removed from the list, to make completing the unused links
1492 more efficient."
1493 :group 'org-link-store
1494 :type 'boolean)
1496 (defgroup org-link-follow nil
1497 "Options concerning following links in Org-mode."
1498 :tag "Org Follow Link"
1499 :group 'org-link)
1501 (defcustom org-link-translation-function nil
1502 "Function to translate links with different syntax to Org syntax.
1503 This can be used to translate links created for example by the Planner
1504 or emacs-wiki packages to Org syntax.
1505 The function must accept two parameters, a TYPE containing the link
1506 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1507 which is everything after the link protocol. It should return a cons
1508 with possibly modified values of type and path.
1509 Org contains a function for this, so if you set this variable to
1510 `org-translate-link-from-planner', you should be able follow many
1511 links created by planner."
1512 :group 'org-link-follow
1513 :type 'function)
1515 (defcustom org-follow-link-hook nil
1516 "Hook that is run after a link has been followed."
1517 :group 'org-link-follow
1518 :type 'hook)
1520 (defcustom org-tab-follows-link nil
1521 "Non-nil means on links TAB will follow the link.
1522 Needs to be set before org.el is loaded.
1523 This really should not be used, it does not make sense, and the
1524 implementation is bad."
1525 :group 'org-link-follow
1526 :type 'boolean)
1528 (defcustom org-return-follows-link nil
1529 "Non-nil means on links RET will follow the link."
1530 :group 'org-link-follow
1531 :type 'boolean)
1533 (defcustom org-mouse-1-follows-link
1534 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1535 "Non-nil means mouse-1 on a link will follow the link.
1536 A longer mouse click will still set point. Does not work on XEmacs.
1537 Needs to be set before org.el is loaded."
1538 :group 'org-link-follow
1539 :type 'boolean)
1541 (defcustom org-mark-ring-length 4
1542 "Number of different positions to be recorded in the ring.
1543 Changing this requires a restart of Emacs to work correctly."
1544 :group 'org-link-follow
1545 :type 'integer)
1547 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1548 "Non-nil means internal links in Org files must exactly match a headline.
1549 When nil, the link search tries to match a phrase with all words
1550 in the search text."
1551 :group 'org-link-follow
1552 :version "24.1"
1553 :type '(choice
1554 (const :tag "Use fuzzy text search" nil)
1555 (const :tag "Match only exact headline" t)
1556 (const :tag "Match exact headline or query to create it"
1557 query-to-create)))
1559 (defcustom org-link-frame-setup
1560 '((vm . vm-visit-folder-other-frame)
1561 (vm-imap . vm-visit-imap-folder-other-frame)
1562 (gnus . org-gnus-no-new-news)
1563 (file . find-file-other-window)
1564 (wl . wl-other-frame))
1565 "Setup the frame configuration for following links.
1566 When following a link with Emacs, it may often be useful to display
1567 this link in another window or frame. This variable can be used to
1568 set this up for the different types of links.
1569 For VM, use any of
1570 `vm-visit-folder'
1571 `vm-visit-folder-other-window'
1572 `vm-visit-folder-other-frame'
1573 For Gnus, use any of
1574 `gnus'
1575 `gnus-other-frame'
1576 `org-gnus-no-new-news'
1577 For FILE, use any of
1578 `find-file'
1579 `find-file-other-window'
1580 `find-file-other-frame'
1581 For Wanderlust use any of
1582 `wl'
1583 `wl-other-frame'
1584 For the calendar, use the variable `calendar-setup'.
1585 For BBDB, it is currently only possible to display the matches in
1586 another window."
1587 :group 'org-link-follow
1588 :type '(list
1589 (cons (const vm)
1590 (choice
1591 (const vm-visit-folder)
1592 (const vm-visit-folder-other-window)
1593 (const vm-visit-folder-other-frame)))
1594 (cons (const gnus)
1595 (choice
1596 (const gnus)
1597 (const gnus-other-frame)
1598 (const org-gnus-no-new-news)))
1599 (cons (const file)
1600 (choice
1601 (const find-file)
1602 (const find-file-other-window)
1603 (const find-file-other-frame)))
1604 (cons (const wl)
1605 (choice
1606 (const wl)
1607 (const wl-other-frame)))))
1609 (defcustom org-display-internal-link-with-indirect-buffer nil
1610 "Non-nil means use indirect buffer to display infile links.
1611 Activating internal links (from one location in a file to another location
1612 in the same file) normally just jumps to the location. When the link is
1613 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1614 is displayed in
1615 another window. When this option is set, the other window actually displays
1616 an indirect buffer clone of the current buffer, to avoid any visibility
1617 changes to the current buffer."
1618 :group 'org-link-follow
1619 :type 'boolean)
1621 (defcustom org-open-non-existing-files nil
1622 "Non-nil means `org-open-file' will open non-existing files.
1623 When nil, an error will be generated.
1624 This variable applies only to external applications because they
1625 might choke on non-existing files. If the link is to a file that
1626 will be opened in Emacs, the variable is ignored."
1627 :group 'org-link-follow
1628 :type 'boolean)
1630 (defcustom org-open-directory-means-index-dot-org nil
1631 "Non-nil means a link to a directory really means to index.org.
1632 When nil, following a directory link will run dired or open a finder/explorer
1633 window on that directory."
1634 :group 'org-link-follow
1635 :type 'boolean)
1637 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1638 "Function and arguments to call for following mailto links.
1639 This is a list with the first element being a Lisp function, and the
1640 remaining elements being arguments to the function. In string arguments,
1641 %a will be replaced by the address, and %s will be replaced by the subject
1642 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1643 :group 'org-link-follow
1644 :type '(choice
1645 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1646 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1647 (const :tag "message-mail" (message-mail "%a" "%s"))
1648 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1650 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1651 "Non-nil means ask for confirmation before executing shell links.
1652 Shell links can be dangerous: just think about a link
1654 [[shell:rm -rf ~/*][Google Search]]
1656 This link would show up in your Org-mode document as \"Google Search\",
1657 but really it would remove your entire home directory.
1658 Therefore we advise against setting this variable to nil.
1659 Just change it to `y-or-n-p' if you want to confirm with a
1660 single keystroke rather than having to type \"yes\"."
1661 :group 'org-link-follow
1662 :type '(choice
1663 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1664 (const :tag "with y-or-n (faster)" y-or-n-p)
1665 (const :tag "no confirmation (dangerous)" nil)))
1666 (put 'org-confirm-shell-link-function
1667 'safe-local-variable
1668 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1670 (defcustom org-confirm-shell-link-not-regexp ""
1671 "A regexp to skip confirmation for shell links."
1672 :group 'org-link-follow
1673 :version "24.1"
1674 :type 'regexp)
1676 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1677 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1678 Elisp links can be dangerous: just think about a link
1680 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1682 This link would show up in your Org-mode document as \"Google Search\",
1683 but really it would remove your entire home directory.
1684 Therefore we advise against setting this variable to nil.
1685 Just change it to `y-or-n-p' if you want to confirm with a
1686 single keystroke rather than having to type \"yes\"."
1687 :group 'org-link-follow
1688 :type '(choice
1689 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1690 (const :tag "with y-or-n (faster)" y-or-n-p)
1691 (const :tag "no confirmation (dangerous)" nil)))
1692 (put 'org-confirm-shell-link-function
1693 'safe-local-variable
1694 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1696 (defcustom org-confirm-elisp-link-not-regexp ""
1697 "A regexp to skip confirmation for Elisp links."
1698 :group 'org-link-follow
1699 :version "24.1"
1700 :type 'regexp)
1702 (defconst org-file-apps-defaults-gnu
1703 '((remote . emacs)
1704 (system . mailcap)
1705 (t . mailcap))
1706 "Default file applications on a UNIX or GNU/Linux system.
1707 See `org-file-apps'.")
1709 (defconst org-file-apps-defaults-macosx
1710 '((remote . emacs)
1711 (t . "open %s")
1712 (system . "open %s")
1713 ("ps.gz" . "gv %s")
1714 ("eps.gz" . "gv %s")
1715 ("dvi" . "xdvi %s")
1716 ("fig" . "xfig %s"))
1717 "Default file applications on a MacOS X system.
1718 The system \"open\" is known as a default, but we use X11 applications
1719 for some files for which the OS does not have a good default.
1720 See `org-file-apps'.")
1722 (defconst org-file-apps-defaults-windowsnt
1723 (list
1724 '(remote . emacs)
1725 (cons t
1726 (list (if (featurep 'xemacs)
1727 'mswindows-shell-execute
1728 'w32-shell-execute)
1729 "open" 'file))
1730 (cons 'system
1731 (list (if (featurep 'xemacs)
1732 'mswindows-shell-execute
1733 'w32-shell-execute)
1734 "open" 'file)))
1735 "Default file applications on a Windows NT system.
1736 The system \"open\" is used for most files.
1737 See `org-file-apps'.")
1739 (defcustom org-file-apps
1741 (auto-mode . emacs)
1742 ("\\.mm\\'" . default)
1743 ("\\.x?html?\\'" . default)
1744 ("\\.pdf\\'" . default)
1746 "External applications for opening `file:path' items in a document.
1747 Org-mode uses system defaults for different file types, but
1748 you can use this variable to set the application for a given file
1749 extension. The entries in this list are cons cells where the car identifies
1750 files and the cdr the corresponding command. Possible values for the
1751 file identifier are
1752 \"string\" A string as a file identifier can be interpreted in different
1753 ways, depending on its contents:
1755 - Alphanumeric characters only:
1756 Match links with this file extension.
1757 Example: (\"pdf\" . \"evince %s\")
1758 to open PDFs with evince.
1760 - Regular expression: Match links where the
1761 filename matches the regexp. If you want to
1762 use groups here, use shy groups.
1764 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1765 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1766 to open *.html and *.xhtml with firefox.
1768 - Regular expression which contains (non-shy) groups:
1769 Match links where the whole link, including \"::\", and
1770 anything after that, matches the regexp.
1771 In a custom command string, %1, %2, etc. are replaced with
1772 the parts of the link that were matched by the groups.
1773 For backwards compatibility, if a command string is given
1774 that does not use any of the group matches, this case is
1775 handled identically to the second one (i.e. match against
1776 file name only).
1777 In a custom lisp form, you can access the group matches with
1778 (match-string n link).
1780 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1781 to open [[file:document.pdf::5]] with evince at page 5.
1783 `directory' Matches a directory
1784 `remote' Matches a remote file, accessible through tramp or efs.
1785 Remote files most likely should be visited through Emacs
1786 because external applications cannot handle such paths.
1787 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1788 so all files Emacs knows how to handle. Using this with
1789 command `emacs' will open most files in Emacs. Beware that this
1790 will also open html files inside Emacs, unless you add
1791 (\"html\" . default) to the list as well.
1792 t Default for files not matched by any of the other options.
1793 `system' The system command to open files, like `open' on Windows
1794 and Mac OS X, and mailcap under GNU/Linux. This is the command
1795 that will be selected if you call `C-c C-o' with a double
1796 \\[universal-argument] \\[universal-argument] prefix.
1798 Possible values for the command are:
1799 `emacs' The file will be visited by the current Emacs process.
1800 `default' Use the default application for this file type, which is the
1801 association for t in the list, most likely in the system-specific
1802 part.
1803 This can be used to overrule an unwanted setting in the
1804 system-specific variable.
1805 `system' Use the system command for opening files, like \"open\".
1806 This command is specified by the entry whose car is `system'.
1807 Most likely, the system-specific version of this variable
1808 does define this command, but you can overrule/replace it
1809 here.
1810 string A command to be executed by a shell; %s will be replaced
1811 by the path to the file.
1812 sexp A Lisp form which will be evaluated. The file path will
1813 be available in the Lisp variable `file'.
1814 For more examples, see the system specific constants
1815 `org-file-apps-defaults-macosx'
1816 `org-file-apps-defaults-windowsnt'
1817 `org-file-apps-defaults-gnu'."
1818 :group 'org-link-follow
1819 :type '(repeat
1820 (cons (choice :value ""
1821 (string :tag "Extension")
1822 (const :tag "System command to open files" system)
1823 (const :tag "Default for unrecognized files" t)
1824 (const :tag "Remote file" remote)
1825 (const :tag "Links to a directory" directory)
1826 (const :tag "Any files that have Emacs modes"
1827 auto-mode))
1828 (choice :value ""
1829 (const :tag "Visit with Emacs" emacs)
1830 (const :tag "Use default" default)
1831 (const :tag "Use the system command" system)
1832 (string :tag "Command")
1833 (sexp :tag "Lisp form")))))
1835 (defcustom org-doi-server-url "http://dx.doi.org/"
1836 "The URL of the DOI server."
1837 :type 'string
1838 :version "24.2"
1839 :group 'org-link-follow)
1841 (defgroup org-refile nil
1842 "Options concerning refiling entries in Org-mode."
1843 :tag "Org Refile"
1844 :group 'org)
1846 (defcustom org-directory "~/org"
1847 "Directory with org files.
1848 This is just a default location to look for Org files. There is no need
1849 at all to put your files into this directory. It is only used in the
1850 following situations:
1852 1. When a remember template specifies a target file that is not an
1853 absolute path. The path will then be interpreted relative to
1854 `org-directory'
1855 2. When a remember note is filed away in an interactive way (when exiting the
1856 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1857 with `org-directory' as the default path."
1858 :group 'org-refile
1859 :group 'org-remember
1860 :type 'directory)
1862 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1863 "Default target for storing notes.
1864 Used as a fall back file for org-remember.el and org-capture.el, for
1865 templates that do not specify a target file."
1866 :group 'org-refile
1867 :group 'org-remember
1868 :type '(choice
1869 (const :tag "Default from remember-data-file" nil)
1870 file))
1872 (defcustom org-goto-interface 'outline
1873 "The default interface to be used for `org-goto'.
1874 Allowed values are:
1875 outline The interface shows an outline of the relevant file
1876 and the correct heading is found by moving through
1877 the outline or by searching with incremental search.
1878 outline-path-completion Headlines in the current buffer are offered via
1879 completion. This is the interface also used by
1880 the refile command."
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Outline" outline)
1884 (const :tag "Outline-path-completion" outline-path-completion)))
1886 (defcustom org-goto-max-level 5
1887 "Maximum target level when running `org-goto' with refile interface."
1888 :group 'org-refile
1889 :type 'integer)
1891 (defcustom org-reverse-note-order nil
1892 "Non-nil means store new notes at the beginning of a file or entry.
1893 When nil, new notes will be filed to the end of a file or entry.
1894 This can also be a list with cons cells of regular expressions that
1895 are matched against file names, and values."
1896 :group 'org-remember
1897 :group 'org-refile
1898 :type '(choice
1899 (const :tag "Reverse always" t)
1900 (const :tag "Reverse never" nil)
1901 (repeat :tag "By file name regexp"
1902 (cons regexp boolean))))
1904 (defcustom org-log-refile nil
1905 "Information to record when a task is refiled.
1907 Possible values are:
1909 nil Don't add anything
1910 time Add a time stamp to the task
1911 note Prompt for a note and add it with template `org-log-note-headings'
1913 This option can also be set with on a per-file-basis with
1915 #+STARTUP: nologrefile
1916 #+STARTUP: logrefile
1917 #+STARTUP: lognoterefile
1919 You can have local logging settings for a subtree by setting the LOGGING
1920 property to one or more of these keywords.
1922 When bulk-refiling from the agenda, the value `note' is forbidden and
1923 will temporarily be changed to `time'."
1924 :group 'org-refile
1925 :group 'org-progress
1926 :version "24.1"
1927 :type '(choice
1928 (const :tag "No logging" nil)
1929 (const :tag "Record timestamp" time)
1930 (const :tag "Record timestamp with note." note)))
1932 (defcustom org-refile-targets nil
1933 "Targets for refiling entries with \\[org-refile].
1934 This is a list of cons cells. Each cell contains:
1935 - a specification of the files to be considered, either a list of files,
1936 or a symbol whose function or variable value will be used to retrieve
1937 a file name or a list of file names. If you use `org-agenda-files' for
1938 that, all agenda files will be scanned for targets. Nil means consider
1939 headings in the current buffer.
1940 - A specification of how to find candidate refile targets. This may be
1941 any of:
1942 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1943 This tag has to be present in all target headlines, inheritance will
1944 not be considered.
1945 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1946 todo keyword.
1947 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1948 headlines that are refiling targets.
1949 - a cons cell (:level . N). Any headline of level N is considered a target.
1950 Note that, when `org-odd-levels-only' is set, level corresponds to
1951 order in hierarchy, not to the number of stars.
1952 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1953 Note that, when `org-odd-levels-only' is set, level corresponds to
1954 order in hierarchy, not to the number of stars.
1956 Each element of this list generates a set of possible targets.
1957 The union of these sets is presented (with completion) to
1958 the user by `org-refile'.
1960 You can set the variable `org-refile-target-verify-function' to a function
1961 to verify each headline found by the simple criteria above.
1963 When this variable is nil, all top-level headlines in the current buffer
1964 are used, equivalent to the value `((nil . (:level . 1))'."
1965 :group 'org-refile
1966 :type '(repeat
1967 (cons
1968 (choice :value org-agenda-files
1969 (const :tag "All agenda files" org-agenda-files)
1970 (const :tag "Current buffer" nil)
1971 (function) (variable) (file))
1972 (choice :tag "Identify target headline by"
1973 (cons :tag "Specific tag" (const :value :tag) (string))
1974 (cons :tag "TODO keyword" (const :value :todo) (string))
1975 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1976 (cons :tag "Level number" (const :value :level) (integer))
1977 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1979 (defcustom org-refile-target-verify-function nil
1980 "Function to verify if the headline at point should be a refile target.
1981 The function will be called without arguments, with point at the
1982 beginning of the headline. It should return t and leave point
1983 where it is if the headline is a valid target for refiling.
1985 If the target should not be selected, the function must return nil.
1986 In addition to this, it may move point to a place from where the search
1987 should be continued. For example, the function may decide that the entire
1988 subtree of the current entry should be excluded and move point to the end
1989 of the subtree."
1990 :group 'org-refile
1991 :type 'function)
1993 (defcustom org-refile-use-cache nil
1994 "Non-nil means cache refile targets to speed up the process.
1995 The cache for a particular file will be updated automatically when
1996 the buffer has been killed, or when any of the marker used for flagging
1997 refile targets no longer points at a live buffer.
1998 If you have added new entries to a buffer that might themselves be targets,
1999 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2000 find that easier, `C-u C-u C-u C-c C-w'."
2001 :group 'org-refile
2002 :version "24.1"
2003 :type 'boolean)
2005 (defcustom org-refile-use-outline-path nil
2006 "Non-nil means provide refile targets as paths.
2007 So a level 3 headline will be available as level1/level2/level3.
2009 When the value is `file', also include the file name (without directory)
2010 into the path. In this case, you can also stop the completion after
2011 the file name, to get entries inserted as top level in the file.
2013 When `full-file-path', include the full file path."
2014 :group 'org-refile
2015 :type '(choice
2016 (const :tag "Not" nil)
2017 (const :tag "Yes" t)
2018 (const :tag "Start with file name" file)
2019 (const :tag "Start with full file path" full-file-path)))
2021 (defcustom org-outline-path-complete-in-steps t
2022 "Non-nil means complete the outline path in hierarchical steps.
2023 When Org-mode uses the refile interface to select an outline path
2024 \(see variable `org-refile-use-outline-path'), the completion of
2025 the path can be done is a single go, or if can be done in steps down
2026 the headline hierarchy. Going in steps is probably the best if you
2027 do not use a special completion package like `ido' or `icicles'.
2028 However, when using these packages, going in one step can be very
2029 fast, while still showing the whole path to the entry."
2030 :group 'org-refile
2031 :type 'boolean)
2033 (defcustom org-refile-allow-creating-parent-nodes nil
2034 "Non-nil means allow to create new nodes as refile targets.
2035 New nodes are then created by adding \"/new node name\" to the completion
2036 of an existing node. When the value of this variable is `confirm',
2037 new node creation must be confirmed by the user (recommended)
2038 When nil, the completion must match an existing entry.
2040 Note that, if the new heading is not seen by the criteria
2041 listed in `org-refile-targets', multiple instances of the same
2042 heading would be created by trying again to file under the new
2043 heading."
2044 :group 'org-refile
2045 :type '(choice
2046 (const :tag "Never" nil)
2047 (const :tag "Always" t)
2048 (const :tag "Prompt for confirmation" confirm)))
2050 (defcustom org-refile-active-region-within-subtree nil
2051 "Non-nil means also refile active region within a subtree.
2053 By default `org-refile' doesn't allow refiling regions if they
2054 don't contain a set of subtrees, but it might be convenient to
2055 do so sometimes: in that case, the first line of the region is
2056 converted to a headline before refiling."
2057 :group 'org-refile
2058 :version "24.1"
2059 :type 'boolean)
2061 (defgroup org-todo nil
2062 "Options concerning TODO items in Org-mode."
2063 :tag "Org TODO"
2064 :group 'org)
2066 (defgroup org-progress nil
2067 "Options concerning Progress logging in Org-mode."
2068 :tag "Org Progress"
2069 :group 'org-time)
2071 (defvar org-todo-interpretation-widgets
2072 '((:tag "Sequence (cycling hits every state)" sequence)
2073 (:tag "Type (cycling directly to DONE)" type))
2074 "The available interpretation symbols for customizing `org-todo-keywords'.
2075 Interested libraries should add to this list.")
2077 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2078 "List of TODO entry keyword sequences and their interpretation.
2079 \\<org-mode-map>This is a list of sequences.
2081 Each sequence starts with a symbol, either `sequence' or `type',
2082 indicating if the keywords should be interpreted as a sequence of
2083 action steps, or as different types of TODO items. The first
2084 keywords are states requiring action - these states will select a headline
2085 for inclusion into the global TODO list Org-mode produces. If one of
2086 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2087 signify that no further action is necessary. If \"|\" is not found,
2088 the last keyword is treated as the only DONE state of the sequence.
2090 The command \\[org-todo] cycles an entry through these states, and one
2091 additional state where no keyword is present. For details about this
2092 cycling, see the manual.
2094 TODO keywords and interpretation can also be set on a per-file basis with
2095 the special #+SEQ_TODO and #+TYP_TODO lines.
2097 Each keyword can optionally specify a letter for fast state selection
2098 \(in combination with the variable `org-use-fast-todo-selection')
2099 and specifiers for state change logging, using the same syntax that
2100 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2101 the WAIT state can be selected with the \"w\" letter. \"WAIT(w!)\"
2102 indicates to record a time stamp each time this state is selected.
2104 Each keyword may also specify if a timestamp or a note should be
2105 recorded when entering or leaving the state, by adding additional
2106 characters in the parenthesis after the keyword. This looks like this:
2107 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2108 record only the time of the state change. With X and Y being either
2109 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2110 Y when leaving the state if and only if the *target* state does not
2111 define X. You may omit any of the fast-selection key or X or /Y,
2112 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2114 For backward compatibility, this variable may also be just a list
2115 of keywords. In this case the interpretation (sequence or type) will be
2116 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2117 :group 'org-todo
2118 :group 'org-keywords
2119 :type '(choice
2120 (repeat :tag "Old syntax, just keywords"
2121 (string :tag "Keyword"))
2122 (repeat :tag "New syntax"
2123 (cons
2124 (choice
2125 :tag "Interpretation"
2126 ;;Quick and dirty way to see
2127 ;;`org-todo-interpretations'. This takes the
2128 ;;place of item arguments
2129 :convert-widget
2130 (lambda (widget)
2131 (widget-put widget
2132 :args (mapcar
2133 #'(lambda (x)
2134 (widget-convert
2135 (cons 'const x)))
2136 org-todo-interpretation-widgets))
2137 widget))
2138 (repeat
2139 (string :tag "Keyword"))))))
2141 (defvar org-todo-keywords-1 nil
2142 "All TODO and DONE keywords active in a buffer.")
2143 (make-variable-buffer-local 'org-todo-keywords-1)
2144 (defvar org-todo-keywords-for-agenda nil)
2145 (defvar org-done-keywords-for-agenda nil)
2146 (defvar org-drawers-for-agenda nil)
2147 (defvar org-todo-keyword-alist-for-agenda nil)
2148 (defvar org-tag-alist-for-agenda nil)
2149 (defvar org-agenda-contributing-files nil)
2150 (defvar org-not-done-keywords nil)
2151 (make-variable-buffer-local 'org-not-done-keywords)
2152 (defvar org-done-keywords nil)
2153 (make-variable-buffer-local 'org-done-keywords)
2154 (defvar org-todo-heads nil)
2155 (make-variable-buffer-local 'org-todo-heads)
2156 (defvar org-todo-sets nil)
2157 (make-variable-buffer-local 'org-todo-sets)
2158 (defvar org-todo-log-states nil)
2159 (make-variable-buffer-local 'org-todo-log-states)
2160 (defvar org-todo-kwd-alist nil)
2161 (make-variable-buffer-local 'org-todo-kwd-alist)
2162 (defvar org-todo-key-alist nil)
2163 (make-variable-buffer-local 'org-todo-key-alist)
2164 (defvar org-todo-key-trigger nil)
2165 (make-variable-buffer-local 'org-todo-key-trigger)
2167 (defcustom org-todo-interpretation 'sequence
2168 "Controls how TODO keywords are interpreted.
2169 This variable is in principle obsolete and is only used for
2170 backward compatibility, if the interpretation of todo keywords is
2171 not given already in `org-todo-keywords'. See that variable for
2172 more information."
2173 :group 'org-todo
2174 :group 'org-keywords
2175 :type '(choice (const sequence)
2176 (const type)))
2178 (defcustom org-use-fast-todo-selection t
2179 "Non-nil means use the fast todo selection scheme with C-c C-t.
2180 This variable describes if and under what circumstances the cycling
2181 mechanism for TODO keywords will be replaced by a single-key, direct
2182 selection scheme.
2184 When nil, fast selection is never used.
2186 When the symbol `prefix', it will be used when `org-todo' is called
2187 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2188 `C-u t' in an agenda buffer.
2190 When t, fast selection is used by default. In this case, the prefix
2191 argument forces cycling instead.
2193 In all cases, the special interface is only used if access keys have
2194 actually been assigned by the user, i.e. if keywords in the configuration
2195 are followed by a letter in parenthesis, like TODO(t)."
2196 :group 'org-todo
2197 :type '(choice
2198 (const :tag "Never" nil)
2199 (const :tag "By default" t)
2200 (const :tag "Only with C-u C-c C-t" prefix)))
2202 (defcustom org-provide-todo-statistics t
2203 "Non-nil means update todo statistics after insert and toggle.
2204 ALL-HEADLINES means update todo statistics by including headlines
2205 with no TODO keyword as well, counting them as not done.
2206 A list of TODO keywords means the same, but skip keywords that are
2207 not in this list.
2209 When this is set, todo statistics is updated in the parent of the
2210 current entry each time a todo state is changed."
2211 :group 'org-todo
2212 :type '(choice
2213 (const :tag "Yes, only for TODO entries" t)
2214 (const :tag "Yes, including all entries" 'all-headlines)
2215 (repeat :tag "Yes, for TODOs in this list"
2216 (string :tag "TODO keyword"))
2217 (other :tag "No TODO statistics" nil)))
2219 (defcustom org-hierarchical-todo-statistics t
2220 "Non-nil means TODO statistics covers just direct children.
2221 When nil, all entries in the subtree are considered.
2222 This has only an effect if `org-provide-todo-statistics' is set.
2223 To set this to nil for only a single subtree, use a COOKIE_DATA
2224 property and include the word \"recursive\" into the value."
2225 :group 'org-todo
2226 :type 'boolean)
2228 (defcustom org-after-todo-state-change-hook nil
2229 "Hook which is run after the state of a TODO item was changed.
2230 The new state (a string with a TODO keyword, or nil) is available in the
2231 Lisp variable `org-state'."
2232 :group 'org-todo
2233 :type 'hook)
2235 (defvar org-blocker-hook nil
2236 "Hook for functions that are allowed to block a state change.
2238 Each function gets as its single argument a property list, see
2239 `org-trigger-hook' for more information about this list.
2241 If any of the functions in this hook returns nil, the state change
2242 is blocked.")
2244 (defvar org-trigger-hook nil
2245 "Hook for functions that are triggered by a state change.
2247 Each function gets as its single argument a property list with at least
2248 the following elements:
2250 (:type type-of-change :position pos-at-entry-start
2251 :from old-state :to new-state)
2253 Depending on the type, more properties may be present.
2255 This mechanism is currently implemented for:
2257 TODO state changes
2258 ------------------
2259 :type todo-state-change
2260 :from previous state (keyword as a string), or nil, or a symbol
2261 'todo' or 'done', to indicate the general type of state.
2262 :to new state, like in :from")
2264 (defcustom org-enforce-todo-dependencies nil
2265 "Non-nil means undone TODO entries will block switching the parent to DONE.
2266 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2267 be blocked if any prior sibling is not yet done.
2268 Finally, if the parent is blocked because of ordered siblings of its own,
2269 the child will also be blocked."
2270 :set (lambda (var val)
2271 (set var val)
2272 (if val
2273 (add-hook 'org-blocker-hook
2274 'org-block-todo-from-children-or-siblings-or-parent)
2275 (remove-hook 'org-blocker-hook
2276 'org-block-todo-from-children-or-siblings-or-parent)))
2277 :group 'org-todo
2278 :type 'boolean)
2280 (defcustom org-enforce-todo-checkbox-dependencies nil
2281 "Non-nil means unchecked boxes will block switching the parent to DONE.
2282 When this is nil, checkboxes have no influence on switching TODO states.
2283 When non-nil, you first need to check off all check boxes before the TODO
2284 entry can be switched to DONE.
2285 This variable needs to be set before org.el is loaded, and you need to
2286 restart Emacs after a change to make the change effective. The only way
2287 to change is while Emacs is running is through the customize interface."
2288 :set (lambda (var val)
2289 (set var val)
2290 (if val
2291 (add-hook 'org-blocker-hook
2292 'org-block-todo-from-checkboxes)
2293 (remove-hook 'org-blocker-hook
2294 'org-block-todo-from-checkboxes)))
2295 :group 'org-todo
2296 :type 'boolean)
2298 (defcustom org-treat-insert-todo-heading-as-state-change nil
2299 "Non-nil means inserting a TODO heading is treated as state change.
2300 So when the command \\[org-insert-todo-heading] is used, state change
2301 logging will apply if appropriate. When nil, the new TODO item will
2302 be inserted directly, and no logging will take place."
2303 :group 'org-todo
2304 :type 'boolean)
2306 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2307 "Non-nil means switching TODO states with S-cursor counts as state change.
2308 This is the default behavior. However, setting this to nil allows a
2309 convenient way to select a TODO state and bypass any logging associated
2310 with that."
2311 :group 'org-todo
2312 :type 'boolean)
2314 (defcustom org-todo-state-tags-triggers nil
2315 "Tag changes that should be triggered by TODO state changes.
2316 This is a list. Each entry is
2318 (state-change (tag . flag) .......)
2320 State-change can be a string with a state, and empty string to indicate the
2321 state that has no TODO keyword, or it can be one of the symbols `todo'
2322 or `done', meaning any not-done or done state, respectively."
2323 :group 'org-todo
2324 :group 'org-tags
2325 :type '(repeat
2326 (cons (choice :tag "When changing to"
2327 (const :tag "Not-done state" todo)
2328 (const :tag "Done state" done)
2329 (string :tag "State"))
2330 (repeat
2331 (cons :tag "Tag action"
2332 (string :tag "Tag")
2333 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2335 (defcustom org-log-done nil
2336 "Information to record when a task moves to the DONE state.
2338 Possible values are:
2340 nil Don't add anything, just change the keyword
2341 time Add a time stamp to the task
2342 note Prompt for a note and add it with template `org-log-note-headings'
2344 This option can also be set with on a per-file-basis with
2346 #+STARTUP: nologdone
2347 #+STARTUP: logdone
2348 #+STARTUP: lognotedone
2350 You can have local logging settings for a subtree by setting the LOGGING
2351 property to one or more of these keywords."
2352 :group 'org-todo
2353 :group 'org-progress
2354 :type '(choice
2355 (const :tag "No logging" nil)
2356 (const :tag "Record CLOSED timestamp" time)
2357 (const :tag "Record CLOSED timestamp with note." note)))
2359 ;; Normalize old uses of org-log-done.
2360 (cond
2361 ((eq org-log-done t) (setq org-log-done 'time))
2362 ((and (listp org-log-done) (memq 'done org-log-done))
2363 (setq org-log-done 'note)))
2365 (defcustom org-log-reschedule nil
2366 "Information to record when the scheduling date of a tasks is modified.
2368 Possible values are:
2370 nil Don't add anything, just change the date
2371 time Add a time stamp to the task
2372 note Prompt for a note and add it with template `org-log-note-headings'
2374 This option can also be set with on a per-file-basis with
2376 #+STARTUP: nologreschedule
2377 #+STARTUP: logreschedule
2378 #+STARTUP: lognotereschedule"
2379 :group 'org-todo
2380 :group 'org-progress
2381 :type '(choice
2382 (const :tag "No logging" nil)
2383 (const :tag "Record timestamp" time)
2384 (const :tag "Record timestamp with note." note)))
2386 (defcustom org-log-redeadline nil
2387 "Information to record when the deadline date of a tasks is modified.
2389 Possible values are:
2391 nil Don't add anything, just change the date
2392 time Add a time stamp to the task
2393 note Prompt for a note and add it with template `org-log-note-headings'
2395 This option can also be set with on a per-file-basis with
2397 #+STARTUP: nologredeadline
2398 #+STARTUP: logredeadline
2399 #+STARTUP: lognoteredeadline
2401 You can have local logging settings for a subtree by setting the LOGGING
2402 property to one or more of these keywords."
2403 :group 'org-todo
2404 :group 'org-progress
2405 :type '(choice
2406 (const :tag "No logging" nil)
2407 (const :tag "Record timestamp" time)
2408 (const :tag "Record timestamp with note." note)))
2410 (defcustom org-log-note-clock-out nil
2411 "Non-nil means record a note when clocking out of an item.
2412 This can also be configured on a per-file basis by adding one of
2413 the following lines anywhere in the buffer:
2415 #+STARTUP: lognoteclock-out
2416 #+STARTUP: nolognoteclock-out"
2417 :group 'org-todo
2418 :group 'org-progress
2419 :type 'boolean)
2421 (defcustom org-log-done-with-time t
2422 "Non-nil means the CLOSED time stamp will contain date and time.
2423 When nil, only the date will be recorded."
2424 :group 'org-progress
2425 :type 'boolean)
2427 (defcustom org-log-note-headings
2428 '((done . "CLOSING NOTE %t")
2429 (state . "State %-12s from %-12S %t")
2430 (note . "Note taken on %t")
2431 (reschedule . "Rescheduled from %S on %t")
2432 (delschedule . "Not scheduled, was %S on %t")
2433 (redeadline . "New deadline from %S on %t")
2434 (deldeadline . "Removed deadline, was %S on %t")
2435 (refile . "Refiled on %t")
2436 (clock-out . ""))
2437 "Headings for notes added to entries.
2438 The value is an alist, with the car being a symbol indicating the note
2439 context, and the cdr is the heading to be used. The heading may also be the
2440 empty string.
2441 %t in the heading will be replaced by a time stamp.
2442 %T will be an active time stamp instead the default inactive one
2443 %d will be replaced by a short-format time stamp.
2444 %D will be replaced by an active short-format time stamp.
2445 %s will be replaced by the new TODO state, in double quotes.
2446 %S will be replaced by the old TODO state, in double quotes.
2447 %u will be replaced by the user name.
2448 %U will be replaced by the full user name.
2450 In fact, it is not a good idea to change the `state' entry, because
2451 agenda log mode depends on the format of these entries."
2452 :group 'org-todo
2453 :group 'org-progress
2454 :type '(list :greedy t
2455 (cons (const :tag "Heading when closing an item" done) string)
2456 (cons (const :tag
2457 "Heading when changing todo state (todo sequence only)"
2458 state) string)
2459 (cons (const :tag "Heading when just taking a note" note) string)
2460 (cons (const :tag "Heading when clocking out" clock-out) string)
2461 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2462 (cons (const :tag "Heading when rescheduling" reschedule) string)
2463 (cons (const :tag "Heading when changing deadline" redeadline) string)
2464 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2465 (cons (const :tag "Heading when refiling" refile) string)))
2467 (unless (assq 'note org-log-note-headings)
2468 (push '(note . "%t") org-log-note-headings))
2470 (defcustom org-log-into-drawer nil
2471 "Non-nil means insert state change notes and time stamps into a drawer.
2472 When nil, state changes notes will be inserted after the headline and
2473 any scheduling and clock lines, but not inside a drawer.
2475 The value of this variable should be the name of the drawer to use.
2476 LOGBOOK is proposed as the default drawer for this purpose, you can
2477 also set this to a string to define the drawer of your choice.
2479 A value of t is also allowed, representing \"LOGBOOK\".
2481 If this variable is set, `org-log-state-notes-insert-after-drawers'
2482 will be ignored.
2484 You can set the property LOG_INTO_DRAWER to overrule this setting for
2485 a subtree."
2486 :group 'org-todo
2487 :group 'org-progress
2488 :type '(choice
2489 (const :tag "Not into a drawer" nil)
2490 (const :tag "LOGBOOK" t)
2491 (string :tag "Other")))
2493 (if (fboundp 'defvaralias)
2494 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2496 (defun org-log-into-drawer ()
2497 "Return the value of `org-log-into-drawer', but let properties overrule.
2498 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2499 used instead of the default value."
2500 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2501 (cond
2502 ((or (not p) (equal p "nil")) org-log-into-drawer)
2503 ((equal p "t") "LOGBOOK")
2504 (t p))))
2506 (defcustom org-log-state-notes-insert-after-drawers nil
2507 "Non-nil means insert state change notes after any drawers in entry.
2508 Only the drawers that *immediately* follow the headline and the
2509 deadline/scheduled line are skipped.
2510 When nil, insert notes right after the heading and perhaps the line
2511 with deadline/scheduling if present.
2513 This variable will have no effect if `org-log-into-drawer' is
2514 set."
2515 :group 'org-todo
2516 :group 'org-progress
2517 :type 'boolean)
2519 (defcustom org-log-states-order-reversed t
2520 "Non-nil means the latest state note will be directly after heading.
2521 When nil, the state change notes will be ordered according to time."
2522 :group 'org-todo
2523 :group 'org-progress
2524 :type 'boolean)
2526 (defcustom org-todo-repeat-to-state nil
2527 "The TODO state to which a repeater should return the repeating task.
2528 By default this is the first task in a TODO sequence, or the previous state
2529 in a TODO_TYP set. But you can specify another task here.
2530 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2531 :group 'org-todo
2532 :version "24.1"
2533 :type '(choice (const :tag "Head of sequence" nil)
2534 (string :tag "Specific state")))
2536 (defcustom org-log-repeat 'time
2537 "Non-nil means record moving through the DONE state when triggering repeat.
2538 An auto-repeating task is immediately switched back to TODO when
2539 marked DONE. If you are not logging state changes (by adding \"@\"
2540 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2541 record a closing note, there will be no record of the task moving
2542 through DONE. This variable forces taking a note anyway.
2544 nil Don't force a record
2545 time Record a time stamp
2546 note Record a note
2548 This option can also be set with on a per-file-basis with
2550 #+STARTUP: logrepeat
2551 #+STARTUP: lognoterepeat
2552 #+STARTUP: nologrepeat
2554 You can have local logging settings for a subtree by setting the LOGGING
2555 property to one or more of these keywords."
2556 :group 'org-todo
2557 :group 'org-progress
2558 :type '(choice
2559 (const :tag "Don't force a record" nil)
2560 (const :tag "Force recording the DONE state" time)
2561 (const :tag "Force recording a note with the DONE state" note)))
2564 (defgroup org-priorities nil
2565 "Priorities in Org-mode."
2566 :tag "Org Priorities"
2567 :group 'org-todo)
2569 (defcustom org-enable-priority-commands t
2570 "Non-nil means priority commands are active.
2571 When nil, these commands will be disabled, so that you never accidentally
2572 set a priority."
2573 :group 'org-priorities
2574 :type 'boolean)
2576 (defcustom org-highest-priority ?A
2577 "The highest priority of TODO items. A character like ?A, ?B etc.
2578 Must have a smaller ASCII number than `org-lowest-priority'."
2579 :group 'org-priorities
2580 :type 'character)
2582 (defcustom org-lowest-priority ?C
2583 "The lowest priority of TODO items. A character like ?A, ?B etc.
2584 Must have a larger ASCII number than `org-highest-priority'."
2585 :group 'org-priorities
2586 :type 'character)
2588 (defcustom org-default-priority ?B
2589 "The default priority of TODO items.
2590 This is the priority an item gets if no explicit priority is given.
2591 When starting to cycle on an empty priority the first step in the cycle
2592 depends on `org-priority-start-cycle-with-default'. The resulting first
2593 step priority must not exceed the range from `org-highest-priority' to
2594 `org-lowest-priority' which means that `org-default-priority' has to be
2595 in this range exclusive or inclusive the range boundaries. Else the
2596 first step refuses to set the default and the second will fall back
2597 to (depending on the command used) the highest or lowest priority."
2598 :group 'org-priorities
2599 :type 'character)
2601 (defcustom org-priority-start-cycle-with-default t
2602 "Non-nil means start with default priority when starting to cycle.
2603 When this is nil, the first step in the cycle will be (depending on the
2604 command used) one higher or lower than the default priority.
2605 See also `org-default-priority'."
2606 :group 'org-priorities
2607 :type 'boolean)
2609 (defcustom org-get-priority-function nil
2610 "Function to extract the priority from a string.
2611 The string is normally the headline. If this is nil Org computes the
2612 priority from the priority cookie like [#A] in the headline. It returns
2613 an integer, increasing by 1000 for each priority level.
2614 The user can set a different function here, which should take a string
2615 as an argument and return the numeric priority."
2616 :group 'org-priorities
2617 :version "24.1"
2618 :type 'function)
2620 (defgroup org-time nil
2621 "Options concerning time stamps and deadlines in Org-mode."
2622 :tag "Org Time"
2623 :group 'org)
2625 (defcustom org-insert-labeled-timestamps-at-point nil
2626 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2627 When nil, these labeled time stamps are forces into the second line of an
2628 entry, just after the headline. When scheduling from the global TODO list,
2629 the time stamp will always be forced into the second line."
2630 :group 'org-time
2631 :type 'boolean)
2633 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2634 "Formats for `format-time-string' which are used for time stamps.
2635 It is not recommended to change this constant.")
2637 (defcustom org-time-stamp-rounding-minutes '(0 5)
2638 "Number of minutes to round time stamps to.
2639 These are two values, the first applies when first creating a time stamp.
2640 The second applies when changing it with the commands `S-up' and `S-down'.
2641 When changing the time stamp, this means that it will change in steps
2642 of N minutes, as given by the second value.
2644 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2645 numbers should be factors of 60, so for example 5, 10, 15.
2647 When this is larger than 1, you can still force an exact time stamp by using
2648 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2649 and by using a prefix arg to `S-up/down' to specify the exact number
2650 of minutes to shift."
2651 :group 'org-time
2652 :get #'(lambda (var) ; Make sure both elements are there
2653 (if (integerp (default-value var))
2654 (list (default-value var) 5)
2655 (default-value var)))
2656 :type '(list
2657 (integer :tag "when inserting times")
2658 (integer :tag "when modifying times")))
2660 ;; Normalize old customizations of this variable.
2661 (when (integerp org-time-stamp-rounding-minutes)
2662 (setq org-time-stamp-rounding-minutes
2663 (list org-time-stamp-rounding-minutes
2664 org-time-stamp-rounding-minutes)))
2666 (defcustom org-display-custom-times nil
2667 "Non-nil means overlay custom formats over all time stamps.
2668 The formats are defined through the variable `org-time-stamp-custom-formats'.
2669 To turn this on on a per-file basis, insert anywhere in the file:
2670 #+STARTUP: customtime"
2671 :group 'org-time
2672 :set 'set-default
2673 :type 'sexp)
2674 (make-variable-buffer-local 'org-display-custom-times)
2676 (defcustom org-time-stamp-custom-formats
2677 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2678 "Custom formats for time stamps. See `format-time-string' for the syntax.
2679 These are overlaid over the default ISO format if the variable
2680 `org-display-custom-times' is set. Time like %H:%M should be at the
2681 end of the second format. The custom formats are also honored by export
2682 commands, if custom time display is turned on at the time of export."
2683 :group 'org-time
2684 :type 'sexp)
2686 (defun org-time-stamp-format (&optional long inactive)
2687 "Get the right format for a time string."
2688 (let ((f (if long (cdr org-time-stamp-formats)
2689 (car org-time-stamp-formats))))
2690 (if inactive
2691 (concat "[" (substring f 1 -1) "]")
2692 f)))
2694 (defcustom org-time-clocksum-format "%d:%02d"
2695 "The format string used when creating CLOCKSUM lines.
2696 This is also used when org-mode generates a time duration."
2697 :group 'org-time
2698 :type 'string)
2700 (defcustom org-time-clocksum-use-fractional nil
2701 "If non-nil, \\[org-clock-display] uses fractional times.
2702 org-mode generates a time duration."
2703 :group 'org-time
2704 :type 'boolean)
2706 (defcustom org-time-clocksum-fractional-format "%.2f"
2707 "The format string used when creating CLOCKSUM lines, or when
2708 org-mode generates a time duration."
2709 :group 'org-time
2710 :type 'string)
2712 (defcustom org-deadline-warning-days 14
2713 "No. of days before expiration during which a deadline becomes active.
2714 This variable governs the display in sparse trees and in the agenda.
2715 When 0 or negative, it means use this number (the absolute value of it)
2716 even if a deadline has a different individual lead time specified.
2718 Custom commands can set this variable in the options section."
2719 :group 'org-time
2720 :group 'org-agenda-daily/weekly
2721 :type 'integer)
2723 (defcustom org-read-date-prefer-future t
2724 "Non-nil means assume future for incomplete date input from user.
2725 This affects the following situations:
2726 1. The user gives a month but not a year.
2727 For example, if it is April and you enter \"feb 2\", this will be read
2728 as Feb 2, *next* year. \"May 5\", however, will be this year.
2729 2. The user gives a day, but no month.
2730 For example, if today is the 15th, and you enter \"3\", Org-mode will
2731 read this as the third of *next* month. However, if you enter \"17\",
2732 it will be considered as *this* month.
2734 If you set this variable to the symbol `time', then also the following
2735 will work:
2737 3. If the user gives a time, but no day. If the time is before now,
2738 to will be interpreted as tomorrow.
2740 Currently none of this works for ISO week specifications.
2742 When this option is nil, the current day, month and year will always be
2743 used as defaults.
2745 See also `org-agenda-jump-prefer-future'."
2746 :group 'org-time
2747 :type '(choice
2748 (const :tag "Never" nil)
2749 (const :tag "Check month and day" t)
2750 (const :tag "Check month, day, and time" time)))
2752 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2753 "Should the agenda jump command prefer the future for incomplete dates?
2754 The default is to do the same as configured in `org-read-date-prefer-future'.
2755 But you can also set a deviating value here.
2756 This may t or nil, or the symbol `org-read-date-prefer-future'."
2757 :group 'org-agenda
2758 :group 'org-time
2759 :version "24.1"
2760 :type '(choice
2761 (const :tag "Use org-read-date-prefer-future"
2762 org-read-date-prefer-future)
2763 (const :tag "Never" nil)
2764 (const :tag "Always" t)))
2766 (defcustom org-read-date-force-compatible-dates t
2767 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2769 Depending on the system Emacs is running on, certain dates cannot
2770 be represented with the type used internally to represent time.
2771 Dates between 1970-1-1 and 2038-1-1 can always be represented
2772 correctly. Some systems allow for earlier dates, some for later,
2773 some for both. One way to find out it to insert any date into an
2774 Org buffer, putting the cursor on the year and hitting S-up and
2775 S-down to test the range.
2777 When this variable is set to t, the date/time prompt will not let
2778 you specify dates outside the 1970-2037 range, so it is certain that
2779 these dates will work in whatever version of Emacs you are
2780 running, and also that you can move a file from one Emacs implementation
2781 to another. WHenever Org is forcing the year for you, it will display
2782 a message and beep.
2784 When this variable is nil, Org will check if the date is
2785 representable in the specific Emacs implementation you are using.
2786 If not, it will force a year, usually the current year, and beep
2787 to remind you. Currently this setting is not recommended because
2788 the likelihood that you will open your Org files in an Emacs that
2789 has limited date range is not negligible.
2791 A workaround for this problem is to use diary sexp dates for time
2792 stamps outside of this range."
2793 :group 'org-time
2794 :version "24.1"
2795 :type 'boolean)
2797 (defcustom org-read-date-display-live t
2798 "Non-nil means display current interpretation of date prompt live.
2799 This display will be in an overlay, in the minibuffer."
2800 :group 'org-time
2801 :type 'boolean)
2803 (defcustom org-read-date-popup-calendar t
2804 "Non-nil means pop up a calendar when prompting for a date.
2805 In the calendar, the date can be selected with mouse-1. However, the
2806 minibuffer will also be active, and you can simply enter the date as well.
2807 When nil, only the minibuffer will be available."
2808 :group 'org-time
2809 :type 'boolean)
2810 (if (fboundp 'defvaralias)
2811 (defvaralias 'org-popup-calendar-for-date-prompt
2812 'org-read-date-popup-calendar))
2814 (defcustom org-read-date-minibuffer-setup-hook nil
2815 "Hook to be used to set up keys for the date/time interface.
2816 Add key definitions to `minibuffer-local-map', which will be a temporary
2817 copy."
2818 :group 'org-time
2819 :type 'hook)
2821 (defcustom org-extend-today-until 0
2822 "The hour when your day really ends. Must be an integer.
2823 This has influence for the following applications:
2824 - When switching the agenda to \"today\". It it is still earlier than
2825 the time given here, the day recognized as TODAY is actually yesterday.
2826 - When a date is read from the user and it is still before the time given
2827 here, the current date and time will be assumed to be yesterday, 23:59.
2828 Also, timestamps inserted in remember templates follow this rule.
2830 IMPORTANT: This is a feature whose implementation is and likely will
2831 remain incomplete. Really, it is only here because past midnight seems to
2832 be the favorite working time of John Wiegley :-)"
2833 :group 'org-time
2834 :type 'integer)
2836 (defcustom org-use-effective-time nil
2837 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2838 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2839 \"effective time\" of any timestamps between midnight and 8am will be
2840 23:59 of the previous day."
2841 :group 'org-time
2842 :version "24.1"
2843 :type 'boolean)
2845 (defcustom org-edit-timestamp-down-means-later nil
2846 "Non-nil means S-down will increase the time in a time stamp.
2847 When nil, S-up will increase."
2848 :group 'org-time
2849 :type 'boolean)
2851 (defcustom org-calendar-follow-timestamp-change t
2852 "Non-nil means make the calendar window follow timestamp changes.
2853 When a timestamp is modified and the calendar window is visible, it will be
2854 moved to the new date."
2855 :group 'org-time
2856 :type 'boolean)
2858 (defgroup org-tags nil
2859 "Options concerning tags in Org-mode."
2860 :tag "Org Tags"
2861 :group 'org)
2863 (defcustom org-tag-alist nil
2864 "List of tags allowed in Org-mode files.
2865 When this list is nil, Org-mode will base TAG input on what is already in the
2866 buffer.
2867 The value of this variable is an alist, the car of each entry must be a
2868 keyword as a string, the cdr may be a character that is used to select
2869 that tag through the fast-tag-selection interface.
2870 See the manual for details."
2871 :group 'org-tags
2872 :type '(repeat
2873 (choice
2874 (cons (string :tag "Tag name")
2875 (character :tag "Access char"))
2876 (list :tag "Start radio group"
2877 (const :startgroup)
2878 (option (string :tag "Group description")))
2879 (list :tag "End radio group"
2880 (const :endgroup)
2881 (option (string :tag "Group description")))
2882 (const :tag "New line" (:newline)))))
2884 (defcustom org-tag-persistent-alist nil
2885 "List of tags that will always appear in all Org-mode files.
2886 This is in addition to any in buffer settings or customizations
2887 of `org-tag-alist'.
2888 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2889 The value of this variable is an alist, the car of each entry must be a
2890 keyword as a string, the cdr may be a character that is used to select
2891 that tag through the fast-tag-selection interface.
2892 See the manual for details.
2893 To disable these tags on a per-file basis, insert anywhere in the file:
2894 #+STARTUP: noptag"
2895 :group 'org-tags
2896 :type '(repeat
2897 (choice
2898 (cons (string :tag "Tag name")
2899 (character :tag "Access char"))
2900 (const :tag "Start radio group" (:startgroup))
2901 (const :tag "End radio group" (:endgroup))
2902 (const :tag "New line" (:newline)))))
2904 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2905 "If non-nil, always offer completion for all tags of all agenda files.
2906 Instead of customizing this variable directly, you might want to
2907 set it locally for capture buffers, because there no list of
2908 tags in that file can be created dynamically (there are none).
2910 (add-hook 'org-capture-mode-hook
2911 (lambda ()
2912 (set (make-local-variable
2913 'org-complete-tags-always-offer-all-agenda-tags)
2914 t)))"
2915 :group 'org-tags
2916 :version "24.1"
2917 :type 'boolean)
2919 (defvar org-file-tags nil
2920 "List of tags that can be inherited by all entries in the file.
2921 The tags will be inherited if the variable `org-use-tag-inheritance'
2922 says they should be.
2923 This variable is populated from #+FILETAGS lines.")
2925 (defcustom org-use-fast-tag-selection 'auto
2926 "Non-nil means use fast tag selection scheme.
2927 This is a special interface to select and deselect tags with single keys.
2928 When nil, fast selection is never used.
2929 When the symbol `auto', fast selection is used if and only if selection
2930 characters for tags have been configured, either through the variable
2931 `org-tag-alist' or through a #+TAGS line in the buffer.
2932 When t, fast selection is always used and selection keys are assigned
2933 automatically if necessary."
2934 :group 'org-tags
2935 :type '(choice
2936 (const :tag "Always" t)
2937 (const :tag "Never" nil)
2938 (const :tag "When selection characters are configured" 'auto)))
2940 (defcustom org-fast-tag-selection-single-key nil
2941 "Non-nil means fast tag selection exits after first change.
2942 When nil, you have to press RET to exit it.
2943 During fast tag selection, you can toggle this flag with `C-c'.
2944 This variable can also have the value `expert'. In this case, the window
2945 displaying the tags menu is not even shown, until you press C-c again."
2946 :group 'org-tags
2947 :type '(choice
2948 (const :tag "No" nil)
2949 (const :tag "Yes" t)
2950 (const :tag "Expert" expert)))
2952 (defvar org-fast-tag-selection-include-todo nil
2953 "Non-nil means fast tags selection interface will also offer TODO states.
2954 This is an undocumented feature, you should not rely on it.")
2956 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2957 "The column to which tags should be indented in a headline.
2958 If this number is positive, it specifies the column. If it is negative,
2959 it means that the tags should be flushright to that column. For example,
2960 -80 works well for a normal 80 character screen.
2961 When 0, place tags directly after headline text, with only one space in
2962 between."
2963 :group 'org-tags
2964 :type 'integer)
2966 (defcustom org-auto-align-tags t
2967 "Non-nil keeps tags aligned when modifying headlines.
2968 Some operations (i.e. demoting) change the length of a headline and
2969 therefore shift the tags around. With this option turned on, after
2970 each such operation the tags are again aligned to `org-tags-column'."
2971 :group 'org-tags
2972 :type 'boolean)
2974 (defcustom org-use-tag-inheritance t
2975 "Non-nil means tags in levels apply also for sublevels.
2976 When nil, only the tags directly given in a specific line apply there.
2977 This may also be a list of tags that should be inherited, or a regexp that
2978 matches tags that should be inherited. Additional control is possible
2979 with the variable `org-tags-exclude-from-inheritance' which gives an
2980 explicit list of tags to be excluded from inheritance., even if the value of
2981 `org-use-tag-inheritance' would select it for inheritance.
2983 If this option is t, a match early-on in a tree can lead to a large
2984 number of matches in the subtree when constructing the agenda or creating
2985 a sparse tree. If you only want to see the first match in a tree during
2986 a search, check out the variable `org-tags-match-list-sublevels'."
2987 :group 'org-tags
2988 :type '(choice
2989 (const :tag "Not" nil)
2990 (const :tag "Always" t)
2991 (repeat :tag "Specific tags" (string :tag "Tag"))
2992 (regexp :tag "Tags matched by regexp")))
2994 (defcustom org-tags-exclude-from-inheritance nil
2995 "List of tags that should never be inherited.
2996 This is a way to exclude a few tags from inheritance. For way to do
2997 the opposite, to actively allow inheritance for selected tags,
2998 see the variable `org-use-tag-inheritance'."
2999 :group 'org-tags
3000 :type '(repeat (string :tag "Tag")))
3002 (defun org-tag-inherit-p (tag)
3003 "Check if TAG is one that should be inherited."
3004 (cond
3005 ((member tag org-tags-exclude-from-inheritance) nil)
3006 ((eq org-use-tag-inheritance t) t)
3007 ((not org-use-tag-inheritance) nil)
3008 ((stringp org-use-tag-inheritance)
3009 (string-match org-use-tag-inheritance tag))
3010 ((listp org-use-tag-inheritance)
3011 (member tag org-use-tag-inheritance))
3012 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3014 (defcustom org-tags-match-list-sublevels t
3015 "Non-nil means list also sublevels of headlines matching a search.
3016 This variable applies to tags/property searches, and also to stuck
3017 projects because this search is based on a tags match as well.
3019 When set to the symbol `indented', sublevels are indented with
3020 leading dots.
3022 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3023 the sublevels of a headline matching a tag search often also match
3024 the same search. Listing all of them can create very long lists.
3025 Setting this variable to nil causes subtrees of a match to be skipped.
3027 This variable is semi-obsolete and probably should always be true. It
3028 is better to limit inheritance to certain tags using the variables
3029 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3030 :group 'org-tags
3031 :type '(choice
3032 (const :tag "No, don't list them" nil)
3033 (const :tag "Yes, do list them" t)
3034 (const :tag "List them, indented with leading dots" indented)))
3036 (defcustom org-tags-sort-function nil
3037 "When set, tags are sorted using this function as a comparator."
3038 :group 'org-tags
3039 :type '(choice
3040 (const :tag "No sorting" nil)
3041 (const :tag "Alphabetical" string<)
3042 (const :tag "Reverse alphabetical" string>)
3043 (function :tag "Custom function" nil)))
3045 (defvar org-tags-history nil
3046 "History of minibuffer reads for tags.")
3047 (defvar org-last-tags-completion-table nil
3048 "The last used completion table for tags.")
3049 (defvar org-after-tags-change-hook nil
3050 "Hook that is run after the tags in a line have changed.")
3052 (defgroup org-properties nil
3053 "Options concerning properties in Org-mode."
3054 :tag "Org Properties"
3055 :group 'org)
3057 (defcustom org-property-format "%-10s %s"
3058 "How property key/value pairs should be formatted by `indent-line'.
3059 When `indent-line' hits a property definition, it will format the line
3060 according to this format, mainly to make sure that the values are
3061 lined-up with respect to each other."
3062 :group 'org-properties
3063 :type 'string)
3065 (defcustom org-properties-postprocess-alist nil
3066 "Alist of properties and functions to adjust inserted values.
3067 Elements of this alist must be of the form
3069 ([string] [function])
3071 where [string] must be a property name and [function] must be a
3072 lambda expression: this lambda expression must take one argument,
3073 the value to adjust, and return the new value as a string.
3075 For example, this element will allow the property \"Remaining\"
3076 to be updated wrt the relation between the \"Effort\" property
3077 and the clock summary:
3079 ((\"Remaining\" (lambda(value)
3080 (let ((clocksum (org-clock-sum-current-item))
3081 (effort (org-duration-string-to-minutes
3082 (org-entry-get (point) \"Effort\"))))
3083 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3084 :group 'org-properties
3085 :version "24.1"
3086 :type '(alist :key-type (string :tag "Property")
3087 :value-type (function :tag "Function")))
3089 (defcustom org-use-property-inheritance nil
3090 "Non-nil means properties apply also for sublevels.
3092 This setting is chiefly used during property searches. Turning it on can
3093 cause significant overhead when doing a search, which is why it is not
3094 on by default.
3096 When nil, only the properties directly given in the current entry count.
3097 When t, every property is inherited. The value may also be a list of
3098 properties that should have inheritance, or a regular expression matching
3099 properties that should be inherited.
3101 However, note that some special properties use inheritance under special
3102 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3103 and the properties ending in \"_ALL\" when they are used as descriptor
3104 for valid values of a property.
3106 Note for programmers:
3107 When querying an entry with `org-entry-get', you can control if inheritance
3108 should be used. By default, `org-entry-get' looks only at the local
3109 properties. You can request inheritance by setting the inherit argument
3110 to t (to force inheritance) or to `selective' (to respect the setting
3111 in this variable)."
3112 :group 'org-properties
3113 :type '(choice
3114 (const :tag "Not" nil)
3115 (const :tag "Always" t)
3116 (repeat :tag "Specific properties" (string :tag "Property"))
3117 (regexp :tag "Properties matched by regexp")))
3119 (defun org-property-inherit-p (property)
3120 "Check if PROPERTY is one that should be inherited."
3121 (cond
3122 ((eq org-use-property-inheritance t) t)
3123 ((not org-use-property-inheritance) nil)
3124 ((stringp org-use-property-inheritance)
3125 (string-match org-use-property-inheritance property))
3126 ((listp org-use-property-inheritance)
3127 (member property org-use-property-inheritance))
3128 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3130 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3131 "The default column format, if no other format has been defined.
3132 This variable can be set on the per-file basis by inserting a line
3134 #+COLUMNS: %25ITEM ....."
3135 :group 'org-properties
3136 :type 'string)
3138 (defcustom org-columns-ellipses ".."
3139 "The ellipses to be used when a field in column view is truncated.
3140 When this is the empty string, as many characters as possible are shown,
3141 but then there will be no visual indication that the field has been truncated.
3142 When this is a string of length N, the last N characters of a truncated
3143 field are replaced by this string. If the column is narrower than the
3144 ellipses string, only part of the ellipses string will be shown."
3145 :group 'org-properties
3146 :type 'string)
3148 (defcustom org-columns-modify-value-for-display-function nil
3149 "Function that modifies values for display in column view.
3150 For example, it can be used to cut out a certain part from a time stamp.
3151 The function must take 2 arguments:
3153 column-title The title of the column (*not* the property name)
3154 value The value that should be modified.
3156 The function should return the value that should be displayed,
3157 or nil if the normal value should be used."
3158 :group 'org-properties
3159 :type 'function)
3161 (defcustom org-effort-property "Effort"
3162 "The property that is being used to keep track of effort estimates.
3163 Effort estimates given in this property need to have the format H:MM."
3164 :group 'org-properties
3165 :group 'org-progress
3166 :type '(string :tag "Property"))
3168 (defconst org-global-properties-fixed
3169 '(("VISIBILITY_ALL" . "folded children content all")
3170 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3171 "List of property/value pairs that can be inherited by any entry.
3173 These are fixed values, for the preset properties. The user variable
3174 that can be used to add to this list is `org-global-properties'.
3176 The entries in this list are cons cells where the car is a property
3177 name and cdr is a string with the value. If the value represents
3178 multiple items like an \"_ALL\" property, separate the items by
3179 spaces.")
3181 (defcustom org-global-properties nil
3182 "List of property/value pairs that can be inherited by any entry.
3184 This list will be combined with the constant `org-global-properties-fixed'.
3186 The entries in this list are cons cells where the car is a property
3187 name and cdr is a string with the value.
3189 You can set buffer-local values for the same purpose in the variable
3190 `org-file-properties' this by adding lines like
3192 #+PROPERTY: NAME VALUE"
3193 :group 'org-properties
3194 :type '(repeat
3195 (cons (string :tag "Property")
3196 (string :tag "Value"))))
3198 (defvar org-file-properties nil
3199 "List of property/value pairs that can be inherited by any entry.
3200 Valid for the current buffer.
3201 This variable is populated from #+PROPERTY lines.")
3202 (make-variable-buffer-local 'org-file-properties)
3204 (defgroup org-agenda nil
3205 "Options concerning agenda views in Org-mode."
3206 :tag "Org Agenda"
3207 :group 'org)
3209 (defvar org-category nil
3210 "Variable used by org files to set a category for agenda display.
3211 Such files should use a file variable to set it, for example
3213 # -*- mode: org; org-category: \"ELisp\"
3215 or contain a special line
3217 #+CATEGORY: ELisp
3219 If the file does not specify a category, then file's base name
3220 is used instead.")
3221 (make-variable-buffer-local 'org-category)
3222 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3224 (defcustom org-agenda-files nil
3225 "The files to be used for agenda display.
3226 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3227 \\[org-remove-file]. You can also use customize to edit the list.
3229 If an entry is a directory, all files in that directory that are matched by
3230 `org-agenda-file-regexp' will be part of the file list.
3232 If the value of the variable is not a list but a single file name, then
3233 the list of agenda files is actually stored and maintained in that file, one
3234 agenda file per line. In this file paths can be given relative to
3235 `org-directory'. Tilde expansion and environment variable substitution
3236 are also made."
3237 :group 'org-agenda
3238 :type '(choice
3239 (repeat :tag "List of files and directories" file)
3240 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3242 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3243 "Regular expression to match files for `org-agenda-files'.
3244 If any element in the list in that variable contains a directory instead
3245 of a normal file, all files in that directory that are matched by this
3246 regular expression will be included."
3247 :group 'org-agenda
3248 :type 'regexp)
3250 (defcustom org-agenda-text-search-extra-files nil
3251 "List of extra files to be searched by text search commands.
3252 These files will be search in addition to the agenda files by the
3253 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3254 Note that these files will only be searched for text search commands,
3255 not for the other agenda views like todo lists, tag searches or the weekly
3256 agenda. This variable is intended to list notes and possibly archive files
3257 that should also be searched by these two commands.
3258 In fact, if the first element in the list is the symbol `agenda-archives',
3259 than all archive files of all agenda files will be added to the search
3260 scope."
3261 :group 'org-agenda
3262 :type '(set :greedy t
3263 (const :tag "Agenda Archives" agenda-archives)
3264 (repeat :inline t (file))))
3266 (if (fboundp 'defvaralias)
3267 (defvaralias 'org-agenda-multi-occur-extra-files
3268 'org-agenda-text-search-extra-files))
3270 (defcustom org-agenda-skip-unavailable-files nil
3271 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3272 A nil value means to remove them, after a query, from the list."
3273 :group 'org-agenda
3274 :type 'boolean)
3276 (defcustom org-calendar-to-agenda-key [?c]
3277 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3278 The command `org-calendar-goto-agenda' will be bound to this key. The
3279 default is the character `c' because then `c' can be used to switch back and
3280 forth between agenda and calendar."
3281 :group 'org-agenda
3282 :type 'sexp)
3284 (defcustom org-calendar-agenda-action-key [?k]
3285 "The key to be installed in `calendar-mode-map' for agenda-action.
3286 The command `org-agenda-action' will be bound to this key. The
3287 default is the character `k' because we use the same key in the agenda."
3288 :group 'org-agenda
3289 :type 'sexp)
3291 (defcustom org-calendar-insert-diary-entry-key [?i]
3292 "The key to be installed in `calendar-mode-map' for adding diary entries.
3293 This option is irrelevant until `org-agenda-diary-file' has been configured
3294 to point to an Org-mode file. When that is the case, the command
3295 `org-agenda-diary-entry' will be bound to the key given here, by default
3296 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3297 if you want to continue doing this, you need to change this to a different
3298 key."
3299 :group 'org-agenda
3300 :type 'sexp)
3302 (defcustom org-agenda-diary-file 'diary-file
3303 "File to which to add new entries with the `i' key in agenda and calendar.
3304 When this is the symbol `diary-file', the functionality in the Emacs
3305 calendar will be used to add entries to the `diary-file'. But when this
3306 points to a file, `org-agenda-diary-entry' will be used instead."
3307 :group 'org-agenda
3308 :type '(choice
3309 (const :tag "The standard Emacs diary file" diary-file)
3310 (file :tag "Special Org file diary entries")))
3312 (eval-after-load "calendar"
3313 '(progn
3314 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3315 'org-calendar-goto-agenda)
3316 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3317 'org-agenda-action)
3318 (add-hook 'calendar-mode-hook
3319 (lambda ()
3320 (unless (eq org-agenda-diary-file 'diary-file)
3321 (define-key calendar-mode-map
3322 org-calendar-insert-diary-entry-key
3323 'org-agenda-diary-entry))))))
3325 (defgroup org-latex nil
3326 "Options for embedding LaTeX code into Org-mode."
3327 :tag "Org LaTeX"
3328 :group 'org)
3330 (defcustom org-format-latex-options
3331 '(:foreground default :background default :scale 1.0
3332 :html-foreground "Black" :html-background "Transparent"
3333 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3334 "Options for creating images from LaTeX fragments.
3335 This is a property list with the following properties:
3336 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3337 `default' means use the foreground of the default face.
3338 :background the background color, or \"Transparent\".
3339 `default' means use the background of the default face.
3340 :scale a scaling factor for the size of the images, to get more pixels
3341 :html-foreground, :html-background, :html-scale
3342 the same numbers for HTML export.
3343 :matchers a list indicating which matchers should be used to
3344 find LaTeX fragments. Valid members of this list are:
3345 \"begin\" find environments
3346 \"$1\" find single characters surrounded by $.$
3347 \"$\" find math expressions surrounded by $...$
3348 \"$$\" find math expressions surrounded by $$....$$
3349 \"\\(\" find math expressions surrounded by \\(...\\)
3350 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3351 :group 'org-latex
3352 :type 'plist)
3354 (defcustom org-format-latex-signal-error t
3355 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3356 When nil, just push out a message."
3357 :group 'org-latex
3358 :version "24.1"
3359 :type 'boolean)
3361 (defcustom org-latex-to-mathml-jar-file nil
3362 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3363 Use this to specify additional executable file say a jar file.
3365 When using MathToWeb as the converter, specify the full-path to
3366 your mathtoweb.jar file."
3367 :group 'org-latex
3368 :version "24.1"
3369 :type '(choice
3370 (const :tag "None" nil)
3371 (file :tag "JAR file" :must-match t)))
3373 (defcustom org-latex-to-mathml-convert-command nil
3374 "Command to convert LaTeX fragments to MathML.
3375 Replace format-specifiers in the command as noted below and use
3376 `shell-command' to convert LaTeX to MathML.
3377 %j: Executable file in fully expanded form as specified by
3378 `org-latex-to-mathml-jar-file'.
3379 %I: Input LaTeX file in fully expanded form
3380 %o: Output MathML file
3381 This command is used by `org-create-math-formula'.
3383 When using MathToWeb as the converter, set this to
3384 \"java -jar %j -unicode -force -df %o %I\"."
3385 :group 'org-latex
3386 :version "24.1"
3387 :type '(choice
3388 (const :tag "None" nil)
3389 (string :tag "\nShell command")))
3391 (defcustom org-latex-create-formula-image-program 'dvipng
3392 "Program to convert LaTeX fragments with.
3394 dvipng Process the LaTeX fragments to dvi file, then convert
3395 dvi files to png files using dvipng.
3396 This will also include processing of non-math environments.
3397 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3398 to convert pdf files to png files"
3399 :group 'org-latex
3400 :version "24.1"
3401 :type '(choice
3402 (const :tag "dvipng" dvipng)
3403 (const :tag "imagemagick" imagemagick)))
3405 (defun org-format-latex-mathml-available-p ()
3406 "Return t if `org-latex-to-mathml-convert-command' is usable."
3407 (save-match-data
3408 (when (and (boundp 'org-latex-to-mathml-convert-command)
3409 org-latex-to-mathml-convert-command)
3410 (let ((executable (car (split-string
3411 org-latex-to-mathml-convert-command))))
3412 (when (executable-find executable)
3413 (if (string-match
3414 "%j" org-latex-to-mathml-convert-command)
3415 (file-readable-p org-latex-to-mathml-jar-file)
3416 t))))))
3418 (defcustom org-format-latex-header "\\documentclass{article}
3419 \\usepackage[usenames]{color}
3420 \\usepackage{amsmath}
3421 \\usepackage[mathscr]{eucal}
3422 \\pagestyle{empty} % do not remove
3423 \[PACKAGES]
3424 \[DEFAULT-PACKAGES]
3425 % The settings below are copied from fullpage.sty
3426 \\setlength{\\textwidth}{\\paperwidth}
3427 \\addtolength{\\textwidth}{-3cm}
3428 \\setlength{\\oddsidemargin}{1.5cm}
3429 \\addtolength{\\oddsidemargin}{-2.54cm}
3430 \\setlength{\\evensidemargin}{\\oddsidemargin}
3431 \\setlength{\\textheight}{\\paperheight}
3432 \\addtolength{\\textheight}{-\\headheight}
3433 \\addtolength{\\textheight}{-\\headsep}
3434 \\addtolength{\\textheight}{-\\footskip}
3435 \\addtolength{\\textheight}{-3cm}
3436 \\setlength{\\topmargin}{1.5cm}
3437 \\addtolength{\\topmargin}{-2.54cm}"
3438 "The document header used for processing LaTeX fragments.
3439 It is imperative that this header make sure that no page number
3440 appears on the page. The package defined in the variables
3441 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3442 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3443 will be appended."
3444 :group 'org-latex
3445 :type 'string)
3447 (defvar org-format-latex-header-extra nil)
3449 (defun org-set-packages-alist (var val)
3450 "Set the packages alist and make sure it has 3 elements per entry."
3451 (set var (mapcar (lambda (x)
3452 (if (and (consp x) (= (length x) 2))
3453 (list (car x) (nth 1 x) t)
3455 val)))
3457 (defun org-get-packages-alist (var)
3459 "Get the packages alist and make sure it has 3 elements per entry."
3460 (mapcar (lambda (x)
3461 (if (and (consp x) (= (length x) 2))
3462 (list (car x) (nth 1 x) t)
3464 (default-value var)))
3466 ;; The following variables are defined here because is it also used
3467 ;; when formatting latex fragments. Originally it was part of the
3468 ;; LaTeX exporter, which is why the name includes "export".
3469 (defcustom org-export-latex-default-packages-alist
3470 '(("AUTO" "inputenc" t)
3471 ("T1" "fontenc" t)
3472 ("" "fixltx2e" nil)
3473 ("" "graphicx" t)
3474 ("" "longtable" nil)
3475 ("" "float" nil)
3476 ("" "wrapfig" nil)
3477 ("" "soul" t)
3478 ("" "textcomp" t)
3479 ("" "marvosym" t)
3480 ("" "wasysym" t)
3481 ("" "latexsym" t)
3482 ("" "amssymb" t)
3483 ("" "hyperref" nil)
3484 "\\tolerance=1000"
3486 "Alist of default packages to be inserted in the header.
3487 Change this only if one of the packages here causes an incompatibility
3488 with another package you are using.
3489 The packages in this list are needed by one part or another of Org-mode
3490 to function properly.
3492 - inputenc, fontenc: for basic font and character selection
3493 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3494 for interpreting the entities in `org-entities'. You can skip some of these
3495 packages if you don't use any of the symbols in it.
3496 - graphicx: for including images
3497 - float, wrapfig: for figure placement
3498 - longtable: for long tables
3499 - hyperref: for cross references
3501 Therefore you should not modify this variable unless you know what you
3502 are doing. The one reason to change it anyway is that you might be loading
3503 some other package that conflicts with one of the default packages.
3504 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3505 If SNIPPET-FLAG is t, the package also needs to be included when
3506 compiling LaTeX snippets into images for inclusion into HTML."
3507 :group 'org-export-latex
3508 :set 'org-set-packages-alist
3509 :get 'org-get-packages-alist
3510 :version "24.1"
3511 :type '(repeat
3512 (choice
3513 (list :tag "options/package pair"
3514 (string :tag "options")
3515 (string :tag "package")
3516 (boolean :tag "Snippet"))
3517 (string :tag "A line of LaTeX"))))
3519 (defcustom org-export-latex-packages-alist nil
3520 "Alist of packages to be inserted in every LaTeX header.
3521 These will be inserted after `org-export-latex-default-packages-alist'.
3522 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3523 SNIPPET-FLAG, when t, indicates that this package is also needed when
3524 turning LaTeX snippets into images for inclusion into HTML.
3525 Make sure that you only list packages here which:
3526 - you want in every file
3527 - do not conflict with the default packages in
3528 `org-export-latex-default-packages-alist'
3529 - do not conflict with the setup in `org-format-latex-header'."
3530 :group 'org-export-latex
3531 :set 'org-set-packages-alist
3532 :get 'org-get-packages-alist
3533 :type '(repeat
3534 (choice
3535 (list :tag "options/package pair"
3536 (string :tag "options")
3537 (string :tag "package")
3538 (boolean :tag "Snippet"))
3539 (string :tag "A line of LaTeX"))))
3542 (defgroup org-appearance nil
3543 "Settings for Org-mode appearance."
3544 :tag "Org Appearance"
3545 :group 'org)
3547 (defcustom org-level-color-stars-only nil
3548 "Non-nil means fontify only the stars in each headline.
3549 When nil, the entire headline is fontified.
3550 Changing it requires restart of `font-lock-mode' to become effective
3551 also in regions already fontified."
3552 :group 'org-appearance
3553 :type 'boolean)
3555 (defcustom org-hide-leading-stars nil
3556 "Non-nil means hide the first N-1 stars in a headline.
3557 This works by using the face `org-hide' for these stars. This
3558 face is white for a light background, and black for a dark
3559 background. You may have to customize the face `org-hide' to
3560 make this work.
3561 Changing it requires restart of `font-lock-mode' to become effective
3562 also in regions already fontified.
3563 You may also set this on a per-file basis by adding one of the following
3564 lines to the buffer:
3566 #+STARTUP: hidestars
3567 #+STARTUP: showstars"
3568 :group 'org-appearance
3569 :type 'boolean)
3571 (defcustom org-hidden-keywords nil
3572 "List of symbols corresponding to keywords to be hidden the org buffer.
3573 For example, a value '(title) for this list will make the document's title
3574 appear in the buffer without the initial #+TITLE: keyword."
3575 :group 'org-appearance
3576 :version "24.1"
3577 :type '(set (const :tag "#+AUTHOR" author)
3578 (const :tag "#+DATE" date)
3579 (const :tag "#+EMAIL" email)
3580 (const :tag "#+TITLE" title)))
3582 (defcustom org-fontify-done-headline nil
3583 "Non-nil means change the face of a headline if it is marked DONE.
3584 Normally, only the TODO/DONE keyword indicates the state of a headline.
3585 When this is non-nil, the headline after the keyword is set to the
3586 `org-headline-done' as an additional indication."
3587 :group 'org-appearance
3588 :type 'boolean)
3590 (defcustom org-fontify-emphasized-text t
3591 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3592 Changing this variable requires a restart of Emacs to take effect."
3593 :group 'org-appearance
3594 :type 'boolean)
3596 (defcustom org-fontify-whole-heading-line nil
3597 "Non-nil means fontify the whole line for headings.
3598 This is useful when setting a background color for the
3599 org-level-* faces."
3600 :group 'org-appearance
3601 :type 'boolean)
3603 (defcustom org-highlight-latex-fragments-and-specials nil
3604 "Non-nil means fontify what is treated specially by the exporters."
3605 :group 'org-appearance
3606 :type 'boolean)
3608 (defcustom org-hide-emphasis-markers nil
3609 "Non-nil mean font-lock should hide the emphasis marker characters."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-pretty-entities nil
3614 "Non-nil means show entities as UTF8 characters.
3615 When nil, the \\name form remains in the buffer."
3616 :group 'org-appearance
3617 :version "24.1"
3618 :type 'boolean)
3620 (defcustom org-pretty-entities-include-sub-superscripts t
3621 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3622 :group 'org-appearance
3623 :version "24.1"
3624 :type 'boolean)
3626 (defvar org-emph-re nil
3627 "Regular expression for matching emphasis.
3628 After a match, the match groups contain these elements:
3629 0 The match of the full regular expression, including the characters
3630 before and after the proper match
3631 1 The character before the proper match, or empty at beginning of line
3632 2 The proper match, including the leading and trailing markers
3633 3 The leading marker like * or /, indicating the type of highlighting
3634 4 The text between the emphasis markers, not including the markers
3635 5 The character after the match, empty at the end of a line")
3636 (defvar org-verbatim-re nil
3637 "Regular expression for matching verbatim text.")
3638 (defvar org-emphasis-regexp-components) ; defined just below
3639 (defvar org-emphasis-alist) ; defined just below
3640 (defun org-set-emph-re (var val)
3641 "Set variable and compute the emphasis regular expression."
3642 (set var val)
3643 (when (and (boundp 'org-emphasis-alist)
3644 (boundp 'org-emphasis-regexp-components)
3645 org-emphasis-alist org-emphasis-regexp-components)
3646 (let* ((e org-emphasis-regexp-components)
3647 (pre (car e))
3648 (post (nth 1 e))
3649 (border (nth 2 e))
3650 (body (nth 3 e))
3651 (nl (nth 4 e))
3652 (body1 (concat body "*?"))
3653 (markers (mapconcat 'car org-emphasis-alist ""))
3654 (vmarkers (mapconcat
3655 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3656 org-emphasis-alist "")))
3657 ;; make sure special characters appear at the right position in the class
3658 (if (string-match "\\^" markers)
3659 (setq markers (concat (replace-match "" t t markers) "^")))
3660 (if (string-match "-" markers)
3661 (setq markers (concat (replace-match "" t t markers) "-")))
3662 (if (string-match "\\^" vmarkers)
3663 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3664 (if (string-match "-" vmarkers)
3665 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3666 (if (> nl 0)
3667 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3668 (int-to-string nl) "\\}")))
3669 ;; Make the regexp
3670 (setq org-emph-re
3671 (concat "\\([" pre "]\\|^\\)"
3672 "\\("
3673 "\\([" markers "]\\)"
3674 "\\("
3675 "[^" border "]\\|"
3676 "[^" border "]"
3677 body1
3678 "[^" border "]"
3679 "\\)"
3680 "\\3\\)"
3681 "\\([" post "]\\|$\\)"))
3682 (setq org-verbatim-re
3683 (concat "\\([" pre "]\\|^\\)"
3684 "\\("
3685 "\\([" vmarkers "]\\)"
3686 "\\("
3687 "[^" border "]\\|"
3688 "[^" border "]"
3689 body1
3690 "[^" border "]"
3691 "\\)"
3692 "\\3\\)"
3693 "\\([" post "]\\|$\\)")))))
3695 (defcustom org-emphasis-regexp-components
3696 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3697 "Components used to build the regular expression for emphasis.
3698 This is a list with five entries. Terminology: In an emphasis string
3699 like \" *strong word* \", we call the initial space PREMATCH, the final
3700 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3701 and \"trong wor\" is the body. The different components in this variable
3702 specify what is allowed/forbidden in each part:
3704 pre Chars allowed as prematch. Beginning of line will be allowed too.
3705 post Chars allowed as postmatch. End of line will be allowed too.
3706 border The chars *forbidden* as border characters.
3707 body-regexp A regexp like \".\" to match a body character. Don't use
3708 non-shy groups here, and don't allow newline here.
3709 newline The maximum number of newlines allowed in an emphasis exp.
3711 Use customize to modify this, or restart Emacs after changing it."
3712 :group 'org-appearance
3713 :set 'org-set-emph-re
3714 :type '(list
3715 (sexp :tag "Allowed chars in pre ")
3716 (sexp :tag "Allowed chars in post ")
3717 (sexp :tag "Forbidden chars in border ")
3718 (sexp :tag "Regexp for body ")
3719 (integer :tag "number of newlines allowed")
3720 (option (boolean :tag "Please ignore this button"))))
3722 (defcustom org-emphasis-alist
3723 `(("*" bold "<b>" "</b>")
3724 ("/" italic "<i>" "</i>")
3725 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3726 ("=" org-code "<code>" "</code>" verbatim)
3727 ("~" org-verbatim "<code>" "</code>" verbatim)
3728 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3729 "<del>" "</del>")
3731 "Special syntax for emphasized text.
3732 Text starting and ending with a special character will be emphasized, for
3733 example *bold*, _underlined_ and /italic/. This variable sets the marker
3734 characters, the face to be used by font-lock for highlighting in Org-mode
3735 Emacs buffers, and the HTML tags to be used for this.
3736 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3737 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3738 Use customize to modify this, or restart Emacs after changing it."
3739 :group 'org-appearance
3740 :set 'org-set-emph-re
3741 :type '(repeat
3742 (list
3743 (string :tag "Marker character")
3744 (choice
3745 (face :tag "Font-lock-face")
3746 (plist :tag "Face property list"))
3747 (string :tag "HTML start tag")
3748 (string :tag "HTML end tag")
3749 (option (const verbatim)))))
3751 (defvar org-protecting-blocks
3752 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3753 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3754 This is needed for font-lock setup.")
3756 ;;; Miscellaneous options
3758 (defgroup org-completion nil
3759 "Completion in Org-mode."
3760 :tag "Org Completion"
3761 :group 'org)
3763 (defcustom org-completion-use-ido nil
3764 "Non-nil means use ido completion wherever possible.
3765 Note that `ido-mode' must be active for this variable to be relevant.
3766 If you decide to turn this variable on, you might well want to turn off
3767 `org-outline-path-complete-in-steps'.
3768 See also `org-completion-use-iswitchb'."
3769 :group 'org-completion
3770 :type 'boolean)
3772 (defcustom org-completion-use-iswitchb nil
3773 "Non-nil means use iswitchb completion wherever possible.
3774 Note that `iswitchb-mode' must be active for this variable to be relevant.
3775 If you decide to turn this variable on, you might well want to turn off
3776 `org-outline-path-complete-in-steps'.
3777 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3778 :group 'org-completion
3779 :type 'boolean)
3781 (defcustom org-completion-fallback-command 'hippie-expand
3782 "The expansion command called by \\[pcomplete] in normal context.
3783 Normal means, no org-mode-specific context."
3784 :group 'org-completion
3785 :type 'function)
3787 ;;; Functions and variables from their packages
3788 ;; Declared here to avoid compiler warnings
3790 ;; XEmacs only
3791 (defvar outline-mode-menu-heading)
3792 (defvar outline-mode-menu-show)
3793 (defvar outline-mode-menu-hide)
3794 (defvar zmacs-regions) ; XEmacs regions
3796 ;; Emacs only
3797 (defvar mark-active)
3799 ;; Various packages
3800 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3801 (declare-function calendar-forward-day "cal-move" (arg))
3802 (declare-function calendar-goto-date "cal-move" (date))
3803 (declare-function calendar-goto-today "cal-move" ())
3804 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3805 (defvar calc-embedded-close-formula)
3806 (defvar calc-embedded-open-formula)
3807 (declare-function cdlatex-tab "ext:cdlatex" ())
3808 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3809 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3810 (defvar font-lock-unfontify-region-function)
3811 (declare-function iswitchb-read-buffer "iswitchb"
3812 (prompt &optional default require-match start matches-set))
3813 (defvar iswitchb-temp-buflist)
3814 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3815 (defvar org-agenda-tags-todo-honor-ignore-options)
3816 (declare-function org-agenda-skip "org-agenda" ())
3817 (declare-function
3818 org-agenda-format-item "org-agenda"
3819 (extra txt &optional category tags dotime noprefix remove-re habitp))
3820 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3821 (declare-function org-agenda-change-all-lines "org-agenda"
3822 (newhead hdmarker &optional fixface just-this))
3823 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3824 (declare-function org-agenda-maybe-redo "org-agenda" ())
3825 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3826 (beg end))
3827 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3828 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3829 "org-agenda" (&optional end))
3830 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3831 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3832 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3833 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3834 (declare-function org-indent-mode "org-indent" (&optional arg))
3835 (declare-function parse-time-string "parse-time" (string))
3836 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3837 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3838 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3839 (defvar remember-data-file)
3840 (defvar texmathp-why)
3841 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3842 (declare-function table--at-cell-p "table" (position &optional object at-column))
3844 (defvar w3m-current-url)
3845 (defvar w3m-current-title)
3847 (defvar org-latex-regexps)
3849 ;;; Autoload and prepare some org modules
3851 ;; Some table stuff that needs to be defined here, because it is used
3852 ;; by the functions setting up org-mode or checking for table context.
3854 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3855 "Detect an org-type or table-type table.")
3856 (defconst org-table-line-regexp "^[ \t]*|"
3857 "Detect an org-type table line.")
3858 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3859 "Detect an org-type table line.")
3860 (defconst org-table-hline-regexp "^[ \t]*|-"
3861 "Detect an org-type table hline.")
3862 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3863 "Detect a table-type table hline.")
3864 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3865 "Detect the first line outside a table when searching from within it.
3866 This works for both table types.")
3868 ;; Autoload the functions in org-table.el that are needed by functions here.
3870 (eval-and-compile
3871 (org-autoload "org-table"
3872 '(org-table-align org-table-begin org-table-blank-field
3873 org-table-convert org-table-convert-region org-table-copy-down
3874 org-table-copy-region org-table-create
3875 org-table-create-or-convert-from-region
3876 org-table-create-with-table.el org-table-current-dline
3877 org-table-cut-region org-table-delete-column org-table-edit-field
3878 org-table-edit-formulas org-table-end org-table-eval-formula
3879 org-table-export org-table-field-info
3880 org-table-get-stored-formulas org-table-goto-column
3881 org-table-hline-and-move org-table-import org-table-insert-column
3882 org-table-insert-hline org-table-insert-row org-table-iterate
3883 org-table-justify-field-maybe org-table-kill-row
3884 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3885 org-table-move-column org-table-move-column-left
3886 org-table-move-column-right org-table-move-row
3887 org-table-move-row-down org-table-move-row-up
3888 org-table-next-field org-table-next-row org-table-paste-rectangle
3889 org-table-previous-field org-table-recalculate
3890 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3891 org-table-toggle-coordinate-overlays
3892 org-table-toggle-formula-debugger org-table-wrap-region
3893 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3894 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3895 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3897 (defun org-at-table-p (&optional table-type)
3898 "Return t if the cursor is inside an org-type table.
3899 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3900 (if org-enable-table-editor
3901 (save-excursion
3902 (beginning-of-line 1)
3903 (looking-at (if table-type org-table-any-line-regexp
3904 org-table-line-regexp)))
3905 nil))
3906 (defsubst org-table-p () (org-at-table-p))
3908 (defun org-at-table.el-p ()
3909 "Return t if and only if we are at a table.el table."
3910 (and (org-at-table-p 'any)
3911 (save-excursion
3912 (goto-char (org-table-begin 'any))
3913 (looking-at org-table1-hline-regexp))))
3914 (defun org-table-recognize-table.el ()
3915 "If there is a table.el table nearby, recognize it and move into it."
3916 (if org-table-tab-recognizes-table.el
3917 (if (org-at-table.el-p)
3918 (progn
3919 (beginning-of-line 1)
3920 (if (looking-at org-table-dataline-regexp)
3922 (if (looking-at org-table1-hline-regexp)
3923 (progn
3924 (beginning-of-line 2)
3925 (if (looking-at org-table-any-border-regexp)
3926 (beginning-of-line -1)))))
3927 (if (re-search-forward "|" (org-table-end t) t)
3928 (progn
3929 (require 'table)
3930 (if (table--at-cell-p (point))
3932 (message "recognizing table.el table...")
3933 (table-recognize-table)
3934 (message "recognizing table.el table...done")))
3935 (error "This should not happen"))
3937 nil)
3938 nil))
3940 (defun org-at-table-hline-p ()
3941 "Return t if the cursor is inside a hline in a table."
3942 (if org-enable-table-editor
3943 (save-excursion
3944 (beginning-of-line 1)
3945 (looking-at org-table-hline-regexp))
3946 nil))
3948 (defvar org-table-clean-did-remove-column nil)
3950 (defun org-table-map-tables (function &optional quietly)
3951 "Apply FUNCTION to the start of all tables in the buffer."
3952 (save-excursion
3953 (save-restriction
3954 (widen)
3955 (goto-char (point-min))
3956 (while (re-search-forward org-table-any-line-regexp nil t)
3957 (unless quietly
3958 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3959 (beginning-of-line 1)
3960 (when (and (looking-at org-table-line-regexp)
3961 ;; Exclude tables in src/example/verbatim/clocktable blocks
3962 (not (org-in-block-p '("src" "example"))))
3963 (save-excursion (funcall function))
3964 (or (looking-at org-table-line-regexp)
3965 (forward-char 1)))
3966 (re-search-forward org-table-any-border-regexp nil 1))))
3967 (unless quietly (message "Mapping tables: done")))
3969 ;; Declare and autoload functions from org-exp.el & Co
3971 (declare-function org-default-export-plist "org-exp")
3972 (declare-function org-infile-export-plist "org-exp")
3973 (declare-function org-get-current-options "org-exp")
3974 (eval-and-compile
3975 (org-autoload "org-exp"
3976 '(org-export org-export-visible
3977 org-insert-export-options-template
3978 org-table-clean-before-export))
3979 (org-autoload "org-ascii"
3980 '(org-export-as-ascii org-export-ascii-preprocess
3981 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3982 org-export-region-as-ascii))
3983 (org-autoload "org-latex"
3984 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3985 org-replace-region-by-latex org-export-region-as-latex
3986 org-export-as-latex org-export-as-pdf
3987 org-export-as-pdf-and-open))
3988 (org-autoload "org-html"
3989 '(org-export-as-html-and-open
3990 org-export-as-html-batch org-export-as-html-to-buffer
3991 org-replace-region-by-html org-export-region-as-html
3992 org-export-as-html))
3993 (org-autoload "org-docbook"
3994 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3995 org-replace-region-by-docbook org-export-region-as-docbook
3996 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3997 org-export-as-docbook))
3998 (org-autoload "org-icalendar"
3999 '(org-export-icalendar-this-file
4000 org-export-icalendar-all-agenda-files
4001 org-export-icalendar-combine-agenda-files))
4002 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4003 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4005 ;; Declare and autoload functions from org-agenda.el
4007 (eval-and-compile
4008 (org-autoload "org-agenda"
4009 '(org-agenda org-agenda-list org-search-view
4010 org-todo-list org-tags-view org-agenda-list-stuck-projects
4011 org-diary org-agenda-to-appt
4012 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4014 ;; Autoload org-remember
4016 (eval-and-compile
4017 (org-autoload "org-remember"
4018 '(org-remember-insinuate org-remember-annotation
4019 org-remember-apply-template org-remember org-remember-handler)))
4021 (eval-and-compile
4022 (org-autoload "org-capture"
4023 '(org-capture org-capture-insert-template-here
4024 org-capture-import-remember-templates)))
4026 ;; Autoload org-clock.el
4028 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4029 (beg end))
4030 (declare-function org-clock-update-mode-line "org-clock" ())
4031 (declare-function org-resolve-clocks "org-clock"
4032 (&optional also-non-dangling-p prompt last-valid))
4033 (defvar org-clock-start-time)
4034 (defvar org-clock-marker (make-marker)
4035 "Marker recording the last clock-in.")
4036 (defvar org-clock-hd-marker (make-marker)
4037 "Marker recording the last clock-in, but the headline position.")
4038 (defvar org-clock-heading ""
4039 "The heading of the current clock entry.")
4040 (defun org-clock-is-active ()
4041 "Return non-nil if clock is currently running.
4042 The return value is actually the clock marker."
4043 (marker-buffer org-clock-marker))
4045 (eval-and-compile
4046 (org-autoload
4047 "org-clock"
4048 '(org-clock-in org-clock-out org-clock-cancel
4049 org-clock-goto org-clock-sum org-clock-display
4050 org-clock-remove-overlays org-clock-report
4051 org-clocktable-shift org-dblock-write:clocktable
4052 org-get-clocktable org-resolve-clocks)))
4054 (defun org-clock-update-time-maybe ()
4055 "If this is a CLOCK line, update it and return t.
4056 Otherwise, return nil."
4057 (interactive)
4058 (save-excursion
4059 (beginning-of-line 1)
4060 (skip-chars-forward " \t")
4061 (when (looking-at org-clock-string)
4062 (let ((re (concat "[ \t]*" org-clock-string
4063 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4064 "\\([ \t]*=>.*\\)?\\)?"))
4065 ts te h m s neg)
4066 (cond
4067 ((not (looking-at re))
4068 nil)
4069 ((not (match-end 2))
4070 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4071 (> org-clock-marker (point))
4072 (<= org-clock-marker (point-at-eol)))
4073 ;; The clock is running here
4074 (setq org-clock-start-time
4075 (apply 'encode-time
4076 (org-parse-time-string (match-string 1))))
4077 (org-clock-update-mode-line)))
4079 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4080 (end-of-line 1)
4081 (setq ts (match-string 1)
4082 te (match-string 3))
4083 (setq s (- (org-float-time
4084 (apply 'encode-time (org-parse-time-string te)))
4085 (org-float-time
4086 (apply 'encode-time (org-parse-time-string ts))))
4087 neg (< s 0)
4088 s (abs s)
4089 h (floor (/ s 3600))
4090 s (- s (* 3600 h))
4091 m (floor (/ s 60))
4092 s (- s (* 60 s)))
4093 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4094 t))))))
4096 (defun org-check-running-clock ()
4097 "Check if the current buffer contains the running clock.
4098 If yes, offer to stop it and to save the buffer with the changes."
4099 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4100 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4101 (buffer-name))))
4102 (org-clock-out)
4103 (when (y-or-n-p "Save changed buffer?")
4104 (save-buffer))))
4106 (defun org-clocktable-try-shift (dir n)
4107 "Check if this line starts a clock table, if yes, shift the time block."
4108 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4109 (org-clocktable-shift dir n)))
4111 ;; Autoload org-timer.el
4113 (eval-and-compile
4114 (org-autoload
4115 "org-timer"
4116 '(org-timer-start org-timer org-timer-item
4117 org-timer-change-times-in-region
4118 org-timer-set-timer
4119 org-timer-reset-timers
4120 org-timer-show-remaining-time)))
4122 ;; Autoload org-feed.el
4124 (eval-and-compile
4125 (org-autoload
4126 "org-feed"
4127 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4130 ;; Autoload org-indent.el
4132 ;; Define the variable already here, to make sure we have it.
4133 (defvar org-indent-mode nil
4134 "Non-nil if Org-Indent mode is enabled.
4135 Use the command `org-indent-mode' to change this variable.")
4137 (eval-and-compile
4138 (org-autoload
4139 "org-indent"
4140 '(org-indent-mode)))
4142 ;; Autoload org-mobile.el
4144 (eval-and-compile
4145 (org-autoload
4146 "org-mobile"
4147 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4149 ;; Autoload archiving code
4150 ;; The stuff that is needed for cycling and tags has to be defined here.
4152 (defgroup org-archive nil
4153 "Options concerning archiving in Org-mode."
4154 :tag "Org Archive"
4155 :group 'org-structure)
4157 (defcustom org-archive-location "%s_archive::"
4158 "The location where subtrees should be archived.
4160 The value of this variable is a string, consisting of two parts,
4161 separated by a double-colon. The first part is a filename and
4162 the second part is a headline.
4164 When the filename is omitted, archiving happens in the same file.
4165 %s in the filename will be replaced by the current file
4166 name (without the directory part). Archiving to a different file
4167 is useful to keep archived entries from contributing to the
4168 Org-mode Agenda.
4170 The archived entries will be filed as subtrees of the specified
4171 headline. When the headline is omitted, the subtrees are simply
4172 filed away at the end of the file, as top-level entries. Also in
4173 the heading you can use %s to represent the file name, this can be
4174 useful when using the same archive for a number of different files.
4176 Here are a few examples:
4177 \"%s_archive::\"
4178 If the current file is Projects.org, archive in file
4179 Projects.org_archive, as top-level trees. This is the default.
4181 \"::* Archived Tasks\"
4182 Archive in the current file, under the top-level headline
4183 \"* Archived Tasks\".
4185 \"~/org/archive.org::\"
4186 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4188 \"~/org/archive.org::* From %s\"
4189 Archive in file ~/org/archive.org (absolute path), under headlines
4190 \"From FILENAME\" where file name is the current file name.
4192 \"~/org/datetree.org::datetree/* Finished Tasks\"
4193 The \"datetree/\" string is special, signifying to archive
4194 items to the datetree. Items are placed in either the CLOSED
4195 date of the item, or the current date if there is no CLOSED date.
4196 The heading will be a subentry to the current date. There doesn't
4197 need to be a heading, but there always needs to be a slash after
4198 datetree. For example, to store archived items directly in the
4199 datetree, use \"~/org/datetree.org::datetree/\".
4201 \"basement::** Finished Tasks\"
4202 Archive in file ./basement (relative path), as level 3 trees
4203 below the level 2 heading \"** Finished Tasks\".
4205 You may set this option on a per-file basis by adding to the buffer a
4206 line like
4208 #+ARCHIVE: basement::** Finished Tasks
4210 You may also define it locally for a subtree by setting an ARCHIVE property
4211 in the entry. If such a property is found in an entry, or anywhere up
4212 the hierarchy, it will be used."
4213 :group 'org-archive
4214 :type 'string)
4216 (defcustom org-archive-tag "ARCHIVE"
4217 "The tag that marks a subtree as archived.
4218 An archived subtree does not open during visibility cycling, and does
4219 not contribute to the agenda listings.
4220 After changing this, font-lock must be restarted in the relevant buffers to
4221 get the proper fontification."
4222 :group 'org-archive
4223 :group 'org-keywords
4224 :type 'string)
4226 (defcustom org-agenda-skip-archived-trees t
4227 "Non-nil means the agenda will skip any items located in archived trees.
4228 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4229 variable is no longer recommended, you should leave it at the value t.
4230 Instead, use the key `v' to cycle the archives-mode in the agenda."
4231 :group 'org-archive
4232 :group 'org-agenda-skip
4233 :type 'boolean)
4235 (defcustom org-columns-skip-archived-trees t
4236 "Non-nil means ignore archived trees when creating column view."
4237 :group 'org-archive
4238 :group 'org-properties
4239 :type 'boolean)
4241 (defcustom org-cycle-open-archived-trees nil
4242 "Non-nil means `org-cycle' will open archived trees.
4243 An archived tree is a tree marked with the tag ARCHIVE.
4244 When nil, archived trees will stay folded. You can still open them with
4245 normal outline commands like `show-all', but not with the cycling commands."
4246 :group 'org-archive
4247 :group 'org-cycle
4248 :type 'boolean)
4250 (defcustom org-sparse-tree-open-archived-trees nil
4251 "Non-nil means sparse tree construction shows matches in archived trees.
4252 When nil, matches in these trees are highlighted, but the trees are kept in
4253 collapsed state."
4254 :group 'org-archive
4255 :group 'org-sparse-trees
4256 :type 'boolean)
4258 (defun org-cycle-hide-archived-subtrees (state)
4259 "Re-hide all archived subtrees after a visibility state change."
4260 (when (and (not org-cycle-open-archived-trees)
4261 (not (memq state '(overview folded))))
4262 (save-excursion
4263 (let* ((globalp (memq state '(contents all)))
4264 (beg (if globalp (point-min) (point)))
4265 (end (if globalp (point-max) (org-end-of-subtree t))))
4266 (org-hide-archived-subtrees beg end)
4267 (goto-char beg)
4268 (if (looking-at (concat ".*:" org-archive-tag ":"))
4269 (message "%s" (substitute-command-keys
4270 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4272 (defun org-force-cycle-archived ()
4273 "Cycle subtree even if it is archived."
4274 (interactive)
4275 (setq this-command 'org-cycle)
4276 (let ((org-cycle-open-archived-trees t))
4277 (call-interactively 'org-cycle)))
4279 (defun org-hide-archived-subtrees (beg end)
4280 "Re-hide all archived subtrees after a visibility state change."
4281 (save-excursion
4282 (let* ((re (concat ":" org-archive-tag ":")))
4283 (goto-char beg)
4284 (while (re-search-forward re end t)
4285 (when (org-at-heading-p)
4286 (org-flag-subtree t)
4287 (org-end-of-subtree t))))))
4289 (defun org-flag-subtree (flag)
4290 (save-excursion
4291 (org-back-to-heading t)
4292 (outline-end-of-heading)
4293 (outline-flag-region (point)
4294 (progn (org-end-of-subtree t) (point))
4295 flag)))
4297 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4299 (eval-and-compile
4300 (org-autoload "org-archive"
4301 '(org-add-archive-files org-archive-subtree
4302 org-archive-to-archive-sibling org-toggle-archive-tag
4303 org-archive-subtree-default
4304 org-archive-subtree-default-with-confirmation)))
4306 ;; Autoload Column View Code
4308 (declare-function org-columns-number-to-string "org-colview")
4309 (declare-function org-columns-get-format-and-top-level "org-colview")
4310 (declare-function org-columns-compute "org-colview")
4312 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4313 '(org-columns-number-to-string org-columns-get-format-and-top-level
4314 org-columns-compute org-agenda-columns org-columns-remove-overlays
4315 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4317 ;; Autoload ID code
4319 (declare-function org-id-store-link "org-id")
4320 (declare-function org-id-locations-load "org-id")
4321 (declare-function org-id-locations-save "org-id")
4322 (defvar org-id-track-globally)
4323 (org-autoload "org-id"
4324 '(org-id-get-create org-id-new org-id-copy org-id-get
4325 org-id-get-with-outline-path-completion
4326 org-id-get-with-outline-drilling org-id-store-link
4327 org-id-goto org-id-find org-id-store-link))
4329 ;; Autoload Plotting Code
4331 (org-autoload "org-plot"
4332 '(org-plot/gnuplot))
4334 ;;; Variables for pre-computed regular expressions, all buffer local
4336 (defvar org-drawer-regexp nil
4337 "Matches first line of a hidden block.")
4338 (make-variable-buffer-local 'org-drawer-regexp)
4339 (defvar org-todo-regexp nil
4340 "Matches any of the TODO state keywords.")
4341 (make-variable-buffer-local 'org-todo-regexp)
4342 (defvar org-not-done-regexp nil
4343 "Matches any of the TODO state keywords except the last one.")
4344 (make-variable-buffer-local 'org-not-done-regexp)
4345 (defvar org-not-done-heading-regexp nil
4346 "Matches a TODO headline that is not done.")
4347 (make-variable-buffer-local 'org-not-done-regexp)
4348 (defvar org-todo-line-regexp nil
4349 "Matches a headline and puts TODO state into group 2 if present.")
4350 (make-variable-buffer-local 'org-todo-line-regexp)
4351 (defvar org-complex-heading-regexp nil
4352 "Matches a headline and puts everything into groups:
4353 group 1: the stars
4354 group 2: The todo keyword, maybe
4355 group 3: Priority cookie
4356 group 4: True headline
4357 group 5: Tags")
4358 (make-variable-buffer-local 'org-complex-heading-regexp)
4359 (defvar org-complex-heading-regexp-format nil
4360 "Printf format to make regexp to match an exact headline.
4361 This regexp will match the headline of any node which has the
4362 exact headline text that is put into the format, but may have any
4363 TODO state, priority and tags.")
4364 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4365 (defvar org-todo-line-tags-regexp nil
4366 "Matches a headline and puts TODO state into group 2 if present.
4367 Also put tags into group 4 if tags are present.")
4368 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4369 (defvar org-ds-keyword-length 12
4370 "Maximum length of the Deadline and SCHEDULED keywords.")
4371 (make-variable-buffer-local 'org-ds-keyword-length)
4372 (defvar org-deadline-regexp nil
4373 "Matches the DEADLINE keyword.")
4374 (make-variable-buffer-local 'org-deadline-regexp)
4375 (defvar org-deadline-time-regexp nil
4376 "Matches the DEADLINE keyword together with a time stamp.")
4377 (make-variable-buffer-local 'org-deadline-time-regexp)
4378 (defvar org-deadline-line-regexp nil
4379 "Matches the DEADLINE keyword and the rest of the line.")
4380 (make-variable-buffer-local 'org-deadline-line-regexp)
4381 (defvar org-scheduled-regexp nil
4382 "Matches the SCHEDULED keyword.")
4383 (make-variable-buffer-local 'org-scheduled-regexp)
4384 (defvar org-scheduled-time-regexp nil
4385 "Matches the SCHEDULED keyword together with a time stamp.")
4386 (make-variable-buffer-local 'org-scheduled-time-regexp)
4387 (defvar org-closed-time-regexp nil
4388 "Matches the CLOSED keyword together with a time stamp.")
4389 (make-variable-buffer-local 'org-closed-time-regexp)
4391 (defvar org-keyword-time-regexp nil
4392 "Matches any of the 4 keywords, together with the time stamp.")
4393 (make-variable-buffer-local 'org-keyword-time-regexp)
4394 (defvar org-keyword-time-not-clock-regexp nil
4395 "Matches any of the 3 keywords, together with the time stamp.")
4396 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4397 (defvar org-maybe-keyword-time-regexp nil
4398 "Matches a timestamp, possibly preceded by a keyword.")
4399 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4400 (defvar org-planning-or-clock-line-re nil
4401 "Matches a line with planning or clock info.")
4402 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4403 (defvar org-all-time-keywords nil
4404 "List of time keywords.")
4405 (make-variable-buffer-local 'org-all-time-keywords)
4407 (defconst org-plain-time-of-day-regexp
4408 (concat
4409 "\\(\\<[012]?[0-9]"
4410 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4411 "\\(--?"
4412 "\\(\\<[012]?[0-9]"
4413 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4414 "\\)?")
4415 "Regular expression to match a plain time or time range.
4416 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4417 groups carry important information:
4418 0 the full match
4419 1 the first time, range or not
4420 8 the second time, if it is a range.")
4422 (defconst org-plain-time-extension-regexp
4423 (concat
4424 "\\(\\<[012]?[0-9]"
4425 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4426 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4427 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4428 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4429 groups carry important information:
4430 0 the full match
4431 7 hours of duration
4432 9 minutes of duration")
4434 (defconst org-stamp-time-of-day-regexp
4435 (concat
4436 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4437 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4438 "\\(--?"
4439 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4440 "Regular expression to match a timestamp time or time range.
4441 After a match, the following groups carry important information:
4442 0 the full match
4443 1 date plus weekday, for back referencing to make sure both times are on the same day
4444 2 the first time, range or not
4445 4 the second time, if it is a range.")
4447 (defconst org-startup-options
4448 '(("fold" org-startup-folded t)
4449 ("overview" org-startup-folded t)
4450 ("nofold" org-startup-folded nil)
4451 ("showall" org-startup-folded nil)
4452 ("showeverything" org-startup-folded showeverything)
4453 ("content" org-startup-folded content)
4454 ("indent" org-startup-indented t)
4455 ("noindent" org-startup-indented nil)
4456 ("hidestars" org-hide-leading-stars t)
4457 ("showstars" org-hide-leading-stars nil)
4458 ("odd" org-odd-levels-only t)
4459 ("oddeven" org-odd-levels-only nil)
4460 ("align" org-startup-align-all-tables t)
4461 ("noalign" org-startup-align-all-tables nil)
4462 ("inlineimages" org-startup-with-inline-images t)
4463 ("noinlineimages" org-startup-with-inline-images nil)
4464 ("customtime" org-display-custom-times t)
4465 ("logdone" org-log-done time)
4466 ("lognotedone" org-log-done note)
4467 ("nologdone" org-log-done nil)
4468 ("lognoteclock-out" org-log-note-clock-out t)
4469 ("nolognoteclock-out" org-log-note-clock-out nil)
4470 ("logrepeat" org-log-repeat state)
4471 ("lognoterepeat" org-log-repeat note)
4472 ("nologrepeat" org-log-repeat nil)
4473 ("logreschedule" org-log-reschedule time)
4474 ("lognotereschedule" org-log-reschedule note)
4475 ("nologreschedule" org-log-reschedule nil)
4476 ("logredeadline" org-log-redeadline time)
4477 ("lognoteredeadline" org-log-redeadline note)
4478 ("nologredeadline" org-log-redeadline nil)
4479 ("logrefile" org-log-refile time)
4480 ("lognoterefile" org-log-refile note)
4481 ("nologrefile" org-log-refile nil)
4482 ("fninline" org-footnote-define-inline t)
4483 ("nofninline" org-footnote-define-inline nil)
4484 ("fnlocal" org-footnote-section nil)
4485 ("fnauto" org-footnote-auto-label t)
4486 ("fnprompt" org-footnote-auto-label nil)
4487 ("fnconfirm" org-footnote-auto-label confirm)
4488 ("fnplain" org-footnote-auto-label plain)
4489 ("fnadjust" org-footnote-auto-adjust t)
4490 ("nofnadjust" org-footnote-auto-adjust nil)
4491 ("constcgs" constants-unit-system cgs)
4492 ("constSI" constants-unit-system SI)
4493 ("noptag" org-tag-persistent-alist nil)
4494 ("hideblocks" org-hide-block-startup t)
4495 ("nohideblocks" org-hide-block-startup nil)
4496 ("beamer" org-startup-with-beamer-mode t)
4497 ("entitiespretty" org-pretty-entities t)
4498 ("entitiesplain" org-pretty-entities nil))
4499 "Variable associated with STARTUP options for org-mode.
4500 Each element is a list of three items: the startup options (as written
4501 in the #+STARTUP line), the corresponding variable, and the value to set
4502 this variable to if the option is found. An optional forth element PUSH
4503 means to push this value onto the list in the variable.")
4505 (defun org-update-property-plist (key val props)
4506 "Update PROPS with KEY and VAL."
4507 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4508 (key (if appending (substring key 0 (- (length key) 1)) key))
4509 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4510 (previous (cdr (assoc key props))))
4511 (if appending
4512 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4513 (cons (cons key val) remainder))))
4515 (defconst org-block-regexp
4516 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4517 "Regular expression for hiding blocks.")
4518 (defconst org-heading-keyword-regexp-format
4519 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4520 "Printf format for a regexp matching an headline with some keyword.
4521 This regexp will match the headline of any node which has the
4522 exact keyword that is put into the format. The keyword isn't in
4523 any group by default, but the stars and the body are.")
4524 (defconst org-heading-keyword-maybe-regexp-format
4525 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4526 "Printf format for a regexp matching an headline, possibly with some keyword.
4527 This regexp can match any headline with the specified keyword, or
4528 without a keyword. The keyword isn't in any group by default,
4529 but the stars and the body are.")
4531 (defun org-set-regexps-and-options ()
4532 "Precompute regular expressions for current buffer."
4533 (when (derived-mode-p 'org-mode)
4534 (org-set-local 'org-todo-kwd-alist nil)
4535 (org-set-local 'org-todo-key-alist nil)
4536 (org-set-local 'org-todo-key-trigger nil)
4537 (org-set-local 'org-todo-keywords-1 nil)
4538 (org-set-local 'org-done-keywords nil)
4539 (org-set-local 'org-todo-heads nil)
4540 (org-set-local 'org-todo-sets nil)
4541 (org-set-local 'org-todo-log-states nil)
4542 (org-set-local 'org-file-properties nil)
4543 (org-set-local 'org-file-tags nil)
4544 (let ((re (org-make-options-regexp
4545 '("CATEGORY" "TODO" "COLUMNS"
4546 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4547 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4548 "OPTIONS")
4549 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4550 (splitre "[ \t]+")
4551 (scripts org-use-sub-superscripts)
4552 kwds kws0 kwsa key log value cat arch tags const links hw dws
4553 tail sep kws1 prio props ftags drawers beamer-p
4554 ext-setup-or-nil setup-contents (start 0))
4555 (save-excursion
4556 (save-restriction
4557 (widen)
4558 (goto-char (point-min))
4559 (while (or (and ext-setup-or-nil
4560 (string-match re ext-setup-or-nil start)
4561 (setq start (match-end 0)))
4562 (and (setq ext-setup-or-nil nil start 0)
4563 (re-search-forward re nil t)))
4564 (setq key (upcase (match-string 1 ext-setup-or-nil))
4565 value (org-match-string-no-properties 2 ext-setup-or-nil))
4566 (if (stringp value) (setq value (org-trim value)))
4567 (cond
4568 ((equal key "CATEGORY")
4569 (setq cat value))
4570 ((member key '("SEQ_TODO" "TODO"))
4571 (push (cons 'sequence (org-split-string value splitre)) kwds))
4572 ((equal key "TYP_TODO")
4573 (push (cons 'type (org-split-string value splitre)) kwds))
4574 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4575 ;; general TODO-like setup
4576 (push (cons (intern (downcase (match-string 1 key)))
4577 (org-split-string value splitre)) kwds))
4578 ((equal key "TAGS")
4579 (setq tags (append tags (if tags '("\\n") nil)
4580 (org-split-string value splitre))))
4581 ((equal key "COLUMNS")
4582 (org-set-local 'org-columns-default-format value))
4583 ((equal key "LINK")
4584 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4585 (push (cons (match-string 1 value)
4586 (org-trim (match-string 2 value)))
4587 links)))
4588 ((equal key "PRIORITIES")
4589 (setq prio (org-split-string value " +")))
4590 ((equal key "PROPERTY")
4591 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4592 (setq props (org-update-property-plist (match-string 1 value)
4593 (match-string 2 value)
4594 props))))
4595 ((equal key "FILETAGS")
4596 (when (string-match "\\S-" value)
4597 (setq ftags
4598 (append
4599 ftags
4600 (apply 'append
4601 (mapcar (lambda (x) (org-split-string x ":"))
4602 (org-split-string value)))))))
4603 ((equal key "DRAWERS")
4604 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4605 ((equal key "CONSTANTS")
4606 (setq const (append const (org-split-string value splitre))))
4607 ((equal key "STARTUP")
4608 (let ((opts (org-split-string value splitre))
4609 l var val)
4610 (while (setq l (pop opts))
4611 (when (setq l (assoc l org-startup-options))
4612 (setq var (nth 1 l) val (nth 2 l))
4613 (if (not (nth 3 l))
4614 (set (make-local-variable var) val)
4615 (if (not (listp (symbol-value var)))
4616 (set (make-local-variable var) nil))
4617 (set (make-local-variable var) (symbol-value var))
4618 (add-to-list var val))))))
4619 ((equal key "ARCHIVE")
4620 (setq arch value)
4621 (remove-text-properties 0 (length arch)
4622 '(face t fontified t) arch))
4623 ((equal key "LATEX_CLASS")
4624 (setq beamer-p (equal value "beamer")))
4625 ((equal key "OPTIONS")
4626 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4627 (setq scripts (read (match-string 2 value)))))
4628 ((equal key "SETUPFILE")
4629 (setq setup-contents (org-file-contents
4630 (expand-file-name
4631 (org-remove-double-quotes value))
4632 'noerror))
4633 (if (not ext-setup-or-nil)
4634 (setq ext-setup-or-nil setup-contents start 0)
4635 (setq ext-setup-or-nil
4636 (concat (substring ext-setup-or-nil 0 start)
4637 "\n" setup-contents "\n"
4638 (substring ext-setup-or-nil start)))))))
4639 ;; search for property blocks
4640 (goto-char (point-min))
4641 (while (re-search-forward org-block-regexp nil t)
4642 (when (equal "PROPERTY" (upcase (match-string 1)))
4643 (setq value (replace-regexp-in-string
4644 "[\n\r]" " " (match-string 4)))
4645 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4646 (setq props (org-update-property-plist (match-string 1 value)
4647 (match-string 2 value)
4648 props)))))))
4649 (org-set-local 'org-use-sub-superscripts scripts)
4650 (when cat
4651 (org-set-local 'org-category (intern cat))
4652 (push (cons "CATEGORY" cat) props))
4653 (when prio
4654 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4655 (setq prio (mapcar 'string-to-char prio))
4656 (org-set-local 'org-highest-priority (nth 0 prio))
4657 (org-set-local 'org-lowest-priority (nth 1 prio))
4658 (org-set-local 'org-default-priority (nth 2 prio)))
4659 (and props (org-set-local 'org-file-properties (nreverse props)))
4660 (and ftags (org-set-local 'org-file-tags
4661 (mapcar 'org-add-prop-inherited ftags)))
4662 (and drawers (org-set-local 'org-drawers drawers))
4663 (and arch (org-set-local 'org-archive-location arch))
4664 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4665 ;; Process the TODO keywords
4666 (unless kwds
4667 ;; Use the global values as if they had been given locally.
4668 (setq kwds (default-value 'org-todo-keywords))
4669 (if (stringp (car kwds))
4670 (setq kwds (list (cons org-todo-interpretation
4671 (default-value 'org-todo-keywords)))))
4672 (setq kwds (reverse kwds)))
4673 (setq kwds (nreverse kwds))
4674 (let (inter kws kw)
4675 (while (setq kws (pop kwds))
4676 (let ((kws (or
4677 (run-hook-with-args-until-success
4678 'org-todo-setup-filter-hook kws)
4679 kws)))
4680 (setq inter (pop kws) sep (member "|" kws)
4681 kws0 (delete "|" (copy-sequence kws))
4682 kwsa nil
4683 kws1 (mapcar
4684 (lambda (x)
4685 ;; 1 2
4686 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4687 (progn
4688 (setq kw (match-string 1 x)
4689 key (and (match-end 2) (match-string 2 x))
4690 log (org-extract-log-state-settings x))
4691 (push (cons kw (and key (string-to-char key))) kwsa)
4692 (and log (push log org-todo-log-states))
4694 (error "Invalid TODO keyword %s" x)))
4695 kws0)
4696 kwsa (if kwsa (append '((:startgroup))
4697 (nreverse kwsa)
4698 '((:endgroup))))
4699 hw (car kws1)
4700 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4701 tail (list inter hw (car dws) (org-last dws))))
4702 (add-to-list 'org-todo-heads hw 'append)
4703 (push kws1 org-todo-sets)
4704 (setq org-done-keywords (append org-done-keywords dws nil))
4705 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4706 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4707 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4708 (setq org-todo-sets (nreverse org-todo-sets)
4709 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4710 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4711 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4712 ;; Process the constants
4713 (when const
4714 (let (e cst)
4715 (while (setq e (pop const))
4716 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4717 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4718 (setq org-table-formula-constants-local cst)))
4720 ;; Process the tags.
4721 (when tags
4722 (let (e tgs)
4723 (while (setq e (pop tags))
4724 (cond
4725 ((equal e "{") (push '(:startgroup) tgs))
4726 ((equal e "}") (push '(:endgroup) tgs))
4727 ((equal e "\\n") (push '(:newline) tgs))
4728 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4729 (push (cons (match-string 1 e)
4730 (string-to-char (match-string 2 e)))
4731 tgs))
4732 (t (push (list e) tgs))))
4733 (org-set-local 'org-tag-alist nil)
4734 (while (setq e (pop tgs))
4735 (or (and (stringp (car e))
4736 (assoc (car e) org-tag-alist))
4737 (push e org-tag-alist)))))
4739 ;; Compute the regular expressions and other local variables.
4740 ;; Using `org-outline-regexp-bol' would complicate them much,
4741 ;; because of the fixed white space at the end of that string.
4742 (if (not org-done-keywords)
4743 (setq org-done-keywords (and org-todo-keywords-1
4744 (list (org-last org-todo-keywords-1)))))
4745 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4746 (length org-scheduled-string)
4747 (length org-clock-string)
4748 (length org-closed-string)))
4749 org-drawer-regexp
4750 (concat "^[ \t]*:\\("
4751 (mapconcat 'regexp-quote org-drawers "\\|")
4752 "\\):[ \t]*$")
4753 org-not-done-keywords
4754 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4755 org-todo-regexp
4756 (concat "\\("
4757 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4758 "\\)")
4759 org-not-done-regexp
4760 (concat "\\("
4761 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4762 "\\)")
4763 org-not-done-heading-regexp
4764 (format org-heading-keyword-regexp-format org-not-done-regexp)
4765 org-todo-line-regexp
4766 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4767 org-complex-heading-regexp
4768 (concat "^\\(\\*+\\)"
4769 "\\(?: +" org-todo-regexp "\\)?"
4770 "\\(?: +\\(\\[#.\\]\\)\\)?"
4771 "\\(?: +\\(.*?\\)\\)?"
4772 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4773 "[ \t]*$")
4774 org-complex-heading-regexp-format
4775 (concat "^\\(\\*+\\)"
4776 "\\(?: +" org-todo-regexp "\\)?"
4777 "\\(?: +\\(\\[#.\\]\\)\\)?"
4778 "\\(?: +"
4779 ;; Stats cookies can be stuck to body.
4780 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4781 "\\(%s\\)"
4782 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4783 "\\)"
4784 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4785 "[ \t]*$")
4786 org-todo-line-tags-regexp
4787 (concat "^\\(\\*+\\)"
4788 "\\(?: +" org-todo-regexp "\\)?"
4789 "\\(?: +\\(.*?\\)\\)?"
4790 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4791 "[ \t]*$")
4792 org-deadline-regexp (concat "\\<" org-deadline-string)
4793 org-deadline-time-regexp
4794 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4795 org-deadline-line-regexp
4796 (concat "\\<\\(" org-deadline-string "\\).*")
4797 org-scheduled-regexp
4798 (concat "\\<" org-scheduled-string)
4799 org-scheduled-time-regexp
4800 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4801 org-closed-time-regexp
4802 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4803 org-keyword-time-regexp
4804 (concat "\\<\\(" org-scheduled-string
4805 "\\|" org-deadline-string
4806 "\\|" org-closed-string
4807 "\\|" org-clock-string "\\)"
4808 " *[[<]\\([^]>]+\\)[]>]")
4809 org-keyword-time-not-clock-regexp
4810 (concat "\\<\\(" org-scheduled-string
4811 "\\|" org-deadline-string
4812 "\\|" org-closed-string
4813 "\\)"
4814 " *[[<]\\([^]>]+\\)[]>]")
4815 org-maybe-keyword-time-regexp
4816 (concat "\\(\\<\\(" org-scheduled-string
4817 "\\|" org-deadline-string
4818 "\\|" org-closed-string
4819 "\\|" org-clock-string "\\)\\)?"
4820 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4821 org-planning-or-clock-line-re
4822 (concat "^[ \t]*\\("
4823 org-scheduled-string "\\|"
4824 org-deadline-string "\\|"
4825 org-closed-string "\\|"
4826 org-clock-string "\\)")
4827 org-all-time-keywords
4828 (mapcar (lambda (w) (substring w 0 -1))
4829 (list org-scheduled-string org-deadline-string
4830 org-clock-string org-closed-string))
4832 (org-compute-latex-and-specials-regexp)
4833 (org-set-font-lock-defaults))))
4835 (defun org-file-contents (file &optional noerror)
4836 "Return the contents of FILE, as a string."
4837 (if (or (not file)
4838 (not (file-readable-p file)))
4839 (if noerror
4840 (progn
4841 (message "Cannot read file \"%s\"" file)
4842 (ding) (sit-for 2)
4844 (error "Cannot read file \"%s\"" file))
4845 (with-temp-buffer
4846 (insert-file-contents file)
4847 (buffer-string))))
4849 (defun org-extract-log-state-settings (x)
4850 "Extract the log state setting from a TODO keyword string.
4851 This will extract info from a string like \"WAIT(w@/!)\"."
4852 (let (kw key log1 log2)
4853 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4854 (setq kw (match-string 1 x)
4855 key (and (match-end 2) (match-string 2 x))
4856 log1 (and (match-end 3) (match-string 3 x))
4857 log2 (and (match-end 4) (match-string 4 x)))
4858 (and (or log1 log2)
4859 (list kw
4860 (and log1 (if (equal log1 "!") 'time 'note))
4861 (and log2 (if (equal log2 "!") 'time 'note)))))))
4863 (defun org-remove-keyword-keys (list)
4864 "Remove a pair of parenthesis at the end of each string in LIST."
4865 (mapcar (lambda (x)
4866 (if (string-match "(.*)$" x)
4867 (substring x 0 (match-beginning 0))
4869 list))
4871 (defun org-assign-fast-keys (alist)
4872 "Assign fast keys to a keyword-key alist.
4873 Respect keys that are already there."
4874 (let (new e (alt ?0))
4875 (while (setq e (pop alist))
4876 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4877 (cdr e)) ;; Key already assigned.
4878 (push e new)
4879 (let ((clist (string-to-list (downcase (car e))))
4880 (used (append new alist)))
4881 (when (= (car clist) ?@)
4882 (pop clist))
4883 (while (and clist (rassoc (car clist) used))
4884 (pop clist))
4885 (unless clist
4886 (while (rassoc alt used)
4887 (incf alt)))
4888 (push (cons (car e) (or (car clist) alt)) new))))
4889 (nreverse new)))
4891 ;;; Some variables used in various places
4893 (defvar org-window-configuration nil
4894 "Used in various places to store a window configuration.")
4895 (defvar org-selected-window nil
4896 "Used in various places to store a window configuration.")
4897 (defvar org-finish-function nil
4898 "Function to be called when `C-c C-c' is used.
4899 This is for getting out of special buffers like remember.")
4902 ;; FIXME: Occasionally check by commenting these, to make sure
4903 ;; no other functions uses these, forgetting to let-bind them.
4904 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4905 (defvar org-last-state)
4906 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4908 ;; Defined somewhere in this file, but used before definition.
4909 (defvar org-entities) ;; defined in org-entities.el
4910 (defvar org-struct-menu)
4911 (defvar org-org-menu)
4912 (defvar org-tbl-menu)
4914 ;;;; Define the Org-mode
4916 ;; We use a before-change function to check if a table might need
4917 ;; an update.
4918 (defvar org-table-may-need-update t
4919 "Indicates that a table might need an update.
4920 This variable is set by `org-before-change-function'.
4921 `org-table-align' sets it back to nil.")
4922 (defun org-before-change-function (beg end)
4923 "Every change indicates that a table might need an update."
4924 (setq org-table-may-need-update t))
4925 (defvar org-mode-map)
4926 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4927 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4928 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4929 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4930 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4931 (defvar org-table-buffer-is-an nil)
4933 (defvar bidi-paragraph-direction)
4934 (defvar buffer-face-mode-face)
4936 (require 'outline)
4937 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4938 (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"))
4939 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4941 ;; Other stuff we need.
4942 (require 'time-date)
4943 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4944 (require 'easymenu)
4945 (require 'overlay)
4947 (require 'org-macs)
4948 (require 'org-entities)
4949 (require 'org-compat)
4950 (require 'org-faces)
4951 (require 'org-list)
4952 (require 'org-pcomplete)
4953 (require 'org-src)
4954 (require 'org-footnote)
4955 (require 'org-element)
4957 ;; babel
4958 (require 'ob)
4959 (require 'ob-table)
4960 (require 'ob-lob)
4961 (require 'ob-ref)
4962 (require 'ob-tangle)
4963 (require 'ob-comint)
4964 (require 'ob-keys)
4966 ;;;###autoload
4967 (define-derived-mode org-mode outline-mode "Org"
4968 "Outline-based notes management and organizer, alias
4969 \"Carsten's outline-mode for keeping track of everything.\"
4971 Org-mode develops organizational tasks around a NOTES file which
4972 contains information about projects as plain text. Org-mode is
4973 implemented on top of outline-mode, which is ideal to keep the content
4974 of large files well structured. It supports ToDo items, deadlines and
4975 time stamps, which magically appear in the diary listing of the Emacs
4976 calendar. Tables are easily created with a built-in table editor.
4977 Plain text URL-like links connect to websites, emails (VM), Usenet
4978 messages (Gnus), BBDB entries, and any files related to the project.
4979 For printing and sharing of notes, an Org-mode file (or a part of it)
4980 can be exported as a structured ASCII or HTML file.
4982 The following commands are available:
4984 \\{org-mode-map}"
4986 ;; Get rid of Outline menus, they are not needed
4987 ;; Need to do this here because define-derived-mode sets up
4988 ;; the keymap so late. Still, it is a waste to call this each time
4989 ;; we switch another buffer into org-mode.
4990 (if (featurep 'xemacs)
4991 (when (boundp 'outline-mode-menu-heading)
4992 ;; Assume this is Greg's port, it uses easymenu
4993 (easy-menu-remove outline-mode-menu-heading)
4994 (easy-menu-remove outline-mode-menu-show)
4995 (easy-menu-remove outline-mode-menu-hide))
4996 (define-key org-mode-map [menu-bar headings] 'undefined)
4997 (define-key org-mode-map [menu-bar hide] 'undefined)
4998 (define-key org-mode-map [menu-bar show] 'undefined))
5000 (org-load-modules-maybe)
5001 (easy-menu-add org-org-menu)
5002 (easy-menu-add org-tbl-menu)
5003 (org-install-agenda-files-menu)
5004 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5005 (add-to-invisibility-spec '(org-cwidth))
5006 (add-to-invisibility-spec '(org-hide-block . t))
5007 (when (featurep 'xemacs)
5008 (org-set-local 'line-move-ignore-invisible t))
5009 (org-set-local 'outline-regexp org-outline-regexp)
5010 (org-set-local 'outline-level 'org-outline-level)
5011 (setq bidi-paragraph-direction 'left-to-right)
5012 (when (and org-ellipsis
5013 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5014 (fboundp 'make-glyph-code))
5015 (unless org-display-table
5016 (setq org-display-table (make-display-table)))
5017 (set-display-table-slot
5018 org-display-table 4
5019 (vconcat (mapcar
5020 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5021 org-ellipsis)))
5022 (if (stringp org-ellipsis) org-ellipsis "..."))))
5023 (setq buffer-display-table org-display-table))
5024 (org-set-regexps-and-options)
5025 (when (and org-tag-faces (not org-tags-special-faces-re))
5026 ;; tag faces set outside customize.... force initialization.
5027 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5028 ;; Calc embedded
5029 (org-set-local 'calc-embedded-open-mode "# ")
5030 (modify-syntax-entry ?@ "w")
5031 (if org-startup-truncated (setq truncate-lines t))
5032 (org-set-local 'font-lock-unfontify-region-function
5033 'org-unfontify-region)
5034 ;; Activate before-change-function
5035 (org-set-local 'org-table-may-need-update t)
5036 (org-add-hook 'before-change-functions 'org-before-change-function nil
5037 'local)
5038 ;; Check for running clock before killing a buffer
5039 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5040 ;; Paragraphs and auto-filling
5041 (org-set-autofill-regexps)
5042 (org-set-local 'indent-line-function 'org-indent-line)
5043 (org-set-local 'indent-region-function 'org-indent-region)
5044 (org-update-radio-target-regexp)
5045 ;; Beginning/end of defun
5046 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5047 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5048 ;; Next error for sparse trees
5049 (org-set-local 'next-error-function 'org-occur-next-match)
5050 ;; Make sure dependence stuff works reliably, even for users who set it
5051 ;; too late :-(
5052 (if org-enforce-todo-dependencies
5053 (add-hook 'org-blocker-hook
5054 'org-block-todo-from-children-or-siblings-or-parent)
5055 (remove-hook 'org-blocker-hook
5056 'org-block-todo-from-children-or-siblings-or-parent))
5057 (if org-enforce-todo-checkbox-dependencies
5058 (add-hook 'org-blocker-hook
5059 'org-block-todo-from-checkboxes)
5060 (remove-hook 'org-blocker-hook
5061 'org-block-todo-from-checkboxes))
5063 ;; Comment characters
5064 (org-set-local 'comment-start "#")
5065 (org-set-local 'comment-padding " ")
5067 ;; Align options lines
5068 (org-set-local
5069 'align-mode-rules-list
5070 '((org-in-buffer-settings
5071 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5072 (modes . '(org-mode)))))
5074 ;; Imenu
5075 (org-set-local 'imenu-create-index-function
5076 'org-imenu-get-tree)
5078 ;; Make isearch reveal context
5079 (if (or (featurep 'xemacs)
5080 (not (boundp 'outline-isearch-open-invisible-function)))
5081 ;; Emacs 21 and XEmacs make use of the hook
5082 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5083 ;; Emacs 22 deals with this through a special variable
5084 (org-set-local 'outline-isearch-open-invisible-function
5085 (lambda (&rest ignore) (org-show-context 'isearch))))
5087 ;; Turn on org-beamer-mode?
5088 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5090 ;; Setup the pcomplete hooks
5091 (set (make-local-variable 'pcomplete-command-completion-function)
5092 'org-pcomplete-initial)
5093 (set (make-local-variable 'pcomplete-command-name-function)
5094 'org-command-at-point)
5095 (set (make-local-variable 'pcomplete-default-completion-function)
5096 'ignore)
5097 (set (make-local-variable 'pcomplete-parse-arguments-function)
5098 'org-parse-arguments)
5099 (set (make-local-variable 'pcomplete-termination-string) "")
5100 (when (>= emacs-major-version 23)
5101 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5103 ;; If empty file that did not turn on org-mode automatically, make it to.
5104 (if (and org-insert-mode-line-in-empty-file
5105 (org-called-interactively-p 'any)
5106 (= (point-min) (point-max)))
5107 (insert "# -*- mode: org -*-\n\n"))
5108 (unless org-inhibit-startup
5109 (when org-startup-align-all-tables
5110 (let ((bmp (buffer-modified-p)))
5111 (org-table-map-tables 'org-table-align 'quietly)
5112 (set-buffer-modified-p bmp)))
5113 (when org-startup-with-inline-images
5114 (org-display-inline-images))
5115 (when org-startup-indented
5116 (require 'org-indent)
5117 (org-indent-mode 1))
5118 (unless org-inhibit-startup-visibility-stuff
5119 (org-set-startup-visibility))))
5121 (when (fboundp 'abbrev-table-put)
5122 (abbrev-table-put org-mode-abbrev-table
5123 :parents (list text-mode-abbrev-table)))
5125 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5127 (defun org-current-time ()
5128 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5129 (if (> (car org-time-stamp-rounding-minutes) 1)
5130 (let ((r (car org-time-stamp-rounding-minutes))
5131 (time (decode-time)))
5132 (apply 'encode-time
5133 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5134 (nthcdr 2 time))))
5135 (current-time)))
5137 (defun org-today ()
5138 "Return today date, considering `org-extend-today-until'."
5139 (time-to-days
5140 (time-subtract (current-time)
5141 (list 0 (* 3600 org-extend-today-until) 0))))
5143 ;;;; Font-Lock stuff, including the activators
5145 (defvar org-mouse-map (make-sparse-keymap))
5146 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5147 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5148 (when org-mouse-1-follows-link
5149 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5150 (when org-tab-follows-link
5151 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5152 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5154 (require 'font-lock)
5156 (defconst org-non-link-chars "]\t\n\r<>")
5157 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5158 "shell" "elisp" "doi" "message"))
5159 (defvar org-link-types-re nil
5160 "Matches a link that has a url-like prefix like \"http:\"")
5161 (defvar org-link-re-with-space nil
5162 "Matches a link with spaces, optional angular brackets around it.")
5163 (defvar org-link-re-with-space2 nil
5164 "Matches a link with spaces, optional angular brackets around it.")
5165 (defvar org-link-re-with-space3 nil
5166 "Matches a link with spaces, only for internal part in bracket links.")
5167 (defvar org-angle-link-re nil
5168 "Matches link with angular brackets, spaces are allowed.")
5169 (defvar org-plain-link-re nil
5170 "Matches plain link, without spaces.")
5171 (defvar org-bracket-link-regexp nil
5172 "Matches a link in double brackets.")
5173 (defvar org-bracket-link-analytic-regexp nil
5174 "Regular expression used to analyze links.
5175 Here is what the match groups contain after a match:
5176 1: http:
5177 2: http
5178 3: path
5179 4: [desc]
5180 5: desc")
5181 (defvar org-bracket-link-analytic-regexp++ nil
5182 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5183 (defvar org-any-link-re nil
5184 "Regular expression matching any link.")
5186 (defcustom org-match-sexp-depth 3
5187 "Number of stacked braces for sub/superscript matching.
5188 This has to be set before loading org.el to be effective."
5189 :group 'org-export-translation ; ??????????????????????????/
5190 :type 'integer)
5192 (defun org-create-multibrace-regexp (left right n)
5193 "Create a regular expression which will match a balanced sexp.
5194 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5195 as single character strings.
5196 The regexp returned will match the entire expression including the
5197 delimiters. It will also define a single group which contains the
5198 match except for the outermost delimiters. The maximum depth of
5199 stacked delimiters is N. Escaping delimiters is not possible."
5200 (let* ((nothing (concat "[^" left right "]*?"))
5201 (or "\\|")
5202 (re nothing)
5203 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5204 (while (> n 1)
5205 (setq n (1- n)
5206 re (concat re or next)
5207 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5208 (concat left "\\(" re "\\)" right)))
5210 (defvar org-match-substring-regexp
5211 (concat
5212 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5213 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5214 "\\|"
5215 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5216 "\\|"
5217 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5218 "The regular expression matching a sub- or superscript.")
5220 (defvar org-match-substring-with-braces-regexp
5221 (concat
5222 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5223 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5224 "\\)")
5225 "The regular expression matching a sub- or superscript, forcing braces.")
5227 (defun org-make-link-regexps ()
5228 "Update the link regular expressions.
5229 This should be called after the variable `org-link-types' has changed."
5230 (setq org-link-types-re
5231 (concat
5232 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5233 org-link-re-with-space
5234 (concat
5235 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5236 "\\([^" org-non-link-chars " ]"
5237 "[^" org-non-link-chars "]*"
5238 "[^" org-non-link-chars " ]\\)>?")
5239 org-link-re-with-space2
5240 (concat
5241 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5242 "\\([^" org-non-link-chars " ]"
5243 "[^\t\n\r]*"
5244 "[^" org-non-link-chars " ]\\)>?")
5245 org-link-re-with-space3
5246 (concat
5247 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5248 "\\([^" org-non-link-chars " ]"
5249 "[^\t\n\r]*\\)")
5250 org-angle-link-re
5251 (concat
5252 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5253 "\\([^" org-non-link-chars " ]"
5254 "[^" org-non-link-chars "]*"
5255 "\\)>")
5256 org-plain-link-re
5257 (concat
5258 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5259 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5260 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5261 org-bracket-link-regexp
5262 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5263 org-bracket-link-analytic-regexp
5264 (concat
5265 "\\[\\["
5266 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5267 "\\([^]]+\\)"
5268 "\\]"
5269 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5270 "\\]")
5271 org-bracket-link-analytic-regexp++
5272 (concat
5273 "\\[\\["
5274 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5275 "\\([^]]+\\)"
5276 "\\]"
5277 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5278 "\\]")
5279 org-any-link-re
5280 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5281 org-angle-link-re "\\)\\|\\("
5282 org-plain-link-re "\\)")))
5284 (org-make-link-regexps)
5286 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5287 "Regular expression for fast time stamp matching.")
5288 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5289 "Regular expression for fast time stamp matching.")
5290 (defconst org-ts-regexp0
5291 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5292 "Regular expression matching time strings for analysis.
5293 This one does not require the space after the date, so it can be used
5294 on a string that terminates immediately after the date.")
5295 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5296 "Regular expression matching time strings for analysis.")
5297 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5298 "Regular expression matching time stamps, with groups.")
5299 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5300 "Regular expression matching time stamps (also [..]), with groups.")
5301 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5302 "Regular expression matching a time stamp range.")
5303 (defconst org-tr-regexp-both
5304 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5305 "Regular expression matching a time stamp range.")
5306 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5307 org-ts-regexp "\\)?")
5308 "Regular expression matching a time stamp or time stamp range.")
5309 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5310 org-ts-regexp-both "\\)?")
5311 "Regular expression matching a time stamp or time stamp range.
5312 The time stamps may be either active or inactive.")
5314 (defvar org-emph-face nil)
5316 (defun org-do-emphasis-faces (limit)
5317 "Run through the buffer and add overlays to emphasized strings."
5318 (let (rtn a)
5319 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5320 (if (not (= (char-after (match-beginning 3))
5321 (char-after (match-beginning 4))))
5322 (progn
5323 (setq rtn t)
5324 (setq a (assoc (match-string 3) org-emphasis-alist))
5325 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5326 'face
5327 (nth 1 a))
5328 (and (nth 4 a)
5329 (org-remove-flyspell-overlays-in
5330 (match-beginning 0) (match-end 0)))
5331 (add-text-properties (match-beginning 2) (match-end 2)
5332 '(font-lock-multiline t org-emphasis t))
5333 (when org-hide-emphasis-markers
5334 (add-text-properties (match-end 4) (match-beginning 5)
5335 '(invisible org-link))
5336 (add-text-properties (match-beginning 3) (match-end 3)
5337 '(invisible org-link)))))
5338 (backward-char 1))
5339 rtn))
5341 (defun org-emphasize (&optional char)
5342 "Insert or change an emphasis, i.e. a font like bold or italic.
5343 If there is an active region, change that region to a new emphasis.
5344 If there is no region, just insert the marker characters and position
5345 the cursor between them.
5346 CHAR should be either the marker character, or the first character of the
5347 HTML tag associated with that emphasis. If CHAR is a space, the means
5348 to remove the emphasis of the selected region.
5349 If char is not given (for example in an interactive call) it
5350 will be prompted for."
5351 (interactive)
5352 (let ((eal org-emphasis-alist) e det
5353 (erc org-emphasis-regexp-components)
5354 (prompt "")
5355 (string "") beg end move tag c s)
5356 (if (org-region-active-p)
5357 (setq beg (region-beginning) end (region-end)
5358 string (buffer-substring beg end))
5359 (setq move t))
5361 (while (setq e (pop eal))
5362 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5363 c (aref tag 0))
5364 (push (cons c (string-to-char (car e))) det)
5365 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5366 (substring tag 1)))))
5367 (setq det (nreverse det))
5368 (unless char
5369 (message "%s" (concat "Emphasis marker or tag:" prompt))
5370 (setq char (read-char-exclusive)))
5371 (setq char (or (cdr (assoc char det)) char))
5372 (if (equal char ?\ )
5373 (setq s "" move nil)
5374 (unless (assoc (char-to-string char) org-emphasis-alist)
5375 (error "No such emphasis marker: \"%c\"" char))
5376 (setq s (char-to-string char)))
5377 (while (and (> (length string) 1)
5378 (equal (substring string 0 1) (substring string -1))
5379 (assoc (substring string 0 1) org-emphasis-alist))
5380 (setq string (substring string 1 -1)))
5381 (setq string (concat s string s))
5382 (if beg (delete-region beg end))
5383 (unless (or (bolp)
5384 (string-match (concat "[" (nth 0 erc) "\n]")
5385 (char-to-string (char-before (point)))))
5386 (insert " "))
5387 (unless (or (eobp)
5388 (string-match (concat "[" (nth 1 erc) "\n]")
5389 (char-to-string (char-after (point)))))
5390 (insert " ") (backward-char 1))
5391 (insert string)
5392 (and move (backward-char 1))))
5394 (defconst org-nonsticky-props
5395 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5397 (defsubst org-rear-nonsticky-at (pos)
5398 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5400 (defun org-activate-plain-links (limit)
5401 "Run through the buffer and add overlays to links."
5402 (catch 'exit
5403 (let (f)
5404 (if (re-search-forward org-plain-link-re limit t)
5405 (progn
5406 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5407 (setq f (get-text-property (match-beginning 0) 'face))
5408 (if (or (eq f 'org-tag)
5409 (and (listp f) (memq 'org-tag f)))
5411 (add-text-properties (match-beginning 0) (match-end 0)
5412 (list 'mouse-face 'highlight
5413 'face 'org-link
5414 'keymap org-mouse-map))
5415 (org-rear-nonsticky-at (match-end 0)))
5416 t)))))
5418 (defun org-activate-code (limit)
5419 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5420 (progn
5421 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5422 (remove-text-properties (match-beginning 0) (match-end 0)
5423 '(display t invisible t intangible t))
5424 t)))
5426 (defcustom org-src-fontify-natively nil
5427 "When non-nil, fontify code in code blocks."
5428 :type 'boolean
5429 :version "24.1"
5430 :group 'org-appearance
5431 :group 'org-babel)
5433 (defcustom org-src-prevent-auto-filling nil
5434 "When non-nil, prevent auto-filling in src blocks."
5435 :type 'boolean
5436 :version "24.1"
5437 :group 'org-appearance
5438 :group 'org-babel)
5440 (defcustom org-allow-promoting-top-level-subtree nil
5441 "When non-nil, allow promoting a top level subtree.
5442 The leading star of the top level headline will be replaced
5443 by a #."
5444 :type 'boolean
5445 :version "24.1"
5446 :group 'org-appearance)
5448 (defun org-fontify-meta-lines-and-blocks (limit)
5449 (condition-case nil
5450 (org-fontify-meta-lines-and-blocks-1 limit)
5451 (error (message "org-mode fontification error"))))
5453 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5454 "Fontify #+ lines and blocks, in the correct ways."
5455 (let ((case-fold-search t))
5456 (if (re-search-forward
5457 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5458 limit t)
5459 (let ((beg (match-beginning 0))
5460 (block-start (match-end 0))
5461 (block-end nil)
5462 (lang (match-string 7))
5463 (beg1 (line-beginning-position 2))
5464 (dc1 (downcase (match-string 2)))
5465 (dc3 (downcase (match-string 3)))
5466 end end1 quoting block-type ovl)
5467 (cond
5468 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5469 ;; a single line of backend-specific content
5470 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5471 (remove-text-properties (match-beginning 0) (match-end 0)
5472 '(display t invisible t intangible t))
5473 (add-text-properties (match-beginning 1) (match-end 3)
5474 '(font-lock-fontified t face org-meta-line))
5475 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5476 '(font-lock-fontified t face org-block))
5477 ; for backend-specific code
5479 ((and (match-end 4) (equal dc3 "begin"))
5480 ;; Truly a block
5481 (setq block-type (downcase (match-string 5))
5482 quoting (member block-type org-protecting-blocks))
5483 (when (re-search-forward
5484 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5485 nil t) ;; on purpose, we look further than LIMIT
5486 (setq end (min (point-max) (match-end 0))
5487 end1 (min (point-max) (1- (match-beginning 0))))
5488 (setq block-end (match-beginning 0))
5489 (when quoting
5490 (remove-text-properties beg end
5491 '(display t invisible t intangible t)))
5492 (add-text-properties
5493 beg end
5494 '(font-lock-fontified t font-lock-multiline t))
5495 (add-text-properties beg beg1 '(face org-meta-line))
5496 (add-text-properties end1 (min (point-max) (1+ end))
5497 '(face org-meta-line)) ; for end_src
5498 (cond
5499 ((and lang (not (string= lang "")) org-src-fontify-natively)
5500 (org-src-font-lock-fontify-block lang block-start block-end)
5501 ;; remove old background overlays
5502 (mapc (lambda (ov)
5503 (if (eq (overlay-get ov 'face) 'org-block-background)
5504 (delete-overlay ov)))
5505 (overlays-at (/ (+ beg1 block-end) 2)))
5506 ;; add a background overlay
5507 (setq ovl (make-overlay beg1 block-end))
5508 (overlay-put ovl 'face 'org-block-background)
5509 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5510 (quoting
5511 (add-text-properties beg1 (min (point-max) (1+ end1))
5512 '(face org-block))) ; end of source block
5513 ((not org-fontify-quote-and-verse-blocks))
5514 ((string= block-type "quote")
5515 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5516 ((string= block-type "verse")
5517 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5518 (add-text-properties beg beg1 '(face org-block-begin-line))
5519 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5520 '(face org-block-end-line))
5522 ((member dc1 '("title:" "author:" "email:" "date:"))
5523 (add-text-properties
5524 beg (match-end 3)
5525 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5526 '(font-lock-fontified t invisible t)
5527 '(font-lock-fontified t face org-document-info-keyword)))
5528 (add-text-properties
5529 (match-beginning 6) (match-end 6)
5530 (if (string-equal dc1 "title:")
5531 '(font-lock-fontified t face org-document-title)
5532 '(font-lock-fontified t face org-document-info))))
5533 ((not (member (char-after beg) '(?\ ?\t)))
5534 ;; just any other in-buffer setting, but not indented
5535 (add-text-properties
5536 beg (match-end 0)
5537 '(font-lock-fontified t face org-meta-line))
5539 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5540 "orgtbl:" "tblfm:" "tblname:" "results:"
5541 "call:" "header:" "headers:" "name:"))
5542 (and (match-end 4) (equal dc3 "attr")))
5543 (add-text-properties
5544 beg (match-end 0)
5545 '(font-lock-fontified t face org-meta-line))
5547 ((member dc3 '(" " ""))
5548 (add-text-properties
5549 beg (match-end 0)
5550 '(font-lock-fontified t face font-lock-comment-face)))
5551 (t nil))))))
5553 (defun org-strip-protective-commas (beg end)
5554 "Strip protective commas between BEG and END in the current buffer."
5555 (interactive "r")
5556 (save-excursion
5557 (save-match-data
5558 (goto-char beg)
5559 (let ((front-line (save-excursion
5560 (re-search-forward
5561 "[^[:space:]]" end t)
5562 (goto-char (match-beginning 0))
5563 (current-column))))
5564 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5565 (goto-char (match-beginning 1))
5566 (when (= (current-column) front-line)
5567 (replace-match "" nil nil nil 1)))))))
5569 (defun org-activate-angle-links (limit)
5570 "Run through the buffer and add overlays to links."
5571 (if (re-search-forward org-angle-link-re limit t)
5572 (progn
5573 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5574 (add-text-properties (match-beginning 0) (match-end 0)
5575 (list 'mouse-face 'highlight
5576 'keymap org-mouse-map))
5577 (org-rear-nonsticky-at (match-end 0))
5578 t)))
5580 (defun org-activate-footnote-links (limit)
5581 "Run through the buffer and add overlays to footnotes."
5582 (let ((fn (org-footnote-next-reference-or-definition limit)))
5583 (when fn
5584 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5585 (org-remove-flyspell-overlays-in beg end)
5586 (add-text-properties beg end
5587 (list 'mouse-face 'highlight
5588 'keymap org-mouse-map
5589 'help-echo
5590 (if (= (point-at-bol) beg)
5591 "Footnote definition"
5592 "Footnote reference")
5593 'font-lock-fontified t
5594 'font-lock-multiline t
5595 'face 'org-footnote))))))
5597 (defun org-activate-bracket-links (limit)
5598 "Run through the buffer and add overlays to bracketed links."
5599 (if (re-search-forward org-bracket-link-regexp limit t)
5600 (let* ((help (concat "LINK: "
5601 (org-match-string-no-properties 1)))
5602 ;; FIXME: above we should remove the escapes.
5603 ;; but that requires another match, protecting match data,
5604 ;; a lot of overhead for font-lock.
5605 (ip (org-maybe-intangible
5606 (list 'invisible 'org-link
5607 'keymap org-mouse-map 'mouse-face 'highlight
5608 'font-lock-multiline t 'help-echo help)))
5609 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5610 'font-lock-multiline t 'help-echo help)))
5611 ;; We need to remove the invisible property here. Table narrowing
5612 ;; may have made some of this invisible.
5613 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5614 (remove-text-properties (match-beginning 0) (match-end 0)
5615 '(invisible nil))
5616 (if (match-end 3)
5617 (progn
5618 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5619 (org-rear-nonsticky-at (match-beginning 3))
5620 (add-text-properties (match-beginning 3) (match-end 3) vp)
5621 (org-rear-nonsticky-at (match-end 3))
5622 (add-text-properties (match-end 3) (match-end 0) ip)
5623 (org-rear-nonsticky-at (match-end 0)))
5624 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5625 (org-rear-nonsticky-at (match-beginning 1))
5626 (add-text-properties (match-beginning 1) (match-end 1) vp)
5627 (org-rear-nonsticky-at (match-end 1))
5628 (add-text-properties (match-end 1) (match-end 0) ip)
5629 (org-rear-nonsticky-at (match-end 0)))
5630 t)))
5632 (defun org-activate-dates (limit)
5633 "Run through the buffer and add overlays to dates."
5634 (if (re-search-forward org-tsr-regexp-both limit t)
5635 (progn
5636 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5637 (add-text-properties (match-beginning 0) (match-end 0)
5638 (list 'mouse-face 'highlight
5639 'keymap org-mouse-map))
5640 (org-rear-nonsticky-at (match-end 0))
5641 (when org-display-custom-times
5642 (if (match-end 3)
5643 (org-display-custom-time (match-beginning 3) (match-end 3)))
5644 (org-display-custom-time (match-beginning 1) (match-end 1)))
5645 t)))
5647 (defvar org-target-link-regexp nil
5648 "Regular expression matching radio targets in plain text.")
5649 (make-variable-buffer-local 'org-target-link-regexp)
5650 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5651 "Regular expression matching a link target.")
5652 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5653 "Regular expression matching a radio target.")
5654 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5655 "Regular expression matching any target.")
5657 (defun org-activate-target-links (limit)
5658 "Run through the buffer and add overlays to target matches."
5659 (when org-target-link-regexp
5660 (let ((case-fold-search t))
5661 (if (re-search-forward org-target-link-regexp limit t)
5662 (progn
5663 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5664 (add-text-properties (match-beginning 0) (match-end 0)
5665 (list 'mouse-face 'highlight
5666 'keymap org-mouse-map
5667 'help-echo "Radio target link"
5668 'org-linked-text t))
5669 (org-rear-nonsticky-at (match-end 0))
5670 t)))))
5672 (defun org-update-radio-target-regexp ()
5673 "Find all radio targets in this file and update the regular expression."
5674 (interactive)
5675 (when (memq 'radio org-activate-links)
5676 (setq org-target-link-regexp
5677 (org-make-target-link-regexp (org-all-targets 'radio)))
5678 (org-restart-font-lock)))
5680 (defun org-hide-wide-columns (limit)
5681 (let (s e)
5682 (setq s (text-property-any (point) (or limit (point-max))
5683 'org-cwidth t))
5684 (when s
5685 (setq e (next-single-property-change s 'org-cwidth))
5686 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5687 (goto-char e)
5688 t)))
5690 (defvar org-latex-and-specials-regexp nil
5691 "Regular expression for highlighting export special stuff.")
5692 (defvar org-match-substring-regexp)
5693 (defvar org-match-substring-with-braces-regexp)
5695 ;; This should be with the exporter code, but we also use if for font-locking
5696 (defconst org-export-html-special-string-regexps
5697 '(("\\\\-" . "&shy;")
5698 ("---\\([^-]\\)" . "&mdash;\\1")
5699 ("--\\([^-]\\)" . "&ndash;\\1")
5700 ("\\.\\.\\." . "&hellip;"))
5701 "Regular expressions for special string conversion.")
5704 (defun org-compute-latex-and-specials-regexp ()
5705 "Compute regular expression for stuff treated specially by exporters."
5706 (if (not org-highlight-latex-fragments-and-specials)
5707 (org-set-local 'org-latex-and-specials-regexp nil)
5708 (require 'org-exp)
5709 (let*
5710 ((matchers (plist-get org-format-latex-options :matchers))
5711 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5712 org-latex-regexps)))
5713 (org-export-allow-BIND nil)
5714 (options (org-combine-plists (org-default-export-plist)
5715 (org-infile-export-plist)))
5716 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5717 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5718 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5719 (org-export-html-expand (plist-get options :expand-quoted-html))
5720 (org-export-with-special-strings (plist-get options :special-strings))
5721 (re-sub
5722 (cond
5723 ((equal org-export-with-sub-superscripts '{})
5724 (list org-match-substring-with-braces-regexp))
5725 (org-export-with-sub-superscripts
5726 (list org-match-substring-regexp))
5727 (t nil)))
5728 (re-latex
5729 (if org-export-with-LaTeX-fragments
5730 (mapcar (lambda (x) (nth 1 x)) latexs)))
5731 (re-macros
5732 (if org-export-with-TeX-macros
5733 (list (concat "\\\\"
5734 (regexp-opt
5735 (append
5737 (delq nil
5738 (mapcar 'car-safe
5739 (append org-entities-user
5740 org-entities)))
5741 (if (boundp 'org-latex-entities)
5742 (mapcar (lambda (x)
5743 (or (car-safe x) x))
5744 org-latex-entities)
5745 nil))
5746 'words))) ; FIXME
5748 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5749 (re-special (if org-export-with-special-strings
5750 (mapcar (lambda (x) (car x))
5751 org-export-html-special-string-regexps)))
5752 (re-rest
5753 (delq nil
5754 (list
5755 (if org-export-html-expand "@<[^>\n]+>")
5756 ))))
5757 (org-set-local
5758 'org-latex-and-specials-regexp
5759 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5760 re-rest) "\\|")))))
5762 (defun org-do-latex-and-special-faces (limit)
5763 "Run through the buffer and add overlays to links."
5764 (when org-latex-and-specials-regexp
5765 (let (rtn d)
5766 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5767 limit t))
5768 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5769 'face))
5770 '(org-code org-verbatim underline)))
5771 (progn
5772 (setq rtn t
5773 d (cond ((member (char-after (1+ (match-beginning 0)))
5774 '(?_ ?^)) 1)
5775 (t 0)))
5776 (font-lock-prepend-text-property
5777 (+ d (match-beginning 0)) (match-end 0)
5778 'face 'org-latex-and-export-specials)
5779 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5780 '(font-lock-multiline t)))))
5781 rtn)))
5783 (defun org-restart-font-lock ()
5784 "Restart `font-lock-mode', to force refontification."
5785 (when (and (boundp 'font-lock-mode) font-lock-mode)
5786 (font-lock-mode -1)
5787 (font-lock-mode 1)))
5789 (defun org-all-targets (&optional radio)
5790 "Return a list of all targets in this file.
5791 With optional argument RADIO, only find radio targets."
5792 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5793 rtn)
5794 (save-excursion
5795 (goto-char (point-min))
5796 (while (re-search-forward re nil t)
5797 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5798 rtn)))
5800 (defun org-make-target-link-regexp (targets)
5801 "Make regular expression matching all strings in TARGETS.
5802 The regular expression finds the targets also if there is a line break
5803 between words."
5804 (and targets
5805 (concat
5806 "\\<\\("
5807 (mapconcat
5808 (lambda (x)
5809 (setq x (regexp-quote x))
5810 (while (string-match " +" x)
5811 (setq x (replace-match "\\s-+" t t x)))
5813 targets
5814 "\\|")
5815 "\\)\\>")))
5817 (defun org-activate-tags (limit)
5818 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5819 (progn
5820 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5821 (add-text-properties (match-beginning 1) (match-end 1)
5822 (list 'mouse-face 'highlight
5823 'keymap org-mouse-map))
5824 (org-rear-nonsticky-at (match-end 1))
5825 t)))
5827 (defun org-outline-level ()
5828 "Compute the outline level of the heading at point.
5829 This function assumes that the cursor is at the beginning of a line matched
5830 by `outline-regexp'. Otherwise it returns garbage.
5831 If this is called at a normal headline, the level is the number of stars.
5832 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5833 (save-excursion
5834 (looking-at org-outline-regexp)
5835 (1- (- (match-end 0) (match-beginning 0)))))
5837 (defvar org-font-lock-keywords nil)
5839 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5840 "Regular expression matching a property line.")
5842 (defvar org-font-lock-hook nil
5843 "Functions to be called for special font lock stuff.")
5845 (defvar org-font-lock-set-keywords-hook nil
5846 "Functions that can manipulate `org-font-lock-extra-keywords'.
5847 This is called after `org-font-lock-extra-keywords' is defined, but before
5848 it is installed to be used by font lock. This can be useful if something
5849 needs to be inserted at a specific position in the font-lock sequence.")
5851 (defun org-font-lock-hook (limit)
5852 (run-hook-with-args 'org-font-lock-hook limit))
5854 (defun org-set-font-lock-defaults ()
5855 (let* ((em org-fontify-emphasized-text)
5856 (lk org-activate-links)
5857 (org-font-lock-extra-keywords
5858 (list
5859 ;; Call the hook
5860 '(org-font-lock-hook)
5861 ;; Headlines
5862 `(,(if org-fontify-whole-heading-line
5863 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5864 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5865 (1 (org-get-level-face 1))
5866 (2 (org-get-level-face 2))
5867 (3 (org-get-level-face 3)))
5868 ;; Table lines
5869 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5870 (1 'org-table t))
5871 ;; Table internals
5872 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5873 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5874 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5875 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5876 ;; Drawers
5877 (list org-drawer-regexp '(0 'org-special-keyword t))
5878 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5879 ;; Properties
5880 (list org-property-re
5881 '(1 'org-special-keyword t)
5882 '(3 'org-property-value t))
5883 ;; Links
5884 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5885 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5886 (if (memq 'plain lk) '(org-activate-plain-links))
5887 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5888 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5889 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5890 (if (memq 'footnote lk) '(org-activate-footnote-links))
5891 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5892 '(org-hide-wide-columns (0 nil append))
5893 ;; TODO keyword
5894 (list (format org-heading-keyword-regexp-format
5895 org-todo-regexp)
5896 '(2 (org-get-todo-face 2) t))
5897 ;; DONE
5898 (if org-fontify-done-headline
5899 (list (format org-heading-keyword-regexp-format
5900 (concat
5901 "\\(?:"
5902 (mapconcat 'regexp-quote org-done-keywords "\\|")
5903 "\\)"))
5904 '(2 'org-headline-done t))
5905 nil)
5906 ;; Priorities
5907 '(org-font-lock-add-priority-faces)
5908 ;; Tags
5909 '(org-font-lock-add-tag-faces)
5910 ;; Special keywords
5911 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5912 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5913 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5914 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5915 ;; Emphasis
5916 (if em
5917 (if (featurep 'xemacs)
5918 '(org-do-emphasis-faces (0 nil append))
5919 '(org-do-emphasis-faces)))
5920 ;; Checkboxes
5921 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5922 1 'org-checkbox prepend)
5923 (if (cdr (assq 'checkbox org-list-automatic-rules))
5924 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5925 (0 (org-get-checkbox-statistics-face) t)))
5926 ;; Description list items
5927 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5928 1 'org-list-dt prepend)
5929 ;; ARCHIVEd headings
5930 (list (concat
5931 org-outline-regexp-bol
5932 "\\(.*:" org-archive-tag ":.*\\)")
5933 '(1 'org-archived prepend))
5934 ;; Specials
5935 '(org-do-latex-and-special-faces)
5936 '(org-fontify-entities)
5937 '(org-raise-scripts)
5938 ;; Code
5939 '(org-activate-code (1 'org-code t))
5940 ;; COMMENT
5941 (list (format org-heading-keyword-regexp-format
5942 (concat "\\("
5943 org-comment-string "\\|" org-quote-string
5944 "\\)"))
5945 '(2 'org-special-keyword t))
5946 '("^#.*" (0 'font-lock-comment-face t))
5947 ;; Blocks and meta lines
5948 '(org-fontify-meta-lines-and-blocks)
5950 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5951 (run-hooks 'org-font-lock-set-keywords-hook)
5952 ;; Now set the full font-lock-keywords
5953 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5954 (org-set-local 'font-lock-defaults
5955 '(org-font-lock-keywords t nil nil backward-paragraph))
5956 (kill-local-variable 'font-lock-keywords) nil))
5958 (defun org-toggle-pretty-entities ()
5959 "Toggle the composition display of entities as UTF8 characters."
5960 (interactive)
5961 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5962 (org-restart-font-lock)
5963 (if org-pretty-entities
5964 (message "Entities are displayed as UTF8 characters")
5965 (save-restriction
5966 (widen)
5967 (org-decompose-region (point-min) (point-max))
5968 (message "Entities are displayed plain"))))
5970 (defun org-fontify-entities (limit)
5971 "Find an entity to fontify."
5972 (let (ee)
5973 (when org-pretty-entities
5974 (catch 'match
5975 (while (re-search-forward
5976 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5977 limit t)
5978 (if (and (not (org-in-indented-comment-line))
5979 (setq ee (org-entity-get (match-string 1)))
5980 (= (length (nth 6 ee)) 1))
5981 (let*
5982 ((end (if (equal (match-string 2) "{}")
5983 (match-end 2)
5984 (match-end 1))))
5985 (add-text-properties
5986 (match-beginning 0) end
5987 (list 'font-lock-fontified t))
5988 (compose-region (match-beginning 0) end
5989 (nth 6 ee) nil)
5990 (backward-char 1)
5991 (throw 'match t))))
5992 nil))))
5994 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5995 "Fontify string S like in Org-mode."
5996 (with-temp-buffer
5997 (insert s)
5998 (let ((org-odd-levels-only odd-levels))
5999 (org-mode)
6000 (font-lock-fontify-buffer)
6001 (buffer-string))))
6003 (defvar org-m nil)
6004 (defvar org-l nil)
6005 (defvar org-f nil)
6006 (defun org-get-level-face (n)
6007 "Get the right face for match N in font-lock matching of headlines."
6008 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6009 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6010 (if org-cycle-level-faces
6011 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6012 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6013 (cond
6014 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6015 ((eq n 2) org-f)
6016 (t (if org-level-color-stars-only nil org-f))))
6019 (defun org-get-todo-face (kwd)
6020 "Get the right face for a TODO keyword KWD.
6021 If KWD is a number, get the corresponding match group."
6022 (if (numberp kwd) (setq kwd (match-string kwd)))
6023 (or (org-face-from-face-or-color
6024 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6025 (and (member kwd org-done-keywords) 'org-done)
6026 'org-todo))
6028 (defun org-face-from-face-or-color (context inherit face-or-color)
6029 "Create a face list that inherits INHERIT, but sets the foreground color.
6030 When FACE-OR-COLOR is not a string, just return it."
6031 (if (stringp face-or-color)
6032 (list :inherit inherit
6033 (cdr (assoc context org-faces-easy-properties))
6034 face-or-color)
6035 face-or-color))
6037 (defun org-font-lock-add-tag-faces (limit)
6038 "Add the special tag faces."
6039 (when (and org-tag-faces org-tags-special-faces-re)
6040 (while (re-search-forward org-tags-special-faces-re limit t)
6041 (add-text-properties (match-beginning 1) (match-end 1)
6042 (list 'face (org-get-tag-face 1)
6043 'font-lock-fontified t))
6044 (backward-char 1))))
6046 (defun org-font-lock-add-priority-faces (limit)
6047 "Add the special priority faces."
6048 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6049 (when (save-match-data (org-at-heading-p))
6050 (add-text-properties
6051 (match-beginning 0) (match-end 0)
6052 (list 'face (or (org-face-from-face-or-color
6053 'priority 'org-special-keyword
6054 (cdr (assoc (char-after (match-beginning 1))
6055 org-priority-faces)))
6056 'org-special-keyword)
6057 'font-lock-fontified t)))))
6059 (defun org-get-tag-face (kwd)
6060 "Get the right face for a TODO keyword KWD.
6061 If KWD is a number, get the corresponding match group."
6062 (if (numberp kwd) (setq kwd (match-string kwd)))
6063 (or (org-face-from-face-or-color
6064 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6065 'org-tag))
6067 (defun org-unfontify-region (beg end &optional maybe_loudly)
6068 "Remove fontification and activation overlays from links."
6069 (font-lock-default-unfontify-region beg end)
6070 (let* ((buffer-undo-list t)
6071 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6072 (inhibit-modification-hooks t)
6073 deactivate-mark buffer-file-name buffer-file-truename)
6074 (org-decompose-region beg end)
6075 (remove-text-properties beg end
6076 '(mouse-face t keymap t org-linked-text t
6077 invisible t intangible t
6078 org-no-flyspell t org-emphasis t))
6079 (org-remove-font-lock-display-properties beg end)))
6081 (defconst org-script-display '(((raise -0.3) (height 0.7))
6082 ((raise 0.3) (height 0.7))
6083 ((raise -0.5))
6084 ((raise 0.5)))
6085 "Display properties for showing superscripts and subscripts.")
6087 (defun org-remove-font-lock-display-properties (beg end)
6088 "Remove specific display properties that have been added by font lock.
6089 The will remove the raise properties that are used to show superscripts
6090 and subscripts."
6091 (let (next prop)
6092 (while (< beg end)
6093 (setq next (next-single-property-change beg 'display nil end)
6094 prop (get-text-property beg 'display))
6095 (if (member prop org-script-display)
6096 (put-text-property beg next 'display nil))
6097 (setq beg next))))
6099 (defun org-raise-scripts (limit)
6100 "Add raise properties to sub/superscripts."
6101 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6102 (if (re-search-forward
6103 (if (eq org-use-sub-superscripts t)
6104 org-match-substring-regexp
6105 org-match-substring-with-braces-regexp)
6106 limit t)
6107 (let* ((pos (point)) table-p comment-p
6108 (mpos (match-beginning 3))
6109 (emph-p (get-text-property mpos 'org-emphasis))
6110 (link-p (get-text-property mpos 'mouse-face))
6111 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6112 (goto-char (point-at-bol))
6113 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6114 comment-p (org-looking-at-p "[ \t]*#"))
6115 (goto-char pos)
6116 ;; FIXME: Should we go back one character here, for a_b^c
6117 ;; (goto-char (1- pos)) ;????????????????????
6118 (if (or comment-p emph-p link-p keyw-p)
6120 (put-text-property (match-beginning 3) (match-end 0)
6121 'display
6122 (if (equal (char-after (match-beginning 2)) ?^)
6123 (nth (if table-p 3 1) org-script-display)
6124 (nth (if table-p 2 0) org-script-display)))
6125 (add-text-properties (match-beginning 2) (match-end 2)
6126 (list 'invisible t
6127 'org-dwidth t 'org-dwidth-n 1))
6128 (if (and (eq (char-after (match-beginning 3)) ?{)
6129 (eq (char-before (match-end 3)) ?}))
6130 (progn
6131 (add-text-properties
6132 (match-beginning 3) (1+ (match-beginning 3))
6133 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6134 (add-text-properties
6135 (1- (match-end 3)) (match-end 3)
6136 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6137 t)))))
6139 ;;;; Visibility cycling, including org-goto and indirect buffer
6141 ;;; Cycling
6143 (defvar org-cycle-global-status nil)
6144 (make-variable-buffer-local 'org-cycle-global-status)
6145 (defvar org-cycle-subtree-status nil)
6146 (make-variable-buffer-local 'org-cycle-subtree-status)
6148 ;;;###autoload
6150 (defvar org-inlinetask-min-level)
6152 (defun org-cycle (&optional arg)
6153 "TAB-action and visibility cycling for Org-mode.
6155 This is the command invoked in Org-mode by the TAB key. Its main purpose
6156 is outline visibility cycling, but it also invokes other actions
6157 in special contexts.
6159 - When this function is called with a prefix argument, rotate the entire
6160 buffer through 3 states (global cycling)
6161 1. OVERVIEW: Show only top-level headlines.
6162 2. CONTENTS: Show all headlines of all levels, but no body text.
6163 3. SHOW ALL: Show everything.
6164 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6165 determined by the variable `org-startup-folded', and by any VISIBILITY
6166 properties in the buffer.
6167 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6168 including any drawers.
6170 - When inside a table, re-align the table and move to the next field.
6172 - When point is at the beginning of a headline, rotate the subtree started
6173 by this line through 3 different states (local cycling)
6174 1. FOLDED: Only the main headline is shown.
6175 2. CHILDREN: The main headline and the direct children are shown.
6176 From this state, you can move to one of the children
6177 and zoom in further.
6178 3. SUBTREE: Show the entire subtree, including body text.
6179 If there is no subtree, switch directly from CHILDREN to FOLDED.
6181 - When point is at the beginning of an empty headline and the variable
6182 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6183 of the headline by demoting and promoting it to likely levels. This
6184 speeds up creation document structure by pressing TAB once or several
6185 times right after creating a new headline.
6187 - When there is a numeric prefix, go up to a heading with level ARG, do
6188 a `show-subtree' and return to the previous cursor position. If ARG
6189 is negative, go up that many levels.
6191 - When point is not at the beginning of a headline, execute the global
6192 binding for TAB, which is re-indenting the line. See the option
6193 `org-cycle-emulate-tab' for details.
6195 - Special case: if point is at the beginning of the buffer and there is
6196 no headline in line 1, this function will act as if called with prefix arg
6197 (C-u TAB, same as S-TAB) also when called without prefix arg.
6198 But only if also the variable `org-cycle-global-at-bob' is t."
6199 (interactive "P")
6200 (org-load-modules-maybe)
6201 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6202 (and org-cycle-level-after-item/entry-creation
6203 (or (org-cycle-level)
6204 (org-cycle-item-indentation))))
6205 (let* ((limit-level
6206 (or org-cycle-max-level
6207 (and (boundp 'org-inlinetask-min-level)
6208 org-inlinetask-min-level
6209 (1- org-inlinetask-min-level))))
6210 (nstars (and limit-level
6211 (if org-odd-levels-only
6212 (and limit-level (1- (* limit-level 2)))
6213 limit-level)))
6214 (org-outline-regexp
6215 (if (not (derived-mode-p 'org-mode))
6216 outline-regexp
6217 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6218 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6219 (not (looking-at org-outline-regexp))))
6220 (org-cycle-hook
6221 (if bob-special
6222 (delq 'org-optimize-window-after-visibility-change
6223 (copy-sequence org-cycle-hook))
6224 org-cycle-hook))
6225 (pos (point)))
6227 (if (or bob-special (equal arg '(4)))
6228 ;; special case: use global cycling
6229 (setq arg t))
6231 (cond
6233 ((equal arg '(16))
6234 (setq last-command 'dummy)
6235 (org-set-startup-visibility)
6236 (message "Startup visibility, plus VISIBILITY properties"))
6238 ((equal arg '(64))
6239 (show-all)
6240 (message "Entire buffer visible, including drawers"))
6242 ;; Table: enter it or move to the next field.
6243 ((org-at-table-p 'any)
6244 (if (org-at-table.el-p)
6245 (message "Use C-c ' to edit table.el tables")
6246 (if arg (org-table-edit-field t)
6247 (org-table-justify-field-maybe)
6248 (call-interactively 'org-table-next-field))))
6250 ((run-hook-with-args-until-success
6251 'org-tab-after-check-for-table-hook))
6253 ;; Global cycling: delegate to `org-cycle-internal-global'.
6254 ((eq arg t) (org-cycle-internal-global))
6256 ;; Drawers: delegate to `org-flag-drawer'.
6257 ((and org-drawers org-drawer-regexp
6258 (save-excursion
6259 (beginning-of-line 1)
6260 (looking-at org-drawer-regexp)))
6261 (org-flag-drawer ; toggle block visibility
6262 (not (get-char-property (match-end 0) 'invisible))))
6264 ;; Show-subtree, ARG levels up from here.
6265 ((integerp arg)
6266 (save-excursion
6267 (org-back-to-heading)
6268 (outline-up-heading (if (< arg 0) (- arg)
6269 (- (funcall outline-level) arg)))
6270 (org-show-subtree)))
6272 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6273 ((and (featurep 'org-inlinetask)
6274 (org-inlinetask-at-task-p)
6275 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6276 (org-inlinetask-toggle-visibility))
6278 ((org-try-cdlatex-tab))
6280 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6281 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6282 (save-excursion (beginning-of-line 1)
6283 (looking-at org-outline-regexp)))
6284 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6285 (org-cycle-internal-local))
6287 ;; From there: TAB emulation and template completion.
6288 (buffer-read-only (org-back-to-heading))
6290 ((run-hook-with-args-until-success
6291 'org-tab-after-check-for-cycling-hook))
6293 ((org-try-structure-completion))
6295 ((run-hook-with-args-until-success
6296 'org-tab-before-tab-emulation-hook))
6298 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6299 (or (not (bolp))
6300 (not (looking-at org-outline-regexp))))
6301 (call-interactively (global-key-binding "\t")))
6303 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6304 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6305 (or (and (eq org-cycle-emulate-tab 'white)
6306 (= (match-end 0) (point-at-eol)))
6307 (and (eq org-cycle-emulate-tab 'whitestart)
6308 (>= (match-end 0) pos))))
6310 (eq org-cycle-emulate-tab t))
6311 (call-interactively (global-key-binding "\t")))
6313 (t (save-excursion
6314 (org-back-to-heading)
6315 (org-cycle)))))))
6317 (defun org-cycle-internal-global ()
6318 "Do the global cycling action."
6319 ;; Hack to avoid display of messages for .org attachments in Gnus
6320 (let ((ga (string-match "\\*fontification" (buffer-name))))
6321 (cond
6322 ((and (eq last-command this-command)
6323 (eq org-cycle-global-status 'overview))
6324 ;; We just created the overview - now do table of contents
6325 ;; This can be slow in very large buffers, so indicate action
6326 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6327 (unless ga (message "CONTENTS..."))
6328 (org-content)
6329 (unless ga (message "CONTENTS...done"))
6330 (setq org-cycle-global-status 'contents)
6331 (run-hook-with-args 'org-cycle-hook 'contents))
6333 ((and (eq last-command this-command)
6334 (eq org-cycle-global-status 'contents))
6335 ;; We just showed the table of contents - now show everything
6336 (run-hook-with-args 'org-pre-cycle-hook 'all)
6337 (show-all)
6338 (unless ga (message "SHOW ALL"))
6339 (setq org-cycle-global-status 'all)
6340 (run-hook-with-args 'org-cycle-hook 'all))
6343 ;; Default action: go to overview
6344 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6345 (org-overview)
6346 (unless ga (message "OVERVIEW"))
6347 (setq org-cycle-global-status 'overview)
6348 (run-hook-with-args 'org-cycle-hook 'overview)))))
6350 (defun org-cycle-internal-local ()
6351 "Do the local cycling action."
6352 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6353 ;; First, determine end of headline (EOH), end of subtree or item
6354 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6355 (save-excursion
6356 (if (org-at-item-p)
6357 (progn
6358 (beginning-of-line)
6359 (setq struct (org-list-struct))
6360 (setq eoh (point-at-eol))
6361 (setq eos (org-list-get-item-end-before-blank (point) struct))
6362 (setq has-children (org-list-has-child-p (point) struct)))
6363 (org-back-to-heading)
6364 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6365 (setq eos (save-excursion
6366 (org-end-of-subtree t)
6367 (unless (eobp)
6368 (skip-chars-forward " \t\n"))
6369 (if (eobp) (point) (1- (point)))))
6370 (setq has-children
6371 (or (save-excursion
6372 (let ((level (funcall outline-level)))
6373 (outline-next-heading)
6374 (and (org-at-heading-p t)
6375 (> (funcall outline-level) level))))
6376 (save-excursion
6377 (org-list-search-forward (org-item-beginning-re) eos t)))))
6378 ;; Determine end invisible part of buffer (EOL)
6379 (beginning-of-line 2)
6380 ;; XEmacs doesn't have `next-single-char-property-change'
6381 (if (featurep 'xemacs)
6382 (while (and (not (eobp)) ;; this is like `next-line'
6383 (get-char-property (1- (point)) 'invisible))
6384 (beginning-of-line 2))
6385 (while (and (not (eobp)) ;; this is like `next-line'
6386 (get-char-property (1- (point)) 'invisible))
6387 (goto-char (next-single-char-property-change (point) 'invisible))
6388 (and (eolp) (beginning-of-line 2))))
6389 (setq eol (point)))
6390 ;; Find out what to do next and set `this-command'
6391 (cond
6392 ((= eos eoh)
6393 ;; Nothing is hidden behind this heading
6394 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6395 (message "EMPTY ENTRY")
6396 (setq org-cycle-subtree-status nil)
6397 (save-excursion
6398 (goto-char eos)
6399 (outline-next-heading)
6400 (if (outline-invisible-p) (org-flag-heading nil))))
6401 ((and (or (>= eol eos)
6402 (not (string-match "\\S-" (buffer-substring eol eos))))
6403 (or has-children
6404 (not (setq children-skipped
6405 org-cycle-skip-children-state-if-no-children))))
6406 ;; Entire subtree is hidden in one line: children view
6407 (run-hook-with-args 'org-pre-cycle-hook 'children)
6408 (if (org-at-item-p)
6409 (org-list-set-item-visibility (point-at-bol) struct 'children)
6410 (org-show-entry)
6411 (org-with-limited-levels (show-children))
6412 ;; FIXME: This slows down the func way too much.
6413 ;; How keep drawers hidden in subtree anyway?
6414 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6415 ;; (org-cycle-hide-drawers 'subtree))
6417 ;; Fold every list in subtree to top-level items.
6418 (when (eq org-cycle-include-plain-lists 'integrate)
6419 (save-excursion
6420 (org-back-to-heading)
6421 (while (org-list-search-forward (org-item-beginning-re) eos t)
6422 (beginning-of-line 1)
6423 (let* ((struct (org-list-struct))
6424 (prevs (org-list-prevs-alist struct))
6425 (end (org-list-get-bottom-point struct)))
6426 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6427 (org-list-get-all-items (point) struct prevs))
6428 (goto-char end))))))
6429 (message "CHILDREN")
6430 (save-excursion
6431 (goto-char eos)
6432 (outline-next-heading)
6433 (if (outline-invisible-p) (org-flag-heading nil)))
6434 (setq org-cycle-subtree-status 'children)
6435 (run-hook-with-args 'org-cycle-hook 'children))
6436 ((or children-skipped
6437 (and (eq last-command this-command)
6438 (eq org-cycle-subtree-status 'children)))
6439 ;; We just showed the children, or no children are there,
6440 ;; now show everything.
6441 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6442 (outline-flag-region eoh eos nil)
6443 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6444 (setq org-cycle-subtree-status 'subtree)
6445 (run-hook-with-args 'org-cycle-hook 'subtree))
6447 ;; Default action: hide the subtree.
6448 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6449 (outline-flag-region eoh eos t)
6450 (message "FOLDED")
6451 (setq org-cycle-subtree-status 'folded)
6452 (run-hook-with-args 'org-cycle-hook 'folded)))))
6454 ;;;###autoload
6455 (defun org-global-cycle (&optional arg)
6456 "Cycle the global visibility. For details see `org-cycle'.
6457 With \\[universal-argument] prefix arg, switch to startup visibility.
6458 With a numeric prefix, show all headlines up to that level."
6459 (interactive "P")
6460 (let ((org-cycle-include-plain-lists
6461 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6462 (cond
6463 ((integerp arg)
6464 (show-all)
6465 (hide-sublevels arg)
6466 (setq org-cycle-global-status 'contents))
6467 ((equal arg '(4))
6468 (org-set-startup-visibility)
6469 (message "Startup visibility, plus VISIBILITY properties."))
6471 (org-cycle '(4))))))
6473 (defun org-set-startup-visibility ()
6474 "Set the visibility required by startup options and properties."
6475 (cond
6476 ((eq org-startup-folded t)
6477 (org-cycle '(4)))
6478 ((eq org-startup-folded 'content)
6479 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6480 (org-cycle '(4)) (org-cycle '(4)))))
6481 (unless (eq org-startup-folded 'showeverything)
6482 (if org-hide-block-startup (org-hide-block-all))
6483 (org-set-visibility-according-to-property 'no-cleanup)
6484 (org-cycle-hide-archived-subtrees 'all)
6485 (org-cycle-hide-drawers 'all)
6486 (org-cycle-show-empty-lines t)))
6488 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6489 "Switch subtree visibilities according to :VISIBILITY: property."
6490 (interactive)
6491 (let (org-show-entry-below state)
6492 (save-excursion
6493 (goto-char (point-min))
6494 (while (re-search-forward
6495 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6496 nil t)
6497 (setq state (match-string 1))
6498 (save-excursion
6499 (org-back-to-heading t)
6500 (hide-subtree)
6501 (org-reveal)
6502 (cond
6503 ((equal state '("fold" "folded"))
6504 (hide-subtree))
6505 ((equal state "children")
6506 (org-show-hidden-entry)
6507 (show-children))
6508 ((equal state "content")
6509 (save-excursion
6510 (save-restriction
6511 (org-narrow-to-subtree)
6512 (org-content))))
6513 ((member state '("all" "showall"))
6514 (show-subtree)))))
6515 (unless no-cleanup
6516 (org-cycle-hide-archived-subtrees 'all)
6517 (org-cycle-hide-drawers 'all)
6518 (org-cycle-show-empty-lines 'all)))))
6520 ;; This function uses outline-regexp instead of the more fundamental
6521 ;; org-outline-regexp so that org-cycle-global works outside of Org
6522 ;; buffers, where outline-regexp is needed.
6523 (defun org-overview ()
6524 "Switch to overview mode, showing only top-level headlines.
6525 Really, this shows all headlines with level equal or greater than the level
6526 of the first headline in the buffer. This is important, because if the
6527 first headline is not level one, then (hide-sublevels 1) gives confusing
6528 results."
6529 (interactive)
6530 (let ((level (save-excursion
6531 (goto-char (point-min))
6532 (if (re-search-forward (concat "^" outline-regexp) nil t)
6533 (progn
6534 (goto-char (match-beginning 0))
6535 (funcall outline-level))))))
6536 (and level (hide-sublevels level))))
6538 (defun org-content (&optional arg)
6539 "Show all headlines in the buffer, like a table of contents.
6540 With numerical argument N, show content up to level N."
6541 (interactive "P")
6542 (save-excursion
6543 ;; Visit all headings and show their offspring
6544 (and (integerp arg) (org-overview))
6545 (goto-char (point-max))
6546 (catch 'exit
6547 (while (and (progn (condition-case nil
6548 (outline-previous-visible-heading 1)
6549 (error (goto-char (point-min))))
6551 (looking-at org-outline-regexp))
6552 (if (integerp arg)
6553 (show-children (1- arg))
6554 (show-branches))
6555 (if (bobp) (throw 'exit nil))))))
6558 (defun org-optimize-window-after-visibility-change (state)
6559 "Adjust the window after a change in outline visibility.
6560 This function is the default value of the hook `org-cycle-hook'."
6561 (when (get-buffer-window (current-buffer))
6562 (cond
6563 ((eq state 'content) nil)
6564 ((eq state 'all) nil)
6565 ((eq state 'folded) nil)
6566 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6567 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6569 (defun org-remove-empty-overlays-at (pos)
6570 "Remove outline overlays that do not contain non-white stuff."
6571 (mapc
6572 (lambda (o)
6573 (and (eq 'outline (overlay-get o 'invisible))
6574 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6575 (overlay-end o))))
6576 (delete-overlay o)))
6577 (overlays-at pos)))
6579 (defun org-clean-visibility-after-subtree-move ()
6580 "Fix visibility issues after moving a subtree."
6581 ;; First, find a reasonable region to look at:
6582 ;; Start two siblings above, end three below
6583 (let* ((beg (save-excursion
6584 (and (org-get-last-sibling)
6585 (org-get-last-sibling))
6586 (point)))
6587 (end (save-excursion
6588 (and (org-get-next-sibling)
6589 (org-get-next-sibling)
6590 (org-get-next-sibling))
6591 (if (org-at-heading-p)
6592 (point-at-eol)
6593 (point))))
6594 (level (looking-at "\\*+"))
6595 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6596 (save-excursion
6597 (save-restriction
6598 (narrow-to-region beg end)
6599 (when re
6600 ;; Properly fold already folded siblings
6601 (goto-char (point-min))
6602 (while (re-search-forward re nil t)
6603 (if (and (not (outline-invisible-p))
6604 (save-excursion
6605 (goto-char (point-at-eol)) (outline-invisible-p)))
6606 (hide-entry))))
6607 (org-cycle-show-empty-lines 'overview)
6608 (org-cycle-hide-drawers 'overview)))))
6610 (defun org-cycle-show-empty-lines (state)
6611 "Show empty lines above all visible headlines.
6612 The region to be covered depends on STATE when called through
6613 `org-cycle-hook'. Lisp program can use t for STATE to get the
6614 entire buffer covered. Note that an empty line is only shown if there
6615 are at least `org-cycle-separator-lines' empty lines before the headline."
6616 (when (not (= org-cycle-separator-lines 0))
6617 (save-excursion
6618 (let* ((n (abs org-cycle-separator-lines))
6619 (re (cond
6620 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6621 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6622 (t (let ((ns (number-to-string (- n 2))))
6623 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6624 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6625 beg end b e)
6626 (cond
6627 ((memq state '(overview contents t))
6628 (setq beg (point-min) end (point-max)))
6629 ((memq state '(children folded))
6630 (setq beg (point) end (progn (org-end-of-subtree t t)
6631 (beginning-of-line 2)
6632 (point)))))
6633 (when beg
6634 (goto-char beg)
6635 (while (re-search-forward re end t)
6636 (unless (get-char-property (match-end 1) 'invisible)
6637 (setq e (match-end 1))
6638 (if (< org-cycle-separator-lines 0)
6639 (setq b (save-excursion
6640 (goto-char (match-beginning 0))
6641 (org-back-over-empty-lines)
6642 (if (save-excursion
6643 (goto-char (max (point-min) (1- (point))))
6644 (org-at-heading-p))
6645 (1- (point))
6646 (point))))
6647 (setq b (match-beginning 1)))
6648 (outline-flag-region b e nil)))))))
6649 ;; Never hide empty lines at the end of the file.
6650 (save-excursion
6651 (goto-char (point-max))
6652 (outline-previous-heading)
6653 (outline-end-of-heading)
6654 (if (and (looking-at "[ \t\n]+")
6655 (= (match-end 0) (point-max)))
6656 (outline-flag-region (point) (match-end 0) nil))))
6658 (defun org-show-empty-lines-in-parent ()
6659 "Move to the parent and re-show empty lines before visible headlines."
6660 (save-excursion
6661 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6662 (org-cycle-show-empty-lines context))))
6664 (defun org-files-list ()
6665 "Return `org-agenda-files' list, plus all open org-mode files.
6666 This is useful for operations that need to scan all of a user's
6667 open and agenda-wise Org files."
6668 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6669 (dolist (buf (buffer-list))
6670 (with-current-buffer buf
6671 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6672 (let ((file (expand-file-name (buffer-file-name))))
6673 (unless (member file files)
6674 (push file files))))))
6675 files))
6677 (defsubst org-entry-beginning-position ()
6678 "Return the beginning position of the current entry."
6679 (save-excursion (outline-back-to-heading t) (point)))
6681 (defsubst org-entry-end-position ()
6682 "Return the end position of the current entry."
6683 (save-excursion (outline-next-heading) (point)))
6685 (defun org-cycle-hide-drawers (state)
6686 "Re-hide all drawers after a visibility state change."
6687 (when (and (derived-mode-p 'org-mode)
6688 (not (memq state '(overview folded contents))))
6689 (save-excursion
6690 (let* ((globalp (memq state '(contents all)))
6691 (beg (if globalp (point-min) (point)))
6692 (end (if globalp (point-max)
6693 (if (eq state 'children)
6694 (save-excursion (outline-next-heading) (point))
6695 (org-end-of-subtree t)))))
6696 (goto-char beg)
6697 (while (re-search-forward org-drawer-regexp end t)
6698 (org-flag-drawer t))))))
6700 (defun org-flag-drawer (flag)
6701 "When FLAG is non-nil, hide the drawer we are within.
6702 Otherwise make it visible."
6703 (save-excursion
6704 (beginning-of-line 1)
6705 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6706 (let ((b (match-end 0)))
6707 (if (re-search-forward
6708 "^[ \t]*:END:"
6709 (save-excursion (outline-next-heading) (point)) t)
6710 (outline-flag-region b (point-at-eol) flag)
6711 (error ":END: line missing at position %s" b))))))
6713 (defun org-subtree-end-visible-p ()
6714 "Is the end of the current subtree visible?"
6715 (pos-visible-in-window-p
6716 (save-excursion (org-end-of-subtree t) (point))))
6718 (defun org-first-headline-recenter (&optional N)
6719 "Move cursor to the first headline and recenter the headline.
6720 Optional argument N means put the headline into the Nth line of the window."
6721 (goto-char (point-min))
6722 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6723 (beginning-of-line)
6724 (recenter (prefix-numeric-value N))))
6726 ;;; Saving and restoring visibility
6728 (defun org-outline-overlay-data (&optional use-markers)
6729 "Return a list of the locations of all outline overlays.
6730 These are overlays with the `invisible' property value `outline'.
6731 The return value is a list of cons cells, with start and stop
6732 positions for each overlay.
6733 If USE-MARKERS is set, return the positions as markers."
6734 (let (beg end)
6735 (save-excursion
6736 (save-restriction
6737 (widen)
6738 (delq nil
6739 (mapcar (lambda (o)
6740 (when (eq (overlay-get o 'invisible) 'outline)
6741 (setq beg (overlay-start o)
6742 end (overlay-end o))
6743 (and beg end (> end beg)
6744 (if use-markers
6745 (cons (move-marker (make-marker) beg)
6746 (move-marker (make-marker) end))
6747 (cons beg end)))))
6748 (overlays-in (point-min) (point-max))))))))
6750 (defun org-set-outline-overlay-data (data)
6751 "Create visibility overlays for all positions in DATA.
6752 DATA should have been made by `org-outline-overlay-data'."
6753 (let (o)
6754 (save-excursion
6755 (save-restriction
6756 (widen)
6757 (show-all)
6758 (mapc (lambda (c)
6759 (outline-flag-region (car c) (cdr c) t))
6760 data)))))
6762 ;;; Folding of blocks
6764 (defvar org-hide-block-overlays nil
6765 "Overlays hiding blocks.")
6766 (make-variable-buffer-local 'org-hide-block-overlays)
6768 (defun org-block-map (function &optional start end)
6769 "Call FUNCTION at the head of all source blocks in the current buffer.
6770 Optional arguments START and END can be used to limit the range."
6771 (let ((start (or start (point-min)))
6772 (end (or end (point-max))))
6773 (save-excursion
6774 (goto-char start)
6775 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6776 (save-excursion
6777 (save-match-data
6778 (goto-char (match-beginning 0))
6779 (funcall function)))))))
6781 (defun org-hide-block-toggle-all ()
6782 "Toggle the visibility of all blocks in the current buffer."
6783 (org-block-map #'org-hide-block-toggle))
6785 (defun org-hide-block-all ()
6786 "Fold all blocks in the current buffer."
6787 (interactive)
6788 (org-show-block-all)
6789 (org-block-map #'org-hide-block-toggle-maybe))
6791 (defun org-show-block-all ()
6792 "Unfold all blocks in the current buffer."
6793 (interactive)
6794 (mapc 'delete-overlay org-hide-block-overlays)
6795 (setq org-hide-block-overlays nil))
6797 (defun org-hide-block-toggle-maybe ()
6798 "Toggle visibility of block at point."
6799 (interactive)
6800 (let ((case-fold-search t))
6801 (if (save-excursion
6802 (beginning-of-line 1)
6803 (looking-at org-block-regexp))
6804 (progn (org-hide-block-toggle)
6805 t) ;; to signal that we took action
6806 nil))) ;; to signal that we did not
6808 (defun org-hide-block-toggle (&optional force)
6809 "Toggle the visibility of the current block."
6810 (interactive)
6811 (save-excursion
6812 (beginning-of-line)
6813 (if (re-search-forward org-block-regexp nil t)
6814 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6815 (end (match-end 0)) ;; end of entire body
6817 (if (memq t (mapcar (lambda (overlay)
6818 (eq (overlay-get overlay 'invisible)
6819 'org-hide-block))
6820 (overlays-at start)))
6821 (if (or (not force) (eq force 'off))
6822 (mapc (lambda (ov)
6823 (when (member ov org-hide-block-overlays)
6824 (setq org-hide-block-overlays
6825 (delq ov org-hide-block-overlays)))
6826 (when (eq (overlay-get ov 'invisible)
6827 'org-hide-block)
6828 (delete-overlay ov)))
6829 (overlays-at start)))
6830 (setq ov (make-overlay start end))
6831 (overlay-put ov 'invisible 'org-hide-block)
6832 ;; make the block accessible to isearch
6833 (overlay-put
6834 ov 'isearch-open-invisible
6835 (lambda (ov)
6836 (when (member ov org-hide-block-overlays)
6837 (setq org-hide-block-overlays
6838 (delq ov org-hide-block-overlays)))
6839 (when (eq (overlay-get ov 'invisible)
6840 'org-hide-block)
6841 (delete-overlay ov))))
6842 (push ov org-hide-block-overlays)))
6843 (error "Not looking at a source block"))))
6845 ;; org-tab-after-check-for-cycling-hook
6846 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6847 ;; Remove overlays when changing major mode
6848 (add-hook 'org-mode-hook
6849 (lambda () (org-add-hook 'change-major-mode-hook
6850 'org-show-block-all 'append 'local)))
6852 ;;; Org-goto
6854 (defvar org-goto-window-configuration nil)
6855 (defvar org-goto-marker nil)
6856 (defvar org-goto-map
6857 (let ((map (make-sparse-keymap)))
6858 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6859 (while (setq cmd (pop cmds))
6860 (substitute-key-definition cmd cmd map global-map)))
6861 (suppress-keymap map)
6862 (org-defkey map "\C-m" 'org-goto-ret)
6863 (org-defkey map [(return)] 'org-goto-ret)
6864 (org-defkey map [(left)] 'org-goto-left)
6865 (org-defkey map [(right)] 'org-goto-right)
6866 (org-defkey map [(control ?g)] 'org-goto-quit)
6867 (org-defkey map "\C-i" 'org-cycle)
6868 (org-defkey map [(tab)] 'org-cycle)
6869 (org-defkey map [(down)] 'outline-next-visible-heading)
6870 (org-defkey map [(up)] 'outline-previous-visible-heading)
6871 (if org-goto-auto-isearch
6872 (if (fboundp 'define-key-after)
6873 (define-key-after map [t] 'org-goto-local-auto-isearch)
6874 nil)
6875 (org-defkey map "q" 'org-goto-quit)
6876 (org-defkey map "n" 'outline-next-visible-heading)
6877 (org-defkey map "p" 'outline-previous-visible-heading)
6878 (org-defkey map "f" 'outline-forward-same-level)
6879 (org-defkey map "b" 'outline-backward-same-level)
6880 (org-defkey map "u" 'outline-up-heading))
6881 (org-defkey map "/" 'org-occur)
6882 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6883 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6884 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6885 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6886 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6887 map))
6889 (defconst org-goto-help
6890 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6891 RET=jump to location [Q]uit and return to previous location
6892 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6894 (defvar org-goto-start-pos) ; dynamically scoped parameter
6896 ;; FIXME: Docstring does not mention both interfaces
6897 (defun org-goto (&optional alternative-interface)
6898 "Look up a different location in the current file, keeping current visibility.
6900 When you want look-up or go to a different location in a
6901 document, the fastest way is often to fold the entire buffer and
6902 then dive into the tree. This method has the disadvantage, that
6903 the previous location will be folded, which may not be what you
6904 want.
6906 This command works around this by showing a copy of the current
6907 buffer in an indirect buffer, in overview mode. You can dive
6908 into the tree in that copy, use org-occur and incremental search
6909 to find a location. When pressing RET or `Q', the command
6910 returns to the original buffer in which the visibility is still
6911 unchanged. After RET it will also jump to the location selected
6912 in the indirect buffer and expose the headline hierarchy above.
6914 With a prefix argument, use the alternative interface: e.g. if
6915 `org-goto-interface' is 'outline use 'outline-path-completion."
6916 (interactive "P")
6917 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6918 (org-refile-use-outline-path t)
6919 (org-refile-target-verify-function nil)
6920 (interface
6921 (if (not alternative-interface)
6922 org-goto-interface
6923 (if (eq org-goto-interface 'outline)
6924 'outline-path-completion
6925 'outline)))
6926 (org-goto-start-pos (point))
6927 (selected-point
6928 (if (eq interface 'outline)
6929 (car (org-get-location (current-buffer) org-goto-help))
6930 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6931 (org-refile-check-position pa)
6932 (nth 3 pa)))))
6933 (if selected-point
6934 (progn
6935 (org-mark-ring-push org-goto-start-pos)
6936 (goto-char selected-point)
6937 (if (or (outline-invisible-p) (org-invisible-p2))
6938 (org-show-context 'org-goto)))
6939 (message "Quit"))))
6941 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6942 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6943 (defvar org-goto-local-auto-isearch-map) ; defined below
6945 (defun org-get-location (buf help)
6946 "Let the user select a location in the Org-mode buffer BUF.
6947 This function uses a recursive edit. It returns the selected position
6948 or nil."
6949 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6950 (isearch-hide-immediately nil)
6951 (isearch-search-fun-function
6952 (lambda () 'org-goto-local-search-headings))
6953 (org-goto-selected-point org-goto-exit-command)
6954 (pop-up-frames nil)
6955 (special-display-buffer-names nil)
6956 (special-display-regexps nil)
6957 (special-display-function nil))
6958 (save-excursion
6959 (save-window-excursion
6960 (delete-other-windows)
6961 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6962 (org-pop-to-buffer-same-window
6963 (condition-case nil
6964 (make-indirect-buffer (current-buffer) "*org-goto*")
6965 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6966 (with-output-to-temp-buffer "*Help*"
6967 (princ help))
6968 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6969 (setq buffer-read-only nil)
6970 (let ((org-startup-truncated t)
6971 (org-startup-folded nil)
6972 (org-startup-align-all-tables nil))
6973 (org-mode)
6974 (org-overview))
6975 (setq buffer-read-only t)
6976 (if (and (boundp 'org-goto-start-pos)
6977 (integer-or-marker-p org-goto-start-pos))
6978 (let ((org-show-hierarchy-above t)
6979 (org-show-siblings t)
6980 (org-show-following-heading t))
6981 (goto-char org-goto-start-pos)
6982 (and (outline-invisible-p) (org-show-context)))
6983 (goto-char (point-min)))
6984 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6985 (message "Select location and press RET")
6986 (use-local-map org-goto-map)
6987 (recursive-edit)
6989 (kill-buffer "*org-goto*")
6990 (cons org-goto-selected-point org-goto-exit-command)))
6992 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6993 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6994 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6995 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6997 (defun org-goto-local-search-headings (string bound noerror)
6998 "Search and make sure that any matches are in headlines."
6999 (catch 'return
7000 (while (if isearch-forward
7001 (search-forward string bound noerror)
7002 (search-backward string bound noerror))
7003 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7004 (and (member :headline context)
7005 (not (member :tags context))))
7006 (throw 'return (point))))))
7008 (defun org-goto-local-auto-isearch ()
7009 "Start isearch."
7010 (interactive)
7011 (goto-char (point-min))
7012 (let ((keys (this-command-keys)))
7013 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7014 (isearch-mode t)
7015 (isearch-process-search-char (string-to-char keys)))))
7017 (defun org-goto-ret (&optional arg)
7018 "Finish `org-goto' by going to the new location."
7019 (interactive "P")
7020 (setq org-goto-selected-point (point)
7021 org-goto-exit-command 'return)
7022 (throw 'exit nil))
7024 (defun org-goto-left ()
7025 "Finish `org-goto' by going to the new location."
7026 (interactive)
7027 (if (org-at-heading-p)
7028 (progn
7029 (beginning-of-line 1)
7030 (setq org-goto-selected-point (point)
7031 org-goto-exit-command 'left)
7032 (throw 'exit nil))
7033 (error "Not on a heading")))
7035 (defun org-goto-right ()
7036 "Finish `org-goto' by going to the new location."
7037 (interactive)
7038 (if (org-at-heading-p)
7039 (progn
7040 (setq org-goto-selected-point (point)
7041 org-goto-exit-command 'right)
7042 (throw 'exit nil))
7043 (error "Not on a heading")))
7045 (defun org-goto-quit ()
7046 "Finish `org-goto' without cursor motion."
7047 (interactive)
7048 (setq org-goto-selected-point nil)
7049 (setq org-goto-exit-command 'quit)
7050 (throw 'exit nil))
7052 ;;; Indirect buffer display of subtrees
7054 (defvar org-indirect-dedicated-frame nil
7055 "This is the frame being used for indirect tree display.")
7056 (defvar org-last-indirect-buffer nil)
7058 (defun org-tree-to-indirect-buffer (&optional arg)
7059 "Create indirect buffer and narrow it to current subtree.
7060 With numerical prefix ARG, go up to this level and then take that tree.
7061 If ARG is negative, go up that many levels.
7062 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7063 indirect buffer previously made with this command, to avoid proliferation of
7064 indirect buffers. However, when you call the command with a \
7065 \\[universal-argument] prefix, or
7066 when `org-indirect-buffer-display' is `new-frame', the last buffer
7067 is kept so that you can work with several indirect buffers at the same time.
7068 If `org-indirect-buffer-display' is `dedicated-frame', the \
7069 \\[universal-argument] prefix also
7070 requests that a new frame be made for the new buffer, so that the dedicated
7071 frame is not changed."
7072 (interactive "P")
7073 (let ((cbuf (current-buffer))
7074 (cwin (selected-window))
7075 (pos (point))
7076 beg end level heading ibuf)
7077 (save-excursion
7078 (org-back-to-heading t)
7079 (when (numberp arg)
7080 (setq level (org-outline-level))
7081 (if (< arg 0) (setq arg (+ level arg)))
7082 (while (> (setq level (org-outline-level)) arg)
7083 (outline-up-heading 1 t)))
7084 (setq beg (point)
7085 heading (org-get-heading))
7086 (org-end-of-subtree t t)
7087 (if (org-at-heading-p) (backward-char 1))
7088 (setq end (point)))
7089 (if (and (buffer-live-p org-last-indirect-buffer)
7090 (not (eq org-indirect-buffer-display 'new-frame))
7091 (not arg))
7092 (kill-buffer org-last-indirect-buffer))
7093 (setq ibuf (org-get-indirect-buffer cbuf)
7094 org-last-indirect-buffer ibuf)
7095 (cond
7096 ((or (eq org-indirect-buffer-display 'new-frame)
7097 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7098 (select-frame (make-frame))
7099 (delete-other-windows)
7100 (org-pop-to-buffer-same-window ibuf)
7101 (org-set-frame-title heading))
7102 ((eq org-indirect-buffer-display 'dedicated-frame)
7103 (raise-frame
7104 (select-frame (or (and org-indirect-dedicated-frame
7105 (frame-live-p org-indirect-dedicated-frame)
7106 org-indirect-dedicated-frame)
7107 (setq org-indirect-dedicated-frame (make-frame)))))
7108 (delete-other-windows)
7109 (org-pop-to-buffer-same-window ibuf)
7110 (org-set-frame-title (concat "Indirect: " heading)))
7111 ((eq org-indirect-buffer-display 'current-window)
7112 (org-pop-to-buffer-same-window ibuf))
7113 ((eq org-indirect-buffer-display 'other-window)
7114 (pop-to-buffer ibuf))
7115 (t (error "Invalid value")))
7116 (if (featurep 'xemacs)
7117 (save-excursion (org-mode) (turn-on-font-lock)))
7118 (narrow-to-region beg end)
7119 (show-all)
7120 (goto-char pos)
7121 (run-hook-with-args 'org-cycle-hook 'all)
7122 (and (window-live-p cwin) (select-window cwin))))
7124 (defun org-get-indirect-buffer (&optional buffer)
7125 (setq buffer (or buffer (current-buffer)))
7126 (let ((n 1) (base (buffer-name buffer)) bname)
7127 (while (buffer-live-p
7128 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7129 (setq n (1+ n)))
7130 (condition-case nil
7131 (make-indirect-buffer buffer bname 'clone)
7132 (error (make-indirect-buffer buffer bname)))))
7134 (defun org-set-frame-title (title)
7135 "Set the title of the current frame to the string TITLE."
7136 ;; FIXME: how to name a single frame in XEmacs???
7137 (unless (featurep 'xemacs)
7138 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7140 ;;;; Structure editing
7142 ;;; Inserting headlines
7144 (defun org-previous-line-empty-p ()
7145 (save-excursion
7146 (and (not (bobp))
7147 (or (beginning-of-line 0) t)
7148 (save-match-data
7149 (looking-at "[ \t]*$")))))
7151 (defun org-insert-heading (&optional force-heading invisible-ok)
7152 "Insert a new heading or item with same depth at point.
7153 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7154 If point is at the beginning of a headline, insert a sibling before the
7155 current headline. If point is not at the beginning, split the line,
7156 create the new headline with the text in the current line after point
7157 \(but see also the variable `org-M-RET-may-split-line').
7159 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7160 This is important for non-interactive uses of the command."
7161 (interactive "P")
7162 (if (or (= (buffer-size) 0)
7163 (and (not (save-excursion
7164 (and (ignore-errors (org-back-to-heading invisible-ok))
7165 (org-at-heading-p))))
7166 (or force-heading (not (org-in-item-p)))))
7167 (progn
7168 (insert "\n* ")
7169 (run-hooks 'org-insert-heading-hook))
7170 (when (or force-heading (not (org-insert-item)))
7171 (let* ((empty-line-p nil)
7172 (level nil)
7173 (on-heading (org-at-heading-p))
7174 (head (save-excursion
7175 (condition-case nil
7176 (progn
7177 (org-back-to-heading invisible-ok)
7178 (when (and (not on-heading)
7179 (featurep 'org-inlinetask)
7180 (integerp org-inlinetask-min-level)
7181 (>= (length (match-string 0))
7182 org-inlinetask-min-level))
7183 ;; Find a heading level before the inline task
7184 (while (and (setq level (org-up-heading-safe))
7185 (>= level org-inlinetask-min-level)))
7186 (if (org-at-heading-p)
7187 (org-back-to-heading invisible-ok)
7188 (error "This should not happen")))
7189 (setq empty-line-p (org-previous-line-empty-p))
7190 (match-string 0))
7191 (error "*"))))
7192 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7193 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7194 pos hide-previous previous-pos)
7195 (cond
7196 ((and (org-at-heading-p) (bolp)
7197 (or (bobp)
7198 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7199 ;; insert before the current line
7200 (open-line (if blank 2 1)))
7201 ((and (bolp)
7202 (not org-insert-heading-respect-content)
7203 (or (bobp)
7204 (save-excursion
7205 (backward-char 1) (not (outline-invisible-p)))))
7206 ;; insert right here
7207 nil)
7209 ;; somewhere in the line
7210 (save-excursion
7211 (setq previous-pos (point-at-bol))
7212 (end-of-line)
7213 (setq hide-previous (outline-invisible-p)))
7214 (and org-insert-heading-respect-content (org-show-subtree))
7215 (let ((split
7216 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7217 (save-excursion
7218 (let ((p (point)))
7219 (goto-char (point-at-bol))
7220 (and (looking-at org-complex-heading-regexp)
7221 (match-beginning 4)
7222 (> p (match-beginning 4)))))))
7223 tags pos)
7224 (cond
7225 (org-insert-heading-respect-content
7226 (org-end-of-subtree nil t)
7227 (when (featurep 'org-inlinetask)
7228 (while (and (not (eobp))
7229 (looking-at "\\(\\*+\\)[ \t]+")
7230 (>= (length (match-string 1))
7231 org-inlinetask-min-level))
7232 (org-end-of-subtree nil t)))
7233 (or (bolp) (newline))
7234 (or (org-previous-line-empty-p)
7235 (and blank (newline)))
7236 (open-line 1))
7237 ((org-at-heading-p)
7238 (when hide-previous
7239 (show-children)
7240 (org-show-entry))
7241 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7242 (setq tags (and (match-end 2) (match-string 2)))
7243 (and (match-end 1)
7244 (delete-region (match-beginning 1) (match-end 1)))
7245 (setq pos (point-at-bol))
7246 (or split (end-of-line 1))
7247 (delete-horizontal-space)
7248 (if (string-match "\\`\\*+\\'"
7249 (buffer-substring (point-at-bol) (point)))
7250 (insert " "))
7251 (newline (if blank 2 1))
7252 (when tags
7253 (save-excursion
7254 (goto-char pos)
7255 (end-of-line 1)
7256 (insert " " tags)
7257 (org-set-tags nil 'align))))
7259 (or split (end-of-line 1))
7260 (newline (if blank 2 1)))))))
7261 (insert head) (just-one-space)
7262 (setq pos (point))
7263 (end-of-line 1)
7264 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7265 (when (and org-insert-heading-respect-content hide-previous)
7266 (save-excursion
7267 (goto-char previous-pos)
7268 (hide-subtree)))
7269 (run-hooks 'org-insert-heading-hook)))))
7271 (defun org-get-heading (&optional no-tags no-todo)
7272 "Return the heading of the current entry, without the stars.
7273 When NO-TAGS is non-nil, don't include tags.
7274 When NO-TODO is non-nil, don't include TODO keywords."
7275 (save-excursion
7276 (org-back-to-heading t)
7277 (cond
7278 ((and no-tags no-todo)
7279 (looking-at org-complex-heading-regexp)
7280 (match-string 4))
7281 (no-tags
7282 (looking-at (concat org-outline-regexp
7283 "\\(.*?\\)"
7284 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7285 (match-string 1))
7286 (no-todo
7287 (looking-at org-todo-line-regexp)
7288 (match-string 3))
7289 (t (looking-at org-heading-regexp)
7290 (match-string 2)))))
7292 (defun org-heading-components ()
7293 "Return the components of the current heading.
7294 This is a list with the following elements:
7295 - the level as an integer
7296 - the reduced level, different if `org-odd-levels-only' is set.
7297 - the TODO keyword, or nil
7298 - the priority character, like ?A, or nil if no priority is given
7299 - the headline text itself, or the tags string if no headline text
7300 - the tags string, or nil."
7301 (save-excursion
7302 (org-back-to-heading t)
7303 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7304 (list (length (match-string 1))
7305 (org-reduced-level (length (match-string 1)))
7306 (org-match-string-no-properties 2)
7307 (and (match-end 3) (aref (match-string 3) 2))
7308 (org-match-string-no-properties 4)
7309 (org-match-string-no-properties 5)))))
7311 (defun org-get-entry ()
7312 "Get the entry text, after heading, entire subtree."
7313 (save-excursion
7314 (org-back-to-heading t)
7315 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7317 (defun org-insert-heading-after-current ()
7318 "Insert a new heading with same level as current, after current subtree."
7319 (interactive)
7320 (org-back-to-heading)
7321 (org-insert-heading)
7322 (org-move-subtree-down)
7323 (end-of-line 1))
7325 (defun org-insert-heading-respect-content ()
7326 (interactive)
7327 (let ((org-insert-heading-respect-content t))
7328 (org-insert-heading t)))
7330 (defun org-insert-todo-heading-respect-content (&optional force-state)
7331 (interactive "P")
7332 (let ((org-insert-heading-respect-content t))
7333 (org-insert-todo-heading force-state t)))
7335 (defun org-insert-todo-heading (arg &optional force-heading)
7336 "Insert a new heading with the same level and TODO state as current heading.
7337 If the heading has no TODO state, or if the state is DONE, use the first
7338 state (TODO by default). Also with prefix arg, force first state."
7339 (interactive "P")
7340 (when (or force-heading (not (org-insert-item 'checkbox)))
7341 (org-insert-heading force-heading)
7342 (save-excursion
7343 (org-back-to-heading)
7344 (outline-previous-heading)
7345 (looking-at org-todo-line-regexp))
7346 (let*
7347 ((new-mark-x
7348 (if (or arg
7349 (not (match-beginning 2))
7350 (member (match-string 2) org-done-keywords))
7351 (car org-todo-keywords-1)
7352 (match-string 2)))
7353 (new-mark
7355 (run-hook-with-args-until-success
7356 'org-todo-get-default-hook new-mark-x nil)
7357 new-mark-x)))
7358 (beginning-of-line 1)
7359 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7360 (if org-treat-insert-todo-heading-as-state-change
7361 (org-todo new-mark)
7362 (insert new-mark " "))))
7363 (when org-provide-todo-statistics
7364 (org-update-parent-todo-statistics))))
7366 (defun org-insert-subheading (arg)
7367 "Insert a new subheading and demote it.
7368 Works for outline headings and for plain lists alike."
7369 (interactive "P")
7370 (org-insert-heading arg)
7371 (cond
7372 ((org-at-heading-p) (org-do-demote))
7373 ((org-at-item-p) (org-indent-item))))
7375 (defun org-insert-todo-subheading (arg)
7376 "Insert a new subheading with TODO keyword or checkbox and demote it.
7377 Works for outline headings and for plain lists alike."
7378 (interactive "P")
7379 (org-insert-todo-heading arg)
7380 (cond
7381 ((org-at-heading-p) (org-do-demote))
7382 ((org-at-item-p) (org-indent-item))))
7384 ;;; Promotion and Demotion
7386 (defvar org-after-demote-entry-hook nil
7387 "Hook run after an entry has been demoted.
7388 The cursor will be at the beginning of the entry.
7389 When a subtree is being demoted, the hook will be called for each node.")
7391 (defvar org-after-promote-entry-hook nil
7392 "Hook run after an entry has been promoted.
7393 The cursor will be at the beginning of the entry.
7394 When a subtree is being promoted, the hook will be called for each node.")
7396 (defun org-promote-subtree ()
7397 "Promote the entire subtree.
7398 See also `org-promote'."
7399 (interactive)
7400 (save-excursion
7401 (org-with-limited-levels (org-map-tree 'org-promote)))
7402 (org-fix-position-after-promote))
7404 (defun org-demote-subtree ()
7405 "Demote the entire subtree. See `org-demote'.
7406 See also `org-promote'."
7407 (interactive)
7408 (save-excursion
7409 (org-with-limited-levels (org-map-tree 'org-demote)))
7410 (org-fix-position-after-promote))
7413 (defun org-do-promote ()
7414 "Promote the current heading higher up the tree.
7415 If the region is active in `transient-mark-mode', promote all headings
7416 in the region."
7417 (interactive)
7418 (save-excursion
7419 (if (org-region-active-p)
7420 (org-map-region 'org-promote (region-beginning) (region-end))
7421 (org-promote)))
7422 (org-fix-position-after-promote))
7424 (defun org-do-demote ()
7425 "Demote the current heading lower down the tree.
7426 If the region is active in `transient-mark-mode', demote all headings
7427 in the region."
7428 (interactive)
7429 (save-excursion
7430 (if (org-region-active-p)
7431 (org-map-region 'org-demote (region-beginning) (region-end))
7432 (org-demote)))
7433 (org-fix-position-after-promote))
7435 (defun org-fix-position-after-promote ()
7436 "Make sure that after pro/demotion cursor position is right."
7437 (let ((pos (point)))
7438 (when (save-excursion
7439 (beginning-of-line 1)
7440 (looking-at org-todo-line-regexp)
7441 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7442 (cond ((eobp) (insert " "))
7443 ((eolp) (insert " "))
7444 ((equal (char-after) ?\ ) (forward-char 1))))))
7446 (defun org-current-level ()
7447 "Return the level of the current entry, or nil if before the first headline.
7448 The level is the number of stars at the beginning of the headline."
7449 (save-excursion
7450 (org-with-limited-levels
7451 (if (ignore-errors (org-back-to-heading t))
7452 (funcall outline-level)))))
7454 (defun org-get-previous-line-level ()
7455 "Return the outline depth of the last headline before the current line.
7456 Returns 0 for the first headline in the buffer, and nil if before the
7457 first headline."
7458 (let ((current-level (org-current-level))
7459 (prev-level (when (> (line-number-at-pos) 1)
7460 (save-excursion
7461 (beginning-of-line 0)
7462 (org-current-level)))))
7463 (cond ((null current-level) nil) ; Before first headline
7464 ((null prev-level) 0) ; At first headline
7465 (prev-level))))
7467 (defun org-reduced-level (l)
7468 "Compute the effective level of a heading.
7469 This takes into account the setting of `org-odd-levels-only'."
7470 (cond
7471 ((zerop l) 0)
7472 (org-odd-levels-only (1+ (floor (/ l 2))))
7473 (t l)))
7475 (defun org-level-increment ()
7476 "Return the number of stars that will be added or removed at a
7477 time to headlines when structure editing, based on the value of
7478 `org-odd-levels-only'."
7479 (if org-odd-levels-only 2 1))
7481 (defun org-get-valid-level (level &optional change)
7482 "Rectify a level change under the influence of `org-odd-levels-only'
7483 LEVEL is a current level, CHANGE is by how much the level should be
7484 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7485 even level numbers will become the next higher odd number."
7486 (if org-odd-levels-only
7487 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7488 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7489 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7490 (max 1 (+ level (or change 0)))))
7492 (if (boundp 'define-obsolete-function-alias)
7493 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7494 (define-obsolete-function-alias 'org-get-legal-level
7495 'org-get-valid-level)
7496 (define-obsolete-function-alias 'org-get-legal-level
7497 'org-get-valid-level "23.1")))
7499 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7500 ;; ̀org-with-limited-levels'
7501 (defun org-promote ()
7502 "Promote the current heading higher up the tree.
7503 If the region is active in `transient-mark-mode', promote all headings
7504 in the region."
7505 (org-back-to-heading t)
7506 (let* ((level (save-match-data (funcall outline-level)))
7507 (after-change-functions (remove 'flyspell-after-change-function
7508 after-change-functions))
7509 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7510 (diff (abs (- level (length up-head) -1))))
7511 (cond ((and (= level 1) org-called-with-limited-levels
7512 org-allow-promoting-top-level-subtree)
7513 (replace-match "# " nil t))
7514 ((= level 1)
7515 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7516 (t (replace-match up-head nil t)))
7517 ;; Fixup tag positioning
7518 (unless (= level 1)
7519 (and org-auto-align-tags (org-set-tags nil t))
7520 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7521 (run-hooks 'org-after-promote-entry-hook)))
7523 (defun org-demote ()
7524 "Demote the current heading lower down the tree.
7525 If the region is active in `transient-mark-mode', demote all headings
7526 in the region."
7527 (org-back-to-heading t)
7528 (let* ((level (save-match-data (funcall outline-level)))
7529 (after-change-functions (remove 'flyspell-after-change-function
7530 after-change-functions))
7531 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7532 (diff (abs (- level (length down-head) -1))))
7533 (replace-match down-head nil t)
7534 ;; Fixup tag positioning
7535 (and org-auto-align-tags (org-set-tags nil t))
7536 (if org-adapt-indentation (org-fixup-indentation diff))
7537 (run-hooks 'org-after-demote-entry-hook)))
7539 (defun org-cycle-level ()
7540 "Cycle the level of an empty headline through possible states.
7541 This goes first to child, then to parent, level, then up the hierarchy.
7542 After top level, it switches back to sibling level."
7543 (interactive)
7544 (let ((org-adapt-indentation nil))
7545 (when (org-point-at-end-of-empty-headline)
7546 (setq this-command 'org-cycle-level) ; Only needed for caching
7547 (let ((cur-level (org-current-level))
7548 (prev-level (org-get-previous-line-level)))
7549 (cond
7550 ;; If first headline in file, promote to top-level.
7551 ((= prev-level 0)
7552 (loop repeat (/ (- cur-level 1) (org-level-increment))
7553 do (org-do-promote)))
7554 ;; If same level as prev, demote one.
7555 ((= prev-level cur-level)
7556 (org-do-demote))
7557 ;; If parent is top-level, promote to top level if not already.
7558 ((= prev-level 1)
7559 (loop repeat (/ (- cur-level 1) (org-level-increment))
7560 do (org-do-promote)))
7561 ;; If top-level, return to prev-level.
7562 ((= cur-level 1)
7563 (loop repeat (/ (- prev-level 1) (org-level-increment))
7564 do (org-do-demote)))
7565 ;; If less than prev-level, promote one.
7566 ((< cur-level prev-level)
7567 (org-do-promote))
7568 ;; If deeper than prev-level, promote until higher than
7569 ;; prev-level.
7570 ((> cur-level prev-level)
7571 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7572 do (org-do-promote))))
7573 t))))
7575 (defun org-map-tree (fun)
7576 "Call FUN for every heading underneath the current one."
7577 (org-back-to-heading)
7578 (let ((level (funcall outline-level)))
7579 (save-excursion
7580 (funcall fun)
7581 (while (and (progn
7582 (outline-next-heading)
7583 (> (funcall outline-level) level))
7584 (not (eobp)))
7585 (funcall fun)))))
7587 (defun org-map-region (fun beg end)
7588 "Call FUN for every heading between BEG and END."
7589 (let ((org-ignore-region t))
7590 (save-excursion
7591 (setq end (copy-marker end))
7592 (goto-char beg)
7593 (if (and (re-search-forward org-outline-regexp-bol nil t)
7594 (< (point) end))
7595 (funcall fun))
7596 (while (and (progn
7597 (outline-next-heading)
7598 (< (point) end))
7599 (not (eobp)))
7600 (funcall fun)))))
7602 (defvar org-property-end-re) ; silence byte-compiler
7603 (defun org-fixup-indentation (diff)
7604 "Change the indentation in the current entry by DIFF.
7605 However, if any line in the current entry has no indentation, or if it
7606 would end up with no indentation after the change, nothing at all is done."
7607 (save-excursion
7608 (let ((end (save-excursion (outline-next-heading)
7609 (point-marker)))
7610 (prohibit (if (> diff 0)
7611 "^\\S-"
7612 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7613 col)
7614 (unless (save-excursion (end-of-line 1)
7615 (re-search-forward prohibit end t))
7616 (while (and (< (point) end)
7617 (re-search-forward "^[ \t]+" end t))
7618 (goto-char (match-end 0))
7619 (setq col (current-column))
7620 (if (< diff 0) (replace-match ""))
7621 (org-indent-to-column (+ diff col))))
7622 (move-marker end nil))))
7624 (defun org-convert-to-odd-levels ()
7625 "Convert an org-mode file with all levels allowed to one with odd levels.
7626 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7627 level 5 etc."
7628 (interactive)
7629 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7630 (let ((outline-level 'org-outline-level)
7631 (org-odd-levels-only nil) n)
7632 (save-excursion
7633 (goto-char (point-min))
7634 (while (re-search-forward "^\\*\\*+ " nil t)
7635 (setq n (- (length (match-string 0)) 2))
7636 (while (>= (setq n (1- n)) 0)
7637 (org-demote))
7638 (end-of-line 1))))))
7640 (defun org-convert-to-oddeven-levels ()
7641 "Convert an org-mode file with only odd levels to one with odd/even levels.
7642 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7643 file contains a section with an even level, conversion would
7644 destroy the structure of the file. An error is signaled in this
7645 case."
7646 (interactive)
7647 (goto-char (point-min))
7648 ;; First check if there are no even levels
7649 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7650 (org-show-context t)
7651 (error "Not all levels are odd in this file. Conversion not possible"))
7652 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7653 (let ((outline-regexp org-outline-regexp)
7654 (outline-level 'org-outline-level)
7655 (org-odd-levels-only nil) n)
7656 (save-excursion
7657 (goto-char (point-min))
7658 (while (re-search-forward "^\\*\\*+ " nil t)
7659 (setq n (/ (1- (length (match-string 0))) 2))
7660 (while (>= (setq n (1- n)) 0)
7661 (org-promote))
7662 (end-of-line 1))))))
7664 (defun org-tr-level (n)
7665 "Make N odd if required."
7666 (if org-odd-levels-only (1+ (/ n 2)) n))
7668 ;;; Vertical tree motion, cutting and pasting of subtrees
7670 (defun org-move-subtree-up (&optional arg)
7671 "Move the current subtree up past ARG headlines of the same level."
7672 (interactive "p")
7673 (org-move-subtree-down (- (prefix-numeric-value arg))))
7675 (defun org-move-subtree-down (&optional arg)
7676 "Move the current subtree down past ARG headlines of the same level."
7677 (interactive "p")
7678 (setq arg (prefix-numeric-value arg))
7679 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7680 'org-get-last-sibling))
7681 (ins-point (make-marker))
7682 (cnt (abs arg))
7683 (col (current-column))
7684 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7685 ;; Select the tree
7686 (org-back-to-heading)
7687 (setq beg0 (point))
7688 (save-excursion
7689 (setq ne-beg (org-back-over-empty-lines))
7690 (setq beg (point)))
7691 (save-match-data
7692 (save-excursion (outline-end-of-heading)
7693 (setq folded (outline-invisible-p)))
7694 (outline-end-of-subtree))
7695 (outline-next-heading)
7696 (setq ne-end (org-back-over-empty-lines))
7697 (setq end (point))
7698 (goto-char beg0)
7699 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7700 ;; include less whitespace
7701 (save-excursion
7702 (goto-char beg)
7703 (forward-line (- ne-beg ne-end))
7704 (setq beg (point))))
7705 ;; Find insertion point, with error handling
7706 (while (> cnt 0)
7707 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7708 (progn (goto-char beg0)
7709 (error "Cannot move past superior level or buffer limit")))
7710 (setq cnt (1- cnt)))
7711 (if (> arg 0)
7712 ;; Moving forward - still need to move over subtree
7713 (progn (org-end-of-subtree t t)
7714 (save-excursion
7715 (org-back-over-empty-lines)
7716 (or (bolp) (newline)))))
7717 (setq ne-ins (org-back-over-empty-lines))
7718 (move-marker ins-point (point))
7719 (setq txt (buffer-substring beg end))
7720 (org-save-markers-in-region beg end)
7721 (delete-region beg end)
7722 (org-remove-empty-overlays-at beg)
7723 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7724 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7725 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7726 (let ((bbb (point)))
7727 (insert-before-markers txt)
7728 (org-reinstall-markers-in-region bbb)
7729 (move-marker ins-point bbb))
7730 (or (bolp) (insert "\n"))
7731 (setq ins-end (point))
7732 (goto-char ins-point)
7733 (org-skip-whitespace)
7734 (when (and (< arg 0)
7735 (org-first-sibling-p)
7736 (> ne-ins ne-beg))
7737 ;; Move whitespace back to beginning
7738 (save-excursion
7739 (goto-char ins-end)
7740 (let ((kill-whole-line t))
7741 (kill-line (- ne-ins ne-beg)) (point)))
7742 (insert (make-string (- ne-ins ne-beg) ?\n)))
7743 (move-marker ins-point nil)
7744 (if folded
7745 (hide-subtree)
7746 (org-show-entry)
7747 (show-children)
7748 (org-cycle-hide-drawers 'children))
7749 (org-clean-visibility-after-subtree-move)
7750 ;; move back to the initial column we were at
7751 (move-to-column col)))
7753 (defvar org-subtree-clip ""
7754 "Clipboard for cut and paste of subtrees.
7755 This is actually only a copy of the kill, because we use the normal kill
7756 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7758 (defvar org-subtree-clip-folded nil
7759 "Was the last copied subtree folded?
7760 This is used to fold the tree back after pasting.")
7762 (defun org-cut-subtree (&optional n)
7763 "Cut the current subtree into the clipboard.
7764 With prefix arg N, cut this many sequential subtrees.
7765 This is a short-hand for marking the subtree and then cutting it."
7766 (interactive "p")
7767 (org-copy-subtree n 'cut))
7769 (defun org-copy-subtree (&optional n cut force-store-markers)
7770 "Cut the current subtree into the clipboard.
7771 With prefix arg N, cut this many sequential subtrees.
7772 This is a short-hand for marking the subtree and then copying it.
7773 If CUT is non-nil, actually cut the subtree.
7774 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7775 of some markers in the region, even if CUT is non-nil. This is
7776 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7777 (interactive "p")
7778 (let (beg end folded (beg0 (point)))
7779 (if (org-called-interactively-p 'any)
7780 (org-back-to-heading nil) ; take what looks like a subtree
7781 (org-back-to-heading t)) ; take what is really there
7782 (org-back-over-empty-lines)
7783 (setq beg (point))
7784 (skip-chars-forward " \t\r\n")
7785 (save-match-data
7786 (save-excursion (outline-end-of-heading)
7787 (setq folded (outline-invisible-p)))
7788 (condition-case nil
7789 (org-forward-same-level (1- n) t)
7790 (error nil))
7791 (org-end-of-subtree t t))
7792 (org-back-over-empty-lines)
7793 (setq end (point))
7794 (goto-char beg0)
7795 (when (> end beg)
7796 (setq org-subtree-clip-folded folded)
7797 (when (or cut force-store-markers)
7798 (org-save-markers-in-region beg end))
7799 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7800 (setq org-subtree-clip (current-kill 0))
7801 (message "%s: Subtree(s) with %d characters"
7802 (if cut "Cut" "Copied")
7803 (length org-subtree-clip)))))
7805 (defun org-paste-subtree (&optional level tree for-yank)
7806 "Paste the clipboard as a subtree, with modification of headline level.
7807 The entire subtree is promoted or demoted in order to match a new headline
7808 level.
7810 If the cursor is at the beginning of a headline, the same level as
7811 that headline is used to paste the tree
7813 If not, the new level is derived from the *visible* headings
7814 before and after the insertion point, and taken to be the inferior headline
7815 level of the two. So if the previous visible heading is level 3 and the
7816 next is level 4 (or vice versa), level 4 will be used for insertion.
7817 This makes sure that the subtree remains an independent subtree and does
7818 not swallow low level entries.
7820 You can also force a different level, either by using a numeric prefix
7821 argument, or by inserting the heading marker by hand. For example, if the
7822 cursor is after \"*****\", then the tree will be shifted to level 5.
7824 If optional TREE is given, use this text instead of the kill ring.
7826 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7827 move back over whitespace before inserting, and move point to the end of
7828 the inserted text when done."
7829 (interactive "P")
7830 (setq tree (or tree (and kill-ring (current-kill 0))))
7831 (unless (org-kill-is-subtree-p tree)
7832 (error "%s"
7833 (substitute-command-keys
7834 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7835 (org-with-limited-levels
7836 (let* ((visp (not (outline-invisible-p)))
7837 (txt tree)
7838 (^re_ "\\(\\*+\\)[ \t]*")
7839 (old-level (if (string-match org-outline-regexp-bol txt)
7840 (- (match-end 0) (match-beginning 0) 1)
7841 -1))
7842 (force-level (cond (level (prefix-numeric-value level))
7843 ((and (looking-at "[ \t]*$")
7844 (string-match
7845 "^\\*+$" (buffer-substring
7846 (point-at-bol) (point))))
7847 (- (match-end 1) (match-beginning 1)))
7848 ((and (bolp)
7849 (looking-at org-outline-regexp))
7850 (- (match-end 0) (point) 1))
7851 (t nil)))
7852 (previous-level (save-excursion
7853 (condition-case nil
7854 (progn
7855 (outline-previous-visible-heading 1)
7856 (if (looking-at ^re_)
7857 (- (match-end 0) (match-beginning 0) 1)
7859 (error 1))))
7860 (next-level (save-excursion
7861 (condition-case nil
7862 (progn
7863 (or (looking-at org-outline-regexp)
7864 (outline-next-visible-heading 1))
7865 (if (looking-at ^re_)
7866 (- (match-end 0) (match-beginning 0) 1)
7868 (error 1))))
7869 (new-level (or force-level (max previous-level next-level)))
7870 (shift (if (or (= old-level -1)
7871 (= new-level -1)
7872 (= old-level new-level))
7874 (- new-level old-level)))
7875 (delta (if (> shift 0) -1 1))
7876 (func (if (> shift 0) 'org-demote 'org-promote))
7877 (org-odd-levels-only nil)
7878 beg end newend)
7879 ;; Remove the forced level indicator
7880 (if force-level
7881 (delete-region (point-at-bol) (point)))
7882 ;; Paste
7883 (beginning-of-line (if (bolp) 1 2))
7884 (unless for-yank (org-back-over-empty-lines))
7885 (setq beg (point))
7886 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7887 (insert-before-markers txt)
7888 (unless (string-match "\n\\'" txt) (insert "\n"))
7889 (setq newend (point))
7890 (org-reinstall-markers-in-region beg)
7891 (setq end (point))
7892 (goto-char beg)
7893 (skip-chars-forward " \t\n\r")
7894 (setq beg (point))
7895 (if (and (outline-invisible-p) visp)
7896 (save-excursion (outline-show-heading)))
7897 ;; Shift if necessary
7898 (unless (= shift 0)
7899 (save-restriction
7900 (narrow-to-region beg end)
7901 (while (not (= shift 0))
7902 (org-map-region func (point-min) (point-max))
7903 (setq shift (+ delta shift)))
7904 (goto-char (point-min))
7905 (setq newend (point-max))))
7906 (when (or (org-called-interactively-p 'interactive) for-yank)
7907 (message "Clipboard pasted as level %d subtree" new-level))
7908 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7909 kill-ring
7910 (eq org-subtree-clip (current-kill 0))
7911 org-subtree-clip-folded)
7912 ;; The tree was folded before it was killed/copied
7913 (hide-subtree))
7914 (and for-yank (goto-char newend)))))
7916 (defun org-kill-is-subtree-p (&optional txt)
7917 "Check if the current kill is an outline subtree, or a set of trees.
7918 Returns nil if kill does not start with a headline, or if the first
7919 headline level is not the largest headline level in the tree.
7920 So this will actually accept several entries of equal levels as well,
7921 which is OK for `org-paste-subtree'.
7922 If optional TXT is given, check this string instead of the current kill."
7923 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7924 (re (org-get-limited-outline-regexp))
7925 (^re (concat "^" re))
7926 (start-level (and kill
7927 (string-match
7928 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7929 kill)
7930 (- (match-end 2) (match-beginning 2) 1)))
7931 (start (1+ (or (match-beginning 2) -1))))
7932 (if (not start-level)
7933 (progn
7934 nil) ;; does not even start with a heading
7935 (catch 'exit
7936 (while (setq start (string-match ^re kill (1+ start)))
7937 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7938 (throw 'exit nil)))
7939 t))))
7941 (defvar org-markers-to-move nil
7942 "Markers that should be moved with a cut-and-paste operation.
7943 Those markers are stored together with their positions relative to
7944 the start of the region.")
7946 (defun org-save-markers-in-region (beg end)
7947 "Check markers in region.
7948 If these markers are between BEG and END, record their position relative
7949 to BEG, so that after moving the block of text, we can put the markers back
7950 into place.
7951 This function gets called just before an entry or tree gets cut from the
7952 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7953 called immediately, to move the markers with the entries."
7954 (setq org-markers-to-move nil)
7955 (when (featurep 'org-clock)
7956 (org-clock-save-markers-for-cut-and-paste beg end))
7957 (when (featurep 'org-agenda)
7958 (org-agenda-save-markers-for-cut-and-paste beg end)))
7960 (defun org-check-and-save-marker (marker beg end)
7961 "Check if MARKER is between BEG and END.
7962 If yes, remember the marker and the distance to BEG."
7963 (when (and (marker-buffer marker)
7964 (equal (marker-buffer marker) (current-buffer)))
7965 (if (and (>= marker beg) (< marker end))
7966 (push (cons marker (- marker beg)) org-markers-to-move))))
7968 (defun org-reinstall-markers-in-region (beg)
7969 "Move all remembered markers to their position relative to BEG."
7970 (mapc (lambda (x)
7971 (move-marker (car x) (+ beg (cdr x))))
7972 org-markers-to-move)
7973 (setq org-markers-to-move nil))
7975 (defun org-narrow-to-subtree ()
7976 "Narrow buffer to the current subtree."
7977 (interactive)
7978 (save-excursion
7979 (save-match-data
7980 (org-with-limited-levels
7981 (narrow-to-region
7982 (progn (org-back-to-heading t) (point))
7983 (progn (org-end-of-subtree t t)
7984 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7985 (point)))))))
7987 (defun org-narrow-to-block ()
7988 "Narrow buffer to the current block."
7989 (interactive)
7990 (let* ((case-fold-search t)
7991 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7992 "^[ \t]*#\\+end_.*")))
7993 (if blockp
7994 (narrow-to-region (car blockp) (cdr blockp))
7995 (error "Not in a block"))))
7997 (eval-when-compile
7998 (defvar org-property-drawer-re))
8000 (defvar org-property-start-re) ;; defined below
8001 (defun org-clone-subtree-with-time-shift (n &optional shift)
8002 "Clone the task (subtree) at point N times.
8003 The clones will be inserted as siblings.
8005 In interactive use, the user will be prompted for the number of
8006 clones to be produced, and for a time SHIFT, which may be a
8007 repeater as used in time stamps, for example `+3d'.
8009 When a valid repeater is given and the entry contains any time
8010 stamps, the clones will become a sequence in time, with time
8011 stamps in the subtree shifted for each clone produced. If SHIFT
8012 is nil or the empty string, time stamps will be left alone. The
8013 ID property of the original subtree is removed.
8015 If the original subtree did contain time stamps with a repeater,
8016 the following will happen:
8017 - the repeater will be removed in each clone
8018 - an additional clone will be produced, with the current, unshifted
8019 date(s) in the entry.
8020 - the original entry will be placed *after* all the clones, with
8021 repeater intact.
8022 - the start days in the repeater in the original entry will be shifted
8023 to past the last clone.
8024 In this way you can spell out a number of instances of a repeating task,
8025 and still retain the repeater to cover future instances of the task."
8026 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8027 (let (beg end template task idprop
8028 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8029 (drawer-re org-drawer-regexp))
8030 (if (not (and (integerp n) (> n 0)))
8031 (error "Invalid number of replications %s" n))
8032 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8033 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8034 shift)))
8035 (error "Invalid shift specification %s" shift))
8036 (when doshift
8037 (setq shift-n (string-to-number (match-string 1 shift))
8038 shift-what (cdr (assoc (match-string 2 shift)
8039 '(("d" . day) ("w" . week)
8040 ("m" . month) ("y" . year))))))
8041 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8042 (setq nmin 1 nmax n)
8043 (org-back-to-heading t)
8044 (setq beg (point))
8045 (setq idprop (org-entry-get nil "ID"))
8046 (org-end-of-subtree t t)
8047 (or (bolp) (insert "\n"))
8048 (setq end (point))
8049 (setq template (buffer-substring beg end))
8050 (when (and doshift
8051 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8052 (delete-region beg end)
8053 (setq end beg)
8054 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8055 (goto-char end)
8056 (loop for n from nmin to nmax do
8057 ;; prepare clone
8058 (with-temp-buffer
8059 (insert template)
8060 (org-mode)
8061 (goto-char (point-min))
8062 (org-show-subtree)
8063 (and idprop (if org-clone-delete-id
8064 (org-entry-delete nil "ID")
8065 (org-id-get-create t)))
8066 (unless (= n 0)
8067 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8068 (kill-whole-line))
8069 (goto-char (point-min))
8070 (while (re-search-forward drawer-re nil t)
8071 (mapc (lambda (d)
8072 (org-remove-empty-drawer-at d (point))) org-drawers)))
8073 (goto-char (point-min))
8074 (when doshift
8075 (while (re-search-forward org-ts-regexp-both nil t)
8076 (org-timestamp-change (* n shift-n) shift-what))
8077 (unless (= n n-no-remove)
8078 (goto-char (point-min))
8079 (while (re-search-forward org-ts-regexp nil t)
8080 (save-excursion
8081 (goto-char (match-beginning 0))
8082 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8083 (delete-region (match-beginning 1) (match-end 1)))))))
8084 (setq task (buffer-string)))
8085 (insert task))
8086 (goto-char beg)))
8088 ;;; Outline Sorting
8090 (defun org-sort (with-case)
8091 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8092 Optional argument WITH-CASE means sort case-sensitively."
8093 (interactive "P")
8094 (cond
8095 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8096 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8098 (org-call-with-arg 'org-sort-entries with-case))))
8100 (defun org-sort-remove-invisible (s)
8101 (remove-text-properties 0 (length s) org-rm-props s)
8102 (while (string-match org-bracket-link-regexp s)
8103 (setq s (replace-match (if (match-end 2)
8104 (match-string 3 s)
8105 (match-string 1 s)) t t s)))
8108 (defvar org-priority-regexp) ; defined later in the file
8110 (defvar org-after-sorting-entries-or-items-hook nil
8111 "Hook that is run after a bunch of entries or items have been sorted.
8112 When children are sorted, the cursor is in the parent line when this
8113 hook gets called. When a region or a plain list is sorted, the cursor
8114 will be in the first entry of the sorted region/list.")
8116 (defun org-sort-entries
8117 (&optional with-case sorting-type getkey-func compare-func property)
8118 "Sort entries on a certain level of an outline tree.
8119 If there is an active region, the entries in the region are sorted.
8120 Else, if the cursor is before the first entry, sort the top-level items.
8121 Else, the children of the entry at point are sorted.
8123 Sorting can be alphabetically, numerically, by date/time as given by
8124 a time stamp, by a property or by priority.
8126 The command prompts for the sorting type unless it has been given to the
8127 function through the SORTING-TYPE argument, which needs to be a character,
8128 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8129 precise meaning of each character:
8131 n Numerically, by converting the beginning of the entry/item to a number.
8132 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8133 t By date/time, either the first active time stamp in the entry, or, if
8134 none exist, by the first inactive one.
8135 s By the scheduled date/time.
8136 d By deadline date/time.
8137 c By creation time, which is assumed to be the first inactive time stamp
8138 at the beginning of a line.
8139 p By priority according to the cookie.
8140 r By the value of a property.
8142 Capital letters will reverse the sort order.
8144 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8145 called with point at the beginning of the record. It must return either
8146 a string or a number that should serve as the sorting key for that record.
8148 Comparing entries ignores case by default. However, with an optional argument
8149 WITH-CASE, the sorting considers case as well."
8150 (interactive "P")
8151 (let ((case-func (if with-case 'identity 'downcase))
8152 start beg end stars re re2
8153 txt what tmp)
8154 ;; Find beginning and end of region to sort
8155 (cond
8156 ((org-region-active-p)
8157 ;; we will sort the region
8158 (setq end (region-end)
8159 what "region")
8160 (goto-char (region-beginning))
8161 (if (not (org-at-heading-p)) (outline-next-heading))
8162 (setq start (point)))
8163 ((or (org-at-heading-p)
8164 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8165 ;; we will sort the children of the current headline
8166 (org-back-to-heading)
8167 (setq start (point)
8168 end (progn (org-end-of-subtree t t)
8169 (or (bolp) (insert "\n"))
8170 (org-back-over-empty-lines)
8171 (point))
8172 what "children")
8173 (goto-char start)
8174 (show-subtree)
8175 (outline-next-heading))
8177 ;; we will sort the top-level entries in this file
8178 (goto-char (point-min))
8179 (or (org-at-heading-p) (outline-next-heading))
8180 (setq start (point))
8181 (goto-char (point-max))
8182 (beginning-of-line 1)
8183 (when (looking-at ".*?\\S-")
8184 ;; File ends in a non-white line
8185 (end-of-line 1)
8186 (insert "\n"))
8187 (setq end (point-max))
8188 (setq what "top-level")
8189 (goto-char start)
8190 (show-all)))
8192 (setq beg (point))
8193 (if (>= beg end) (error "Nothing to sort"))
8195 (looking-at "\\(\\*+\\)")
8196 (setq stars (match-string 1)
8197 re (concat "^" (regexp-quote stars) " +")
8198 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8199 txt (buffer-substring beg end))
8200 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8201 (if (and (not (equal stars "*")) (string-match re2 txt))
8202 (error "Region to sort contains a level above the first entry"))
8204 (unless sorting-type
8205 (message
8206 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8207 [t]ime [s]cheduled [d]eadline [c]reated
8208 A/N/T/S/D/C/P/O/F means reversed:"
8209 what)
8210 (setq sorting-type (read-char-exclusive))
8212 (and (= (downcase sorting-type) ?f)
8213 (setq getkey-func
8214 (org-icompleting-read "Sort using function: "
8215 obarray 'fboundp t nil nil))
8216 (setq getkey-func (intern getkey-func)))
8218 (and (= (downcase sorting-type) ?r)
8219 (setq property
8220 (org-icompleting-read "Property: "
8221 (mapcar 'list (org-buffer-property-keys t))
8222 nil t))))
8224 (message "Sorting entries...")
8226 (save-restriction
8227 (narrow-to-region start end)
8228 (let ((dcst (downcase sorting-type))
8229 (case-fold-search nil)
8230 (now (current-time)))
8231 (sort-subr
8232 (/= dcst sorting-type)
8233 ;; This function moves to the beginning character of the "record" to
8234 ;; be sorted.
8235 (lambda nil
8236 (if (re-search-forward re nil t)
8237 (goto-char (match-beginning 0))
8238 (goto-char (point-max))))
8239 ;; This function moves to the last character of the "record" being
8240 ;; sorted.
8241 (lambda nil
8242 (save-match-data
8243 (condition-case nil
8244 (outline-forward-same-level 1)
8245 (error
8246 (goto-char (point-max))))))
8247 ;; This function returns the value that gets sorted against.
8248 (lambda nil
8249 (cond
8250 ((= dcst ?n)
8251 (if (looking-at org-complex-heading-regexp)
8252 (string-to-number (match-string 4))
8253 nil))
8254 ((= dcst ?a)
8255 (if (looking-at org-complex-heading-regexp)
8256 (funcall case-func (match-string 4))
8257 nil))
8258 ((= dcst ?t)
8259 (let ((end (save-excursion (outline-next-heading) (point))))
8260 (if (or (re-search-forward org-ts-regexp end t)
8261 (re-search-forward org-ts-regexp-both end t))
8262 (org-time-string-to-seconds (match-string 0))
8263 (org-float-time now))))
8264 ((= dcst ?c)
8265 (let ((end (save-excursion (outline-next-heading) (point))))
8266 (if (re-search-forward
8267 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8268 end t)
8269 (org-time-string-to-seconds (match-string 0))
8270 (org-float-time now))))
8271 ((= dcst ?s)
8272 (let ((end (save-excursion (outline-next-heading) (point))))
8273 (if (re-search-forward org-scheduled-time-regexp end t)
8274 (org-time-string-to-seconds (match-string 1))
8275 (org-float-time now))))
8276 ((= dcst ?d)
8277 (let ((end (save-excursion (outline-next-heading) (point))))
8278 (if (re-search-forward org-deadline-time-regexp end t)
8279 (org-time-string-to-seconds (match-string 1))
8280 (org-float-time now))))
8281 ((= dcst ?p)
8282 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8283 (string-to-char (match-string 2))
8284 org-default-priority))
8285 ((= dcst ?r)
8286 (or (org-entry-get nil property) ""))
8287 ((= dcst ?o)
8288 (if (looking-at org-complex-heading-regexp)
8289 (- 9999 (length (member (match-string 2)
8290 org-todo-keywords-1)))))
8291 ((= dcst ?f)
8292 (if getkey-func
8293 (progn
8294 (setq tmp (funcall getkey-func))
8295 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8296 tmp)
8297 (error "Invalid key function `%s'" getkey-func)))
8298 (t (error "Invalid sorting type `%c'" sorting-type))))
8300 (cond
8301 ((= dcst ?a) 'string<)
8302 ((= dcst ?f) compare-func)
8303 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8304 (t nil)))))
8305 (run-hooks 'org-after-sorting-entries-or-items-hook)
8306 (message "Sorting entries...done")))
8308 (defun org-do-sort (table what &optional with-case sorting-type)
8309 "Sort TABLE of WHAT according to SORTING-TYPE.
8310 The user will be prompted for the SORTING-TYPE if the call to this
8311 function does not specify it. WHAT is only for the prompt, to indicate
8312 what is being sorted. The sorting key will be extracted from
8313 the car of the elements of the table.
8314 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8315 (unless sorting-type
8316 (message
8317 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8318 what)
8319 (setq sorting-type (read-char-exclusive)))
8320 (let ((dcst (downcase sorting-type))
8321 extractfun comparefun)
8322 ;; Define the appropriate functions
8323 (cond
8324 ((= dcst ?n)
8325 (setq extractfun 'string-to-number
8326 comparefun (if (= dcst sorting-type) '< '>)))
8327 ((= dcst ?a)
8328 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8329 (lambda(x) (downcase (org-sort-remove-invisible x))))
8330 comparefun (if (= dcst sorting-type)
8331 'string<
8332 (lambda (a b) (and (not (string< a b))
8333 (not (string= a b)))))))
8334 ((= dcst ?t)
8335 (setq extractfun
8336 (lambda (x)
8337 (if (or (string-match org-ts-regexp x)
8338 (string-match org-ts-regexp-both x))
8339 (org-float-time
8340 (org-time-string-to-time (match-string 0 x)))
8342 comparefun (if (= dcst sorting-type) '< '>)))
8343 (t (error "Invalid sorting type `%c'" sorting-type)))
8345 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8346 table)
8347 (lambda (a b) (funcall comparefun (car a) (car b))))))
8350 ;;; The orgstruct minor mode
8352 ;; Define a minor mode which can be used in other modes in order to
8353 ;; integrate the org-mode structure editing commands.
8355 ;; This is really a hack, because the org-mode structure commands use
8356 ;; keys which normally belong to the major mode. Here is how it
8357 ;; works: The minor mode defines all the keys necessary to operate the
8358 ;; structure commands, but wraps the commands into a function which
8359 ;; tests if the cursor is currently at a headline or a plain list
8360 ;; item. If that is the case, the structure command is used,
8361 ;; temporarily setting many Org-mode variables like regular
8362 ;; expressions for filling etc. However, when any of those keys is
8363 ;; used at a different location, function uses `key-binding' to look
8364 ;; up if the key has an associated command in another currently active
8365 ;; keymap (minor modes, major mode, global), and executes that
8366 ;; command. There might be problems if any of the keys is otherwise
8367 ;; used as a prefix key.
8369 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8370 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8371 ;; addresses this by checking explicitly for both bindings.
8373 (defvar orgstruct-mode-map (make-sparse-keymap)
8374 "Keymap for the minor `orgstruct-mode'.")
8376 (defvar org-local-vars nil
8377 "List of local variables, for use by `orgstruct-mode'.")
8379 ;;;###autoload
8380 (define-minor-mode orgstruct-mode
8381 "Toggle the minor mode `orgstruct-mode'.
8382 This mode is for using Org-mode structure commands in other
8383 modes. The following keys behave as if Org-mode were active, if
8384 the cursor is on a headline, or on a plain list item (both as
8385 defined by Org-mode).
8387 M-up Move entry/item up
8388 M-down Move entry/item down
8389 M-left Promote
8390 M-right Demote
8391 M-S-up Move entry/item up
8392 M-S-down Move entry/item down
8393 M-S-left Promote subtree
8394 M-S-right Demote subtree
8395 M-q Fill paragraph and items like in Org-mode
8396 C-c ^ Sort entries
8397 C-c - Cycle list bullet
8398 TAB Cycle item visibility
8399 M-RET Insert new heading/item
8400 S-M-RET Insert new TODO heading / Checkbox item
8401 C-c C-c Set tags / toggle checkbox"
8402 nil " OrgStruct" nil
8403 (org-load-modules-maybe)
8404 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8406 ;;;###autoload
8407 (defun turn-on-orgstruct ()
8408 "Unconditionally turn on `orgstruct-mode'."
8409 (orgstruct-mode 1))
8411 (defvar org-fb-vars nil)
8412 (make-variable-buffer-local 'org-fb-vars)
8413 (defun orgstruct++-mode (&optional arg)
8414 "Toggle `orgstruct-mode', the enhanced version of it.
8415 In addition to setting orgstruct-mode, this also exports all
8416 indentation and autofilling variables from org-mode into the
8417 buffer. It will also recognize item context in multiline items."
8418 (interactive "P")
8419 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8420 (if (< arg 1)
8421 (progn (orgstruct-mode -1)
8422 (mapc (lambda(v)
8423 (org-set-local (car v)
8424 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8425 org-fb-vars))
8426 (orgstruct-mode 1)
8427 (setq org-fb-vars nil)
8428 (let (var val)
8429 (mapc
8430 (lambda (x)
8431 (when (string-match
8432 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8433 (symbol-name (car x)))
8434 (setq var (car x) val (nth 1 x))
8435 (push (list var `(quote ,(eval var))) org-fb-vars)
8436 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8437 org-local-vars)
8438 (org-set-local 'orgstruct-is-++ t))))
8440 (defvar orgstruct-is-++ nil
8441 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8442 (make-variable-buffer-local 'orgstruct-is-++)
8444 ;;;###autoload
8445 (defun turn-on-orgstruct++ ()
8446 "Unconditionally turn on `orgstruct++-mode'."
8447 (orgstruct++-mode 1))
8449 (defun orgstruct-error ()
8450 "Error when there is no default binding for a structure key."
8451 (interactive)
8452 (error "This key has no function outside structure elements"))
8454 (defun orgstruct-setup ()
8455 "Setup orgstruct keymaps."
8456 (let ((nfunc 0)
8457 (bindings
8458 (list
8459 '([(meta up)] org-metaup)
8460 '([(meta down)] org-metadown)
8461 '([(meta left)] org-metaleft)
8462 '([(meta right)] org-metaright)
8463 '([(meta shift up)] org-shiftmetaup)
8464 '([(meta shift down)] org-shiftmetadown)
8465 '([(meta shift left)] org-shiftmetaleft)
8466 '([(meta shift right)] org-shiftmetaright)
8467 '([?\e (up)] org-metaup)
8468 '([?\e (down)] org-metadown)
8469 '([?\e (left)] org-metaleft)
8470 '([?\e (right)] org-metaright)
8471 '([?\e (shift up)] org-shiftmetaup)
8472 '([?\e (shift down)] org-shiftmetadown)
8473 '([?\e (shift left)] org-shiftmetaleft)
8474 '([?\e (shift right)] org-shiftmetaright)
8475 '([(shift up)] org-shiftup)
8476 '([(shift down)] org-shiftdown)
8477 '([(shift left)] org-shiftleft)
8478 '([(shift right)] org-shiftright)
8479 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8480 '("\M-q" fill-paragraph)
8481 '("\C-c^" org-sort)
8482 '("\C-c-" org-cycle-list-bullet)))
8483 elt key fun cmd)
8484 (while (setq elt (pop bindings))
8485 (setq nfunc (1+ nfunc))
8486 (setq key (org-key (car elt))
8487 fun (nth 1 elt)
8488 cmd (orgstruct-make-binding fun nfunc key))
8489 (org-defkey orgstruct-mode-map key cmd))
8491 ;; Special treatment needed for TAB and RET
8492 (org-defkey orgstruct-mode-map [(tab)]
8493 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8494 (org-defkey orgstruct-mode-map "\C-i"
8495 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8497 (org-defkey orgstruct-mode-map "\M-\C-m"
8498 (orgstruct-make-binding 'org-insert-heading 105
8499 "\M-\C-m" [(meta return)]))
8500 (org-defkey orgstruct-mode-map [(meta return)]
8501 (orgstruct-make-binding 'org-insert-heading 106
8502 [(meta return)] "\M-\C-m"))
8504 (org-defkey orgstruct-mode-map [(shift meta return)]
8505 (orgstruct-make-binding 'org-insert-todo-heading 107
8506 [(meta return)] "\M-\C-m"))
8508 (org-defkey orgstruct-mode-map "\e\C-m"
8509 (orgstruct-make-binding 'org-insert-heading 108
8510 "\e\C-m" [?\e (return)]))
8511 (org-defkey orgstruct-mode-map [?\e (return)]
8512 (orgstruct-make-binding 'org-insert-heading 109
8513 [?\e (return)] "\e\C-m"))
8514 (org-defkey orgstruct-mode-map [?\e (shift return)]
8515 (orgstruct-make-binding 'org-insert-todo-heading 110
8516 [?\e (return)] "\e\C-m"))
8518 (unless org-local-vars
8519 (setq org-local-vars (org-get-local-variables)))
8523 (defun orgstruct-make-binding (fun n &rest keys)
8524 "Create a function for binding in the structure minor mode.
8525 FUN is the command to call inside a table. N is used to create a unique
8526 command name. KEYS are keys that should be checked in for a command
8527 to execute outside of tables."
8528 (eval
8529 (list 'defun
8530 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8531 '(arg)
8532 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8533 "Outside of structure, run the binding of `"
8534 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8535 "'.")
8536 '(interactive "p")
8537 (list 'if
8538 `(org-context-p 'headline 'item
8539 (and orgstruct-is-++
8540 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8541 'item-body))
8542 (list 'org-run-like-in-org-mode (list 'quote fun))
8543 (list 'let '(orgstruct-mode)
8544 (list 'call-interactively
8545 (append '(or)
8546 (mapcar (lambda (k)
8547 (list 'key-binding k))
8548 keys)
8549 '('orgstruct-error))))))))
8551 (defun org-context-p (&rest contexts)
8552 "Check if local context is any of CONTEXTS.
8553 Possible values in the list of contexts are `table', `headline', and `item'."
8554 (let ((pos (point)))
8555 (goto-char (point-at-bol))
8556 (prog1 (or (and (memq 'table contexts)
8557 (looking-at "[ \t]*|"))
8558 (and (memq 'headline contexts)
8559 (looking-at org-outline-regexp))
8560 (and (memq 'item contexts)
8561 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8562 (and (memq 'item-body contexts)
8563 (org-in-item-p)))
8564 (goto-char pos))))
8566 (defun org-get-local-variables ()
8567 "Return a list of all local variables in an org-mode buffer."
8568 (let (varlist)
8569 (with-current-buffer (get-buffer-create "*Org tmp*")
8570 (erase-buffer)
8571 (org-mode)
8572 (setq varlist (buffer-local-variables)))
8573 (kill-buffer "*Org tmp*")
8574 (delq nil
8575 (mapcar
8576 (lambda (x)
8577 (setq x
8578 (if (symbolp x)
8579 (list x)
8580 (list (car x) (list 'quote (cdr x)))))
8581 (if (string-match
8582 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8583 (symbol-name (car x)))
8584 x nil))
8585 varlist))))
8587 (defun org-clone-local-variables (from-buffer &optional regexp)
8588 "Clone local variables from FROM-BUFFER.
8589 Optional argument REGEXP selects variables to clone."
8590 (mapc
8591 (lambda (pair)
8592 (and (symbolp (car pair))
8593 (or (null regexp)
8594 (string-match regexp (symbol-name (car pair))))
8595 (set (make-local-variable (car pair))
8596 (cdr pair))))
8597 (buffer-local-variables from-buffer)))
8599 ;;;###autoload
8600 (defun org-run-like-in-org-mode (cmd)
8601 "Run a command, pretending that the current buffer is in Org-mode.
8602 This will temporarily bind local variables that are typically bound in
8603 Org-mode to the values they have in Org-mode, and then interactively
8604 call CMD."
8605 (org-load-modules-maybe)
8606 (unless org-local-vars
8607 (setq org-local-vars (org-get-local-variables)))
8608 (eval (list 'let org-local-vars
8609 (list 'call-interactively (list 'quote cmd)))))
8611 ;;;; Archiving
8613 (defun org-get-category (&optional pos force-refresh)
8614 "Get the category applying to position POS."
8615 (save-match-data
8616 (if force-refresh (org-refresh-category-properties))
8617 (let ((pos (or pos (point))))
8618 (or (get-text-property pos 'org-category)
8619 (progn (org-refresh-category-properties)
8620 (get-text-property pos 'org-category))))))
8622 (defun org-refresh-category-properties ()
8623 "Refresh category text properties in the buffer."
8624 (let ((inhibit-read-only t)
8625 (def-cat (cond
8626 ((null org-category)
8627 (if buffer-file-name
8628 (file-name-sans-extension
8629 (file-name-nondirectory buffer-file-name))
8630 "???"))
8631 ((symbolp org-category) (symbol-name org-category))
8632 (t org-category)))
8633 beg end cat pos optionp)
8634 (org-unmodified
8635 (save-excursion
8636 (save-restriction
8637 (widen)
8638 (goto-char (point-min))
8639 (put-text-property (point) (point-max) 'org-category def-cat)
8640 (while (re-search-forward
8641 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8642 (setq pos (match-end 0)
8643 optionp (equal (char-after (match-beginning 0)) ?#)
8644 cat (org-trim (match-string 2)))
8645 (if optionp
8646 (setq beg (point-at-bol) end (point-max))
8647 (org-back-to-heading t)
8648 (setq beg (point) end (org-end-of-subtree t t)))
8649 (put-text-property beg end 'org-category cat)
8650 (put-text-property beg end 'org-category-position beg)
8651 (goto-char pos)))))))
8654 ;;;; Link Stuff
8656 ;;; Link abbreviations
8658 (defun org-link-expand-abbrev (link)
8659 "Apply replacements as defined in `org-link-abbrev-alist'."
8660 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8661 (let* ((key (match-string 1 link))
8662 (as (or (assoc key org-link-abbrev-alist-local)
8663 (assoc key org-link-abbrev-alist)))
8664 (tag (and (match-end 2) (match-string 3 link)))
8665 rpl)
8666 (if (not as)
8667 link
8668 (setq rpl (cdr as))
8669 (cond
8670 ((symbolp rpl) (funcall rpl tag))
8671 ((string-match "%(\\([^)]+\\))" rpl)
8672 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8673 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8674 ((string-match "%h" rpl)
8675 (replace-match (url-hexify-string (or tag "")) t t rpl))
8676 (t (concat rpl tag)))))
8677 link))
8679 ;;; Storing and inserting links
8681 (defvar org-insert-link-history nil
8682 "Minibuffer history for links inserted with `org-insert-link'.")
8684 (defvar org-stored-links nil
8685 "Contains the links stored with `org-store-link'.")
8687 (defvar org-store-link-plist nil
8688 "Plist with info about the most recently link created with `org-store-link'.")
8690 (defvar org-link-protocols nil
8691 "Link protocols added to Org-mode using `org-add-link-type'.")
8693 (defvar org-store-link-functions nil
8694 "List of functions that are called to create and store a link.
8695 Each function will be called in turn until one returns a non-nil
8696 value. Each function should check if it is responsible for creating
8697 this link (for example by looking at the major mode).
8698 If not, it must exit and return nil.
8699 If yes, it should return a non-nil value after a calling
8700 `org-store-link-props' with a list of properties and values.
8701 Special properties are:
8703 :type The link prefix, like \"http\". This must be given.
8704 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8705 This is obligatory as well.
8706 :description Optional default description for the second pair
8707 of brackets in an Org-mode link. The user can still change
8708 this when inserting this link into an Org-mode buffer.
8710 In addition to these, any additional properties can be specified
8711 and then used in remember templates.")
8713 (defun org-add-link-type (type &optional follow export)
8714 "Add TYPE to the list of `org-link-types'.
8715 Re-compute all regular expressions depending on `org-link-types'
8717 FOLLOW and EXPORT are two functions.
8719 FOLLOW should take the link path as the single argument and do whatever
8720 is necessary to follow the link, for example find a file or display
8721 a mail message.
8723 EXPORT should format the link path for export to one of the export formats.
8724 It should be a function accepting three arguments:
8726 path the path of the link, the text after the prefix (like \"http:\")
8727 desc the description of the link, if any, or a description added by
8728 org-export-normalize-links if there is none
8729 format the export format, a symbol like `html' or `latex' or `ascii'..
8731 The function may use the FORMAT information to return different values
8732 depending on the format. The return value will be put literally into
8733 the exported file. If the return value is nil, this means Org should
8734 do what it normally does with links which do not have EXPORT defined.
8736 Org-mode has a built-in default for exporting links. If you are happy with
8737 this default, there is no need to define an export function for the link
8738 type. For a simple example of an export function, see `org-bbdb.el'."
8739 (add-to-list 'org-link-types type t)
8740 (org-make-link-regexps)
8741 (if (assoc type org-link-protocols)
8742 (setcdr (assoc type org-link-protocols) (list follow export))
8743 (push (list type follow export) org-link-protocols)))
8745 (defvar org-agenda-buffer-name)
8747 ;;;###autoload
8748 (defun org-store-link (arg)
8749 "\\<org-mode-map>Store an org-link to the current location.
8750 This link is added to `org-stored-links' and can later be inserted
8751 into an org-buffer with \\[org-insert-link].
8753 For some link types, a prefix arg is interpreted:
8754 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8755 For file links, arg negates `org-context-in-file-links'."
8756 (interactive "P")
8757 (org-load-modules-maybe)
8758 (setq org-store-link-plist nil) ; reset
8759 (org-with-limited-levels
8760 (let (link cpltxt desc description search txt custom-id agenda-link)
8761 (cond
8763 ((run-hook-with-args-until-success 'org-store-link-functions)
8764 (setq link (plist-get org-store-link-plist :link)
8765 desc (or (plist-get org-store-link-plist :description) link)))
8767 ((org-src-edit-buffer-p)
8768 (let (label gc)
8769 (while (or (not label)
8770 (save-excursion
8771 (save-restriction
8772 (widen)
8773 (goto-char (point-min))
8774 (re-search-forward
8775 (regexp-quote (format org-coderef-label-format label))
8776 nil t))))
8777 (when label (message "Label exists already") (sit-for 2))
8778 (setq label (read-string "Code line label: " label)))
8779 (end-of-line 1)
8780 (setq link (format org-coderef-label-format label))
8781 (setq gc (- 79 (length link)))
8782 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8783 (insert link)
8784 (setq link (concat "(" label ")") desc nil)))
8786 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8787 ;; We are in the agenda, link to referenced location
8788 (let ((m (or (get-text-property (point) 'org-hd-marker)
8789 (get-text-property (point) 'org-marker))))
8790 (when m
8791 (org-with-point-at m
8792 (setq agenda-link
8793 (if (org-called-interactively-p 'any)
8794 (call-interactively 'org-store-link)
8795 (org-store-link nil)))))))
8797 ((eq major-mode 'calendar-mode)
8798 (let ((cd (calendar-cursor-to-date)))
8799 (setq link
8800 (format-time-string
8801 (car org-time-stamp-formats)
8802 (apply 'encode-time
8803 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8804 nil nil nil))))
8805 (org-store-link-props :type "calendar" :date cd)))
8807 ((eq major-mode 'w3-mode)
8808 (setq cpltxt (if (and (buffer-name)
8809 (not (string-match "Untitled" (buffer-name))))
8810 (buffer-name)
8811 (url-view-url t))
8812 link (org-make-link (url-view-url t)))
8813 (org-store-link-props :type "w3" :url (url-view-url t)))
8815 ((eq major-mode 'w3m-mode)
8816 (setq cpltxt (or w3m-current-title w3m-current-url)
8817 link (org-make-link w3m-current-url))
8818 (org-store-link-props :type "w3m" :url (url-view-url t)))
8820 ((setq search (run-hook-with-args-until-success
8821 'org-create-file-search-functions))
8822 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8823 "::" search))
8824 (setq cpltxt (or description link)))
8826 ((eq major-mode 'image-mode)
8827 (setq cpltxt (concat "file:"
8828 (abbreviate-file-name buffer-file-name))
8829 link (org-make-link cpltxt))
8830 (org-store-link-props :type "image" :file buffer-file-name))
8832 ((eq major-mode 'dired-mode)
8833 ;; link to the file in the current line
8834 (let ((file (dired-get-filename nil t)))
8835 (setq file (if file
8836 (abbreviate-file-name
8837 (expand-file-name (dired-get-filename nil t)))
8838 ;; otherwise, no file so use current directory.
8839 default-directory))
8840 (setq cpltxt (concat "file:" file)
8841 link (org-make-link cpltxt))))
8843 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8844 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8845 (cond
8846 ((org-in-regexp "<<\\(.*?\\)>>")
8847 (setq cpltxt
8848 (concat "file:"
8849 (abbreviate-file-name
8850 (buffer-file-name (buffer-base-buffer)))
8851 "::" (match-string 1))
8852 link (org-make-link cpltxt)))
8853 ((and (featurep 'org-id)
8854 (or (eq org-link-to-org-use-id t)
8855 (and (eq org-link-to-org-use-id 'create-if-interactive)
8856 (org-called-interactively-p 'any))
8857 (and (eq org-link-to-org-use-id
8858 'create-if-interactive-and-no-custom-id)
8859 (org-called-interactively-p 'any)
8860 (not custom-id))
8861 (and org-link-to-org-use-id
8862 (org-entry-get nil "ID"))))
8863 ;; We can make a link using the ID.
8864 (setq link (condition-case nil
8865 (prog1 (org-id-store-link)
8866 (setq desc (plist-get org-store-link-plist
8867 :description)))
8868 (error
8869 ;; probably before first headline, link to file only
8870 (concat "file:"
8871 (abbreviate-file-name
8872 (buffer-file-name (buffer-base-buffer))))))))
8874 ;; Just link to current headline
8875 (setq cpltxt (concat "file:"
8876 (abbreviate-file-name
8877 (buffer-file-name (buffer-base-buffer)))))
8878 ;; Add a context search string
8879 (when (org-xor org-context-in-file-links arg)
8880 (setq txt (cond
8881 ((org-at-heading-p) nil)
8882 ((org-region-active-p)
8883 (buffer-substring (region-beginning) (region-end)))
8884 (t nil)))
8885 (when (or (null txt) (string-match "\\S-" txt))
8886 (setq cpltxt
8887 (concat cpltxt "::"
8888 (condition-case nil
8889 (org-make-org-heading-search-string txt)
8890 (error "")))
8891 desc (or (nth 4 (ignore-errors
8892 (org-heading-components))) "NONE"))))
8893 (if (string-match "::\\'" cpltxt)
8894 (setq cpltxt (substring cpltxt 0 -2)))
8895 (setq link (org-make-link cpltxt)))))
8897 ((buffer-file-name (buffer-base-buffer))
8898 ;; Just link to this file here.
8899 (setq cpltxt (concat "file:"
8900 (abbreviate-file-name
8901 (buffer-file-name (buffer-base-buffer)))))
8902 ;; Add a context string
8903 (when (org-xor org-context-in-file-links arg)
8904 (setq txt (if (org-region-active-p)
8905 (buffer-substring (region-beginning) (region-end))
8906 (buffer-substring (point-at-bol) (point-at-eol))))
8907 ;; Only use search option if there is some text.
8908 (when (string-match "\\S-" txt)
8909 (setq cpltxt
8910 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8911 desc "NONE")))
8912 (setq link (org-make-link cpltxt)))
8914 ((org-called-interactively-p 'interactive)
8915 (error "Cannot link to a buffer which is not visiting a file"))
8917 (t (setq link nil)))
8919 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8920 (setq link (or link cpltxt)
8921 desc (or desc cpltxt))
8922 (if (equal desc "NONE") (setq desc nil))
8924 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8925 (progn
8926 (setq org-stored-links
8927 (cons (list link desc) org-stored-links))
8928 (message "Stored: %s" (or desc link))
8929 (when custom-id
8930 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8931 "::#" custom-id))
8932 (setq org-stored-links
8933 (cons (list link desc) org-stored-links))))
8934 (or agenda-link (and link (org-make-link-string link desc)))))))
8936 (defun org-store-link-props (&rest plist)
8937 "Store link properties, extract names and addresses."
8938 (let (x adr)
8939 (when (setq x (plist-get plist :from))
8940 (setq adr (mail-extract-address-components x))
8941 (setq plist (plist-put plist :fromname (car adr)))
8942 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8943 (when (setq x (plist-get plist :to))
8944 (setq adr (mail-extract-address-components x))
8945 (setq plist (plist-put plist :toname (car adr)))
8946 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8947 (let ((from (plist-get plist :from))
8948 (to (plist-get plist :to)))
8949 (when (and from to org-from-is-user-regexp)
8950 (setq plist
8951 (plist-put plist :fromto
8952 (if (string-match org-from-is-user-regexp from)
8953 (concat "to %t")
8954 (concat "from %f"))))))
8955 (setq org-store-link-plist plist))
8957 (defun org-add-link-props (&rest plist)
8958 "Add these properties to the link property list."
8959 (let (key value)
8960 (while plist
8961 (setq key (pop plist) value (pop plist))
8962 (setq org-store-link-plist
8963 (plist-put org-store-link-plist key value)))))
8965 (defun org-email-link-description (&optional fmt)
8966 "Return the description part of an email link.
8967 This takes information from `org-store-link-plist' and formats it
8968 according to FMT (default from `org-email-link-description-format')."
8969 (setq fmt (or fmt org-email-link-description-format))
8970 (let* ((p org-store-link-plist)
8971 (to (plist-get p :toaddress))
8972 (from (plist-get p :fromaddress))
8973 (table
8974 (list
8975 (cons "%c" (plist-get p :fromto))
8976 (cons "%F" (plist-get p :from))
8977 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8978 (cons "%T" (plist-get p :to))
8979 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8980 (cons "%s" (plist-get p :subject))
8981 (cons "%d" (plist-get p :date))
8982 (cons "%m" (plist-get p :message-id)))))
8983 (when (string-match "%c" fmt)
8984 ;; Check if the user wrote this message
8985 (if (and org-from-is-user-regexp from to
8986 (save-match-data (string-match org-from-is-user-regexp from)))
8987 (setq fmt (replace-match "to %t" t t fmt))
8988 (setq fmt (replace-match "from %f" t t fmt))))
8989 (org-replace-escapes fmt table)))
8991 (defun org-make-org-heading-search-string (&optional string heading)
8992 "Make search string for STRING or current headline."
8993 (interactive)
8994 (let ((s (or string (org-get-heading)))
8995 (lines org-context-in-file-links))
8996 (unless (and string (not heading))
8997 ;; We are using a headline, clean up garbage in there.
8998 (if (string-match org-todo-regexp s)
8999 (setq s (replace-match "" t t s)))
9000 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9001 (setq s (replace-match "" t t s)))
9002 (setq s (org-trim s))
9003 (if (string-match (concat "^\\(" org-quote-string "\\|"
9004 org-comment-string "\\)") s)
9005 (setq s (replace-match "" t t s)))
9006 (while (string-match org-ts-regexp s)
9007 (setq s (replace-match "" t t s))))
9008 (or string (setq s (concat "*" s))) ; Add * for headlines
9009 (when (and string (integerp lines) (> lines 0))
9010 (let ((slines (org-split-string s "\n")))
9011 (when (< lines (length slines))
9012 (setq s (mapconcat
9013 'identity
9014 (reverse (nthcdr (- (length slines) lines)
9015 (reverse slines))) "\n")))))
9016 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9018 (defun org-make-link (&rest strings)
9019 "Concatenate STRINGS."
9020 (apply 'concat strings))
9022 (defun org-make-link-string (link &optional description)
9023 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9024 (unless (string-match "\\S-" link)
9025 (error "Empty link"))
9026 (when (and description
9027 (stringp description)
9028 (not (string-match "\\S-" description)))
9029 (setq description nil))
9030 (when (stringp description)
9031 ;; Remove brackets from the description, they are fatal.
9032 (while (string-match "\\[" description)
9033 (setq description (replace-match "{" t t description)))
9034 (while (string-match "\\]" description)
9035 (setq description (replace-match "}" t t description))))
9036 (when (equal link description)
9037 ;; No description needed, it is identical
9038 (setq description nil))
9039 (when (and (not description)
9040 (not (string-match (org-image-file-name-regexp) link))
9041 (not (equal link (org-link-escape link))))
9042 (setq description (org-extract-attributes link)))
9043 (setq link
9044 (cond ((string-match (org-image-file-name-regexp) link) link)
9045 ((string-match org-link-types-re link)
9046 (concat (match-string 1 link)
9047 (org-link-escape (substring link (match-end 1)))))
9048 (t (org-link-escape link))))
9049 (concat "[[" link "]"
9050 (if description (concat "[" description "]") "")
9051 "]"))
9053 (defconst org-link-escape-chars
9054 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9055 "List of characters that should be escaped in link.
9056 This is the list that is used for internal purposes.")
9058 (defvar org-url-encoding-use-url-hexify nil)
9060 (defconst org-link-escape-chars-browser
9061 '(?\ )
9062 "List of escapes for characters that are problematic in links.
9063 This is the list that is used before handing over to the browser.")
9065 (defun org-link-escape (text &optional table merge)
9066 "Return percent escaped representation of TEXT.
9067 TEXT is a string with the text to escape.
9068 Optional argument TABLE is a list with characters that should be
9069 escaped. When nil, `org-link-escape-chars' is used.
9070 If optional argument MERGE is set, merge TABLE into
9071 `org-link-escape-chars'."
9072 (if (and org-url-encoding-use-url-hexify (not table))
9073 (url-hexify-string text)
9074 (cond
9075 ((and table merge)
9076 (mapc (lambda (defchr)
9077 (unless (member defchr table)
9078 (setq table (cons defchr table)))) org-link-escape-chars))
9079 ((null table)
9080 (setq table org-link-escape-chars)))
9081 (mapconcat
9082 (lambda (char)
9083 (if (or (member char table)
9084 (< char 32) (= char 37) (> char 126))
9085 (mapconcat (lambda (sequence-element)
9086 (format "%%%.2X" sequence-element))
9087 (or (encode-coding-char char 'utf-8)
9088 (error "Unable to percent escape character: %s"
9089 (char-to-string char))) "")
9090 (char-to-string char))) text "")))
9092 (defun org-link-unescape (str)
9093 "Unhex hexified Unicode strings as returned from the JavaScript function
9094 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9095 (unless (and (null str) (string= "" str))
9096 (let ((pos 0) (case-fold-search t) unhexed)
9097 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9098 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9099 (setq str (replace-match unhexed t t str))
9100 (setq pos (+ pos (length unhexed))))))
9101 str)
9103 (defun org-link-unescape-compound (hex)
9104 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9105 Note: this function also decodes single byte encodings like
9106 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9107 (save-match-data
9108 (let* ((bytes (cdr (split-string hex "%")))
9109 (ret "")
9110 (eat 0)
9111 (sum 0))
9112 (while bytes
9113 (let* ((val (string-to-number (pop bytes) 16))
9114 (shift-xor
9115 (if (= 0 eat)
9116 (cond
9117 ((>= val 252) (cons 6 252))
9118 ((>= val 248) (cons 5 248))
9119 ((>= val 240) (cons 4 240))
9120 ((>= val 224) (cons 3 224))
9121 ((>= val 192) (cons 2 192))
9122 (t (cons 0 0)))
9123 (cons 6 128))))
9124 (if (>= val 192) (setq eat (car shift-xor)))
9125 (setq val (logxor val (cdr shift-xor)))
9126 (setq sum (+ (lsh sum (car shift-xor)) val))
9127 (if (> eat 0) (setq eat (- eat 1)))
9128 (cond
9129 ((= 0 eat) ;multi byte
9130 (setq ret (concat ret (org-char-to-string sum)))
9131 (setq sum 0))
9132 ((not bytes) ; single byte(s)
9133 (setq ret (org-link-unescape-single-byte-sequence hex))))
9134 )) ;; end (while bytes
9135 ret )))
9137 (defun org-link-unescape-single-byte-sequence (hex)
9138 "Unhexify hex-encoded single byte character sequences."
9139 (mapconcat (lambda (byte)
9140 (char-to-string (string-to-number byte 16)))
9141 (cdr (split-string hex "%")) ""))
9143 (defun org-xor (a b)
9144 "Exclusive or."
9145 (if a (not b) b))
9147 (defun org-fixup-message-id-for-http (s)
9148 "Replace special characters in a message id, so it can be used in an http query."
9149 (when (string-match "%" s)
9150 (setq s (mapconcat (lambda (c)
9151 (if (eq c ?%)
9152 "%25"
9153 (char-to-string c)))
9154 s "")))
9155 (while (string-match "<" s)
9156 (setq s (replace-match "%3C" t t s)))
9157 (while (string-match ">" s)
9158 (setq s (replace-match "%3E" t t s)))
9159 (while (string-match "@" s)
9160 (setq s (replace-match "%40" t t s)))
9163 (defun org-link-prettify (link)
9164 "Return a human-readable representation of LINK.
9165 The car of LINK must be a raw link the cdr of LINK must be either
9166 a link description or nil."
9167 (let ((desc (or (cadr link) "<no description>")))
9168 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9169 "[[" (car link) "]]")))
9171 ;;;###autoload
9172 (defun org-insert-link-global ()
9173 "Insert a link like Org-mode does.
9174 This command can be called in any mode to insert a link in Org-mode syntax."
9175 (interactive)
9176 (org-load-modules-maybe)
9177 (org-run-like-in-org-mode 'org-insert-link))
9179 (defun org-insert-link (&optional complete-file link-location default-description)
9180 "Insert a link. At the prompt, enter the link.
9182 Completion can be used to insert any of the link protocol prefixes like
9183 http or ftp in use.
9185 The history can be used to select a link previously stored with
9186 `org-store-link'. When the empty string is entered (i.e. if you just
9187 press RET at the prompt), the link defaults to the most recently
9188 stored link. As SPC triggers completion in the minibuffer, you need to
9189 use M-SPC or C-q SPC to force the insertion of a space character.
9191 You will also be prompted for a description, and if one is given, it will
9192 be displayed in the buffer instead of the link.
9194 If there is already a link at point, this command will allow you to edit link
9195 and description parts.
9197 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9198 be selected using completion. The path to the file will be relative to the
9199 current directory if the file is in the current directory or a subdirectory.
9200 Otherwise, the link will be the absolute path as completed in the minibuffer
9201 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9202 option `org-link-file-path-type'.
9204 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9205 the current directory or below.
9207 With three \\[universal-argument] prefixes, negate the meaning of
9208 `org-keep-stored-link-after-insertion'.
9210 If `org-make-link-description-function' is non-nil, this function will be
9211 called with the link target, and the result will be the default
9212 link description.
9214 If the LINK-LOCATION parameter is non-nil, this value will be
9215 used as the link location instead of reading one interactively.
9217 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9218 be used as the default description."
9219 (interactive "P")
9220 (let* ((wcf (current-window-configuration))
9221 (region (if (org-region-active-p)
9222 (buffer-substring (region-beginning) (region-end))))
9223 (remove (and region (list (region-beginning) (region-end))))
9224 (desc region)
9225 tmphist ; byte-compile incorrectly complains about this
9226 (link link-location)
9227 entry file all-prefixes)
9228 (cond
9229 (link-location) ; specified by arg, just use it.
9230 ((org-in-regexp org-bracket-link-regexp 1)
9231 ;; We do have a link at point, and we are going to edit it.
9232 (setq remove (list (match-beginning 0) (match-end 0)))
9233 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9234 (setq link (read-string "Link: "
9235 (org-link-unescape
9236 (org-match-string-no-properties 1)))))
9237 ((or (org-in-regexp org-angle-link-re)
9238 (org-in-regexp org-plain-link-re))
9239 ;; Convert to bracket link
9240 (setq remove (list (match-beginning 0) (match-end 0))
9241 link (read-string "Link: "
9242 (org-remove-angle-brackets (match-string 0)))))
9243 ((member complete-file '((4) (16)))
9244 ;; Completing read for file names.
9245 (setq link (org-file-complete-link complete-file)))
9247 ;; Read link, with completion for stored links.
9248 (with-output-to-temp-buffer "*Org Links*"
9249 (princ "Insert a link.
9250 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9251 (when org-stored-links
9252 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9253 (princ (mapconcat 'org-link-prettify
9254 (reverse org-stored-links) "\n"))))
9255 (let ((cw (selected-window)))
9256 (select-window (get-buffer-window "*Org Links*" 'visible))
9257 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9258 (unless (pos-visible-in-window-p (point-max))
9259 (org-fit-window-to-buffer))
9260 (and (window-live-p cw) (select-window cw)))
9261 ;; Fake a link history, containing the stored links.
9262 (setq tmphist (append (mapcar 'car org-stored-links)
9263 org-insert-link-history))
9264 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9265 (mapcar 'car org-link-abbrev-alist)
9266 org-link-types))
9267 (unwind-protect
9268 (progn
9269 (setq link
9270 (let ((org-completion-use-ido nil)
9271 (org-completion-use-iswitchb nil))
9272 (org-completing-read
9273 "Link: "
9274 (append
9275 (mapcar (lambda (x) (list (concat x ":")))
9276 all-prefixes)
9277 (mapcar 'car org-stored-links))
9278 nil nil nil
9279 'tmphist
9280 (car (car org-stored-links)))))
9281 (if (not (string-match "\\S-" link))
9282 (error "No link selected"))
9283 (if (or (member link all-prefixes)
9284 (and (equal ":" (substring link -1))
9285 (member (substring link 0 -1) all-prefixes)
9286 (setq link (substring link 0 -1))))
9287 (setq link (org-link-try-special-completion link))))
9288 (set-window-configuration wcf)
9289 (kill-buffer "*Org Links*"))
9290 (setq entry (assoc link org-stored-links))
9291 (or entry (push link org-insert-link-history))
9292 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9293 (not org-keep-stored-link-after-insertion))
9294 (setq org-stored-links (delq (assoc link org-stored-links)
9295 org-stored-links)))
9296 (setq desc (or desc (nth 1 entry)))))
9298 (if (string-match org-plain-link-re link)
9299 ;; URL-like link, normalize the use of angular brackets.
9300 (setq link (org-make-link (org-remove-angle-brackets link))))
9302 ;; Check if we are linking to the current file with a search option
9303 ;; If yes, simplify the link by using only the search option.
9304 (when (and buffer-file-name
9305 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9306 (let* ((path (match-string 1 link))
9307 (case-fold-search nil)
9308 (search (match-string 2 link)))
9309 (save-match-data
9310 (if (equal (file-truename buffer-file-name) (file-truename path))
9311 ;; We are linking to this same file, with a search option
9312 (setq link search)))))
9314 ;; Check if we can/should use a relative path. If yes, simplify the link
9315 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9316 (let* ((type (match-string 1 link))
9317 (path (match-string 2 link))
9318 (origpath path)
9319 (case-fold-search nil))
9320 (cond
9321 ((or (eq org-link-file-path-type 'absolute)
9322 (equal complete-file '(16)))
9323 (setq path (abbreviate-file-name (expand-file-name path))))
9324 ((eq org-link-file-path-type 'noabbrev)
9325 (setq path (expand-file-name path)))
9326 ((eq org-link-file-path-type 'relative)
9327 (setq path (file-relative-name path)))
9329 (save-match-data
9330 (if (string-match (concat "^" (regexp-quote
9331 (expand-file-name
9332 (file-name-as-directory
9333 default-directory))))
9334 (expand-file-name path))
9335 ;; We are linking a file with relative path name.
9336 (setq path (substring (expand-file-name path)
9337 (match-end 0)))
9338 (setq path (abbreviate-file-name (expand-file-name path)))))))
9339 (setq link (concat type path))
9340 (if (equal desc origpath)
9341 (setq desc path))))
9343 (if org-make-link-description-function
9344 (setq desc (funcall org-make-link-description-function link desc))
9345 (if default-description (setq desc default-description)))
9347 (setq desc (read-string "Description: " desc))
9348 (unless (string-match "\\S-" desc) (setq desc nil))
9349 (if remove (apply 'delete-region remove))
9350 (insert (org-make-link-string link desc))))
9352 (defun org-link-try-special-completion (type)
9353 "If there is completion support for link type TYPE, offer it."
9354 (let ((fun (intern (concat "org-" type "-complete-link"))))
9355 (if (functionp fun)
9356 (funcall fun)
9357 (read-string "Link (no completion support): " (concat type ":")))))
9359 (defun org-file-complete-link (&optional arg)
9360 "Create a file link using completion."
9361 (let (file link)
9362 (setq file (read-file-name "File: "))
9363 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9364 (pwd1 (file-name-as-directory (abbreviate-file-name
9365 (expand-file-name ".")))))
9366 (cond
9367 ((equal arg '(16))
9368 (setq link (org-make-link
9369 "file:"
9370 (abbreviate-file-name (expand-file-name file)))))
9371 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9372 (setq link (org-make-link "file:" (match-string 1 file))))
9373 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9374 (expand-file-name file))
9375 (setq link (org-make-link
9376 "file:" (match-string 1 (expand-file-name file)))))
9377 (t (setq link (org-make-link "file:" file)))))
9378 link))
9380 (defun org-completing-read (&rest args)
9381 "Completing-read with SPACE being a normal character."
9382 (let ((enable-recursive-minibuffers t)
9383 (minibuffer-local-completion-map
9384 (copy-keymap minibuffer-local-completion-map)))
9385 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9386 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9387 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9388 (apply 'org-icompleting-read args)))
9390 (defun org-completing-read-no-i (&rest args)
9391 (let (org-completion-use-ido org-completion-use-iswitchb)
9392 (apply 'org-completing-read args)))
9394 (defun org-iswitchb-completing-read (prompt choices &rest args)
9395 "Use iswitch as a completing-read replacement to choose from choices.
9396 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9397 from."
9398 (let* ((iswitchb-use-virtual-buffers nil)
9399 (iswitchb-make-buflist-hook
9400 (lambda ()
9401 (setq iswitchb-temp-buflist choices))))
9402 (iswitchb-read-buffer prompt)))
9404 (defun org-icompleting-read (&rest args)
9405 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9406 (org-without-partial-completion
9407 (if (and org-completion-use-ido
9408 (fboundp 'ido-completing-read)
9409 (boundp 'ido-mode) ido-mode
9410 (listp (second args)))
9411 (let ((ido-enter-matching-directory nil))
9412 (apply 'ido-completing-read (concat (car args))
9413 (if (consp (car (nth 1 args)))
9414 (mapcar 'car (nth 1 args))
9415 (nth 1 args))
9416 (cddr args)))
9417 (if (and org-completion-use-iswitchb
9418 (boundp 'iswitchb-mode) iswitchb-mode
9419 (listp (second args)))
9420 (apply 'org-iswitchb-completing-read (concat (car args))
9421 (if (consp (car (nth 1 args)))
9422 (mapcar 'car (nth 1 args))
9423 (nth 1 args))
9424 (cddr args))
9425 (apply 'completing-read args)))))
9427 (defun org-extract-attributes (s)
9428 "Extract the attributes cookie from a string and set as text property."
9429 (let (a attr (start 0) key value)
9430 (save-match-data
9431 (when (string-match "{{\\([^}]+\\)}}$" s)
9432 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9433 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9434 (setq key (match-string 1 a) value (match-string 2 a)
9435 start (match-end 0)
9436 attr (plist-put attr (intern key) value))))
9437 (org-add-props s nil 'org-attr attr))
9440 (defun org-extract-attributes-from-string (tag)
9441 (let (key value attr)
9442 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9443 (setq key (match-string 1 tag) value (match-string 2 tag)
9444 tag (replace-match "" t t tag)
9445 attr (plist-put attr (intern key) value)))
9446 (cons tag attr)))
9448 (defun org-attributes-to-string (plist)
9449 "Format a property list into an HTML attribute list."
9450 (let ((s "") key value)
9451 (while plist
9452 (setq key (pop plist) value (pop plist))
9453 (and value
9454 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9457 ;;; Opening/following a link
9459 (defvar org-link-search-failed nil)
9461 (defvar org-open-link-functions nil
9462 "Hook for functions finding a plain text link.
9463 These functions must take a single argument, the link content.
9464 They will be called for links that look like [[link text][description]]
9465 when LINK TEXT does not have a protocol like \"http:\" and does not look
9466 like a filename (e.g. \"./blue.png\").
9468 These functions will be called *before* Org attempts to resolve the
9469 link by doing text searches in the current buffer - so if you want a
9470 link \"[[target]]\" to still find \"<<target>>\", your function should
9471 handle this as a special case.
9473 When the function does handle the link, it must return a non-nil value.
9474 If it decides that it is not responsible for this link, it must return
9475 nil to indicate that that Org-mode can continue with other options
9476 like exact and fuzzy text search.")
9478 (defun org-next-link ()
9479 "Move forward to the next link.
9480 If the link is in hidden text, expose it."
9481 (interactive)
9482 (when (and org-link-search-failed (eq this-command last-command))
9483 (goto-char (point-min))
9484 (message "Link search wrapped back to beginning of buffer"))
9485 (setq org-link-search-failed nil)
9486 (let* ((pos (point))
9487 (ct (org-context))
9488 (a (assoc :link ct)))
9489 (if a (goto-char (nth 2 a)))
9490 (if (re-search-forward org-any-link-re nil t)
9491 (progn
9492 (goto-char (match-beginning 0))
9493 (if (outline-invisible-p) (org-show-context)))
9494 (goto-char pos)
9495 (setq org-link-search-failed t)
9496 (error "No further link found"))))
9498 (defun org-previous-link ()
9499 "Move backward to the previous link.
9500 If the link is in hidden text, expose it."
9501 (interactive)
9502 (when (and org-link-search-failed (eq this-command last-command))
9503 (goto-char (point-max))
9504 (message "Link search wrapped back to end of buffer"))
9505 (setq org-link-search-failed nil)
9506 (let* ((pos (point))
9507 (ct (org-context))
9508 (a (assoc :link ct)))
9509 (if a (goto-char (nth 1 a)))
9510 (if (re-search-backward org-any-link-re nil t)
9511 (progn
9512 (goto-char (match-beginning 0))
9513 (if (outline-invisible-p) (org-show-context)))
9514 (goto-char pos)
9515 (setq org-link-search-failed t)
9516 (error "No further link found"))))
9518 (defun org-translate-link (s)
9519 "Translate a link string if a translation function has been defined."
9520 (if (and org-link-translation-function
9521 (fboundp org-link-translation-function)
9522 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9523 (progn
9524 (setq s (funcall org-link-translation-function
9525 (match-string 1 s) (match-string 2 s)))
9526 (concat (car s) ":" (cdr s)))
9529 (defun org-translate-link-from-planner (type path)
9530 "Translate a link from Emacs Planner syntax so that Org can follow it.
9531 This is still an experimental function, your mileage may vary."
9532 (cond
9533 ((member type '("http" "https" "news" "ftp"))
9534 ;; standard Internet links are the same.
9535 nil)
9536 ((and (equal type "irc") (string-match "^//" path))
9537 ;; Planner has two / at the beginning of an irc link, we have 1.
9538 ;; We should have zero, actually....
9539 (setq path (substring path 1)))
9540 ((and (equal type "lisp") (string-match "^/" path))
9541 ;; Planner has a slash, we do not.
9542 (setq type "elisp" path (substring path 1)))
9543 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9544 ;; A typical message link. Planner has the id after the final slash,
9545 ;; we separate it with a hash mark
9546 (setq path (concat (match-string 1 path) "#"
9547 (org-remove-angle-brackets (match-string 2 path)))))
9549 (cons type path))
9551 (defun org-find-file-at-mouse (ev)
9552 "Open file link or URL at mouse."
9553 (interactive "e")
9554 (mouse-set-point ev)
9555 (org-open-at-point 'in-emacs))
9557 (defun org-open-at-mouse (ev)
9558 "Open file link or URL at mouse.
9559 See the docstring of `org-open-file' for details."
9560 (interactive "e")
9561 (mouse-set-point ev)
9562 (if (eq major-mode 'org-agenda-mode)
9563 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9564 (org-open-at-point))
9566 (defvar org-window-config-before-follow-link nil
9567 "The window configuration before following a link.
9568 This is saved in case the need arises to restore it.")
9570 (defvar org-open-link-marker (make-marker)
9571 "Marker pointing to the location where `org-open-at-point; was called.")
9573 ;;;###autoload
9574 (defun org-open-at-point-global ()
9575 "Follow a link like Org-mode does.
9576 This command can be called in any mode to follow a link that has
9577 Org-mode syntax."
9578 (interactive)
9579 (org-run-like-in-org-mode 'org-open-at-point))
9581 ;;;###autoload
9582 (defun org-open-link-from-string (s &optional arg reference-buffer)
9583 "Open a link in the string S, as if it was in Org-mode."
9584 (interactive "sLink: \nP")
9585 (let ((reference-buffer (or reference-buffer (current-buffer))))
9586 (with-temp-buffer
9587 (let ((org-inhibit-startup (not reference-buffer)))
9588 (org-mode)
9589 (insert s)
9590 (goto-char (point-min))
9591 (when reference-buffer
9592 (setq org-link-abbrev-alist-local
9593 (with-current-buffer reference-buffer
9594 org-link-abbrev-alist-local)))
9595 (org-open-at-point arg reference-buffer)))))
9597 (defvar org-open-at-point-functions nil
9598 "Hook that is run when following a link at point.
9600 Functions in this hook must return t if they identify and follow
9601 a link at point. If they don't find anything interesting at point,
9602 they must return nil.")
9604 (defun org-open-at-point (&optional arg reference-buffer)
9605 "Open link at or after point.
9606 If there is no link at point, this function will search forward up to
9607 the end of the current line.
9608 Normally, files will be opened by an appropriate application. If the
9609 optional prefix argument ARG is non-nil, Emacs will visit the file.
9610 With a double prefix argument, try to open outside of Emacs, in the
9611 application the system uses for this file type."
9612 (interactive "P")
9613 ;; if in a code block, then open the block's results
9614 (unless (call-interactively #'org-babel-open-src-block-result)
9615 (org-load-modules-maybe)
9616 (move-marker org-open-link-marker (point))
9617 (setq org-window-config-before-follow-link (current-window-configuration))
9618 (org-remove-occur-highlights nil nil t)
9619 (cond
9620 ((and (org-at-heading-p)
9621 (not (org-at-timestamp-p t))
9622 (not (org-in-regexp
9623 (concat org-plain-link-re "\\|"
9624 org-bracket-link-regexp "\\|"
9625 org-angle-link-re "\\|"
9626 "[ \t]:[^ \t\n]+:[ \t]*$")))
9627 (not (get-text-property (point) 'org-linked-text)))
9628 (or (org-offer-links-in-entry arg)
9629 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9630 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9631 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9632 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9633 (not (org-in-regexp org-bracket-link-regexp)))
9634 (org-footnote-action))
9636 (let (type path link line search (pos (point)))
9637 (catch 'match
9638 (save-excursion
9639 (skip-chars-forward "^]\n\r")
9640 (when (org-in-regexp org-bracket-link-regexp 1)
9641 (setq link (org-extract-attributes
9642 (org-link-unescape (org-match-string-no-properties 1))))
9643 (while (string-match " *\n *" link)
9644 (setq link (replace-match " " t t link)))
9645 (setq link (org-link-expand-abbrev link))
9646 (cond
9647 ((or (file-name-absolute-p link)
9648 (string-match "^\\.\\.?/" link))
9649 (setq type "file" path link))
9650 ((string-match org-link-re-with-space3 link)
9651 (setq type (match-string 1 link) path (match-string 2 link)))
9652 (t (setq type "thisfile" path link)))
9653 (throw 'match t)))
9655 (when (get-text-property (point) 'org-linked-text)
9656 (setq type "thisfile"
9657 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9658 (1+ (point)) (point))
9659 path (buffer-substring
9660 (or (previous-single-property-change pos 'org-linked-text)
9661 (point-min))
9662 (or (next-single-property-change pos 'org-linked-text)
9663 (point-max))))
9664 (throw 'match t))
9666 (save-excursion
9667 (when (or (org-in-regexp org-angle-link-re)
9668 (org-in-regexp org-plain-link-re))
9669 (setq type (match-string 1)
9670 path (org-link-unescape (match-string 2)))
9671 (throw 'match t)))
9672 (save-excursion
9673 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9674 (setq type "tags"
9675 path (match-string 1))
9676 (while (string-match ":" path)
9677 (setq path (replace-match "+" t t path)))
9678 (throw 'match t)))
9679 (when (org-in-regexp "<\\([^><\n]+\\)>")
9680 (setq type "tree-match"
9681 path (match-string 1))
9682 (throw 'match t)))
9683 (unless path
9684 (error "No link found"))
9686 ;; switch back to reference buffer
9687 ;; needed when if called in a temporary buffer through
9688 ;; org-open-link-from-string
9689 (with-current-buffer (or reference-buffer (current-buffer))
9691 ;; Remove any trailing spaces in path
9692 (if (string-match " +\\'" path)
9693 (setq path (replace-match "" t t path)))
9694 (if (and org-link-translation-function
9695 (fboundp org-link-translation-function))
9696 ;; Check if we need to translate the link
9697 (let ((tmp (funcall org-link-translation-function type path)))
9698 (setq type (car tmp) path (cdr tmp))))
9700 (cond
9702 ((assoc type org-link-protocols)
9703 (funcall (nth 1 (assoc type org-link-protocols)) path))
9705 ((equal type "mailto")
9706 (let ((cmd (car org-link-mailto-program))
9707 (args (cdr org-link-mailto-program)) args1
9708 (address path) (subject "") a)
9709 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9710 (setq address (match-string 1 path)
9711 subject (org-link-escape (match-string 2 path))))
9712 (while args
9713 (cond
9714 ((not (stringp (car args))) (push (pop args) args1))
9715 (t (setq a (pop args))
9716 (if (string-match "%a" a)
9717 (setq a (replace-match address t t a)))
9718 (if (string-match "%s" a)
9719 (setq a (replace-match subject t t a)))
9720 (push a args1))))
9721 (apply cmd (nreverse args1))))
9723 ((member type '("http" "https" "ftp" "news"))
9724 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9725 (org-link-escape
9726 path org-link-escape-chars-browser)
9727 path))))
9729 ((string= type "doi")
9730 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9731 (org-link-escape
9732 path org-link-escape-chars-browser)
9733 path))))
9735 ((member type '("message"))
9736 (browse-url (concat type ":" path)))
9738 ((string= type "tags")
9739 (org-tags-view arg path))
9741 ((string= type "tree-match")
9742 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9744 ((string= type "file")
9745 (if (string-match "::\\([0-9]+\\)\\'" path)
9746 (setq line (string-to-number (match-string 1 path))
9747 path (substring path 0 (match-beginning 0)))
9748 (if (string-match "::\\(.+\\)\\'" path)
9749 (setq search (match-string 1 path)
9750 path (substring path 0 (match-beginning 0)))))
9751 (if (string-match "[*?{]" (file-name-nondirectory path))
9752 (dired path)
9753 (org-open-file path arg line search)))
9755 ((string= type "shell")
9756 (let ((cmd path))
9757 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9758 (string-match org-confirm-shell-link-not-regexp cmd))
9759 (not org-confirm-shell-link-function)
9760 (funcall org-confirm-shell-link-function
9761 (format "Execute \"%s\" in shell? "
9762 (org-add-props cmd nil
9763 'face 'org-warning))))
9764 (progn
9765 (message "Executing %s" cmd)
9766 (shell-command cmd))
9767 (error "Abort"))))
9769 ((string= type "elisp")
9770 (let ((cmd path))
9771 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9772 (string-match org-confirm-elisp-link-not-regexp cmd))
9773 (not org-confirm-elisp-link-function)
9774 (funcall org-confirm-elisp-link-function
9775 (format "Execute \"%s\" as elisp? "
9776 (org-add-props cmd nil
9777 'face 'org-warning))))
9778 (message "%s => %s" cmd
9779 (if (equal (string-to-char cmd) ?\()
9780 (eval (read cmd))
9781 (call-interactively (read cmd))))
9782 (error "Abort"))))
9784 ((and (string= type "thisfile")
9785 (run-hook-with-args-until-success
9786 'org-open-link-functions path)))
9788 ((string= type "thisfile")
9789 (if arg
9790 (switch-to-buffer-other-window
9791 (org-get-buffer-for-internal-link (current-buffer)))
9792 (org-mark-ring-push))
9793 (let ((cmd `(org-link-search
9794 ,path
9795 ,(cond ((equal arg '(4)) ''occur)
9796 ((equal arg '(16)) ''org-occur)
9797 (t nil))
9798 ,pos)))
9799 (condition-case nil (let ((org-link-search-inhibit-query t))
9800 (eval cmd))
9801 (error (progn (widen) (eval cmd))))))
9804 (browse-url-at-point)))))))
9805 (move-marker org-open-link-marker nil)
9806 (run-hook-with-args 'org-follow-link-hook)))
9808 (defun org-offer-links-in-entry (&optional nth zero)
9809 "Offer links in the current entry and follow the selected link.
9810 If there is only one link, follow it immediately as well.
9811 If NTH is an integer, immediately pick the NTH link found.
9812 If ZERO is a string, check also this string for a link, and if
9813 there is one, offer it as link number zero."
9814 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9815 "\\(" org-angle-link-re "\\)\\|"
9816 "\\(" org-plain-link-re "\\)"))
9817 (cnt ?0)
9818 (in-emacs (if (integerp nth) nil nth))
9819 have-zero end links link c)
9820 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9821 (push (match-string 0 zero) links)
9822 (setq cnt (1- cnt) have-zero t))
9823 (save-excursion
9824 (org-back-to-heading t)
9825 (setq end (save-excursion (outline-next-heading) (point)))
9826 (while (re-search-forward re end t)
9827 (push (match-string 0) links))
9828 (setq links (org-uniquify (reverse links))))
9830 (cond
9831 ((null links)
9832 (message "No links"))
9833 ((equal (length links) 1)
9834 (setq link (list (car links))))
9835 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9836 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9837 (t ; we have to select a link
9838 (save-excursion
9839 (save-window-excursion
9840 (delete-other-windows)
9841 (with-output-to-temp-buffer "*Select Link*"
9842 (mapc (lambda (l)
9843 (if (not (string-match org-bracket-link-regexp l))
9844 (princ (format "[%c] %s\n" (incf cnt)
9845 (org-remove-angle-brackets l)))
9846 (if (match-end 3)
9847 (princ (format "[%c] %s (%s)\n" (incf cnt)
9848 (match-string 3 l) (match-string 1 l)))
9849 (princ (format "[%c] %s\n" (incf cnt)
9850 (match-string 1 l))))))
9851 links))
9852 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9853 (message "Select link to open, RET to open all:")
9854 (setq c (read-char-exclusive))
9855 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9856 (when (equal c ?q) (error "Abort"))
9857 (if (equal c ?\C-m)
9858 (setq link links)
9859 (setq nth (- c ?0))
9860 (if have-zero (setq nth (1+ nth)))
9861 (unless (and (integerp nth) (>= (length links) nth))
9862 (error "Invalid link selection"))
9863 (setq link (list (nth (1- nth) links))))))
9864 (if link
9865 (let ((buf (current-buffer)))
9866 (dolist (l link)
9867 (org-open-link-from-string l in-emacs buf))
9869 nil)))
9871 ;; Add special file links that specify the way of opening
9873 (org-add-link-type "file+sys" 'org-open-file-with-system)
9874 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9875 (defun org-open-file-with-system (path)
9876 "Open file at PATH using the system way of opening it."
9877 (org-open-file path 'system))
9878 (defun org-open-file-with-emacs (path)
9879 "Open file at PATH in Emacs."
9880 (org-open-file path 'emacs))
9881 (defun org-remove-file-link-modifiers ()
9882 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9883 (goto-char (point-min))
9884 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9885 (org-if-unprotected
9886 (replace-match "file:" t t))))
9887 (eval-after-load "org-exp"
9888 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9889 'org-remove-file-link-modifiers))
9891 ;;;; Time estimates
9893 (defun org-get-effort (&optional pom)
9894 "Get the effort estimate for the current entry."
9895 (org-entry-get pom org-effort-property))
9897 ;;; File search
9899 (defvar org-create-file-search-functions nil
9900 "List of functions to construct the right search string for a file link.
9901 These functions are called in turn with point at the location to
9902 which the link should point.
9904 A function in the hook should first test if it would like to
9905 handle this file type, for example by checking the `major-mode'
9906 or the file extension. If it decides not to handle this file, it
9907 should just return nil to give other functions a chance. If it
9908 does handle the file, it must return the search string to be used
9909 when following the link. The search string will be part of the
9910 file link, given after a double colon, and `org-open-at-point'
9911 will automatically search for it. If special measures must be
9912 taken to make the search successful, another function should be
9913 added to the companion hook `org-execute-file-search-functions',
9914 which see.
9916 A function in this hook may also use `setq' to set the variable
9917 `description' to provide a suggestion for the descriptive text to
9918 be used for this link when it gets inserted into an Org-mode
9919 buffer with \\[org-insert-link].")
9921 (defvar org-execute-file-search-functions nil
9922 "List of functions to execute a file search triggered by a link.
9924 Functions added to this hook must accept a single argument, the
9925 search string that was part of the file link, the part after the
9926 double colon. The function must first check if it would like to
9927 handle this search, for example by checking the `major-mode' or
9928 the file extension. If it decides not to handle this search, it
9929 should just return nil to give other functions a chance. If it
9930 does handle the search, it must return a non-nil value to keep
9931 other functions from trying.
9933 Each function can access the current prefix argument through the
9934 variable `current-prefix-argument'. Note that a single prefix is
9935 used to force opening a link in Emacs, so it may be good to only
9936 use a numeric or double prefix to guide the search function.
9938 In case this is needed, a function in this hook can also restore
9939 the window configuration before `org-open-at-point' was called using:
9941 (set-window-configuration org-window-config-before-follow-link)")
9943 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9944 (defun org-link-search (s &optional type avoid-pos stealth)
9945 "Search for a link search option.
9946 If S is surrounded by forward slashes, it is interpreted as a
9947 regular expression. In org-mode files, this will create an `org-occur'
9948 sparse tree. In ordinary files, `occur' will be used to list matches.
9949 If the current buffer is in `dired-mode', grep will be used to search
9950 in all files. If AVOID-POS is given, ignore matches near that position.
9952 When optional argument STEALTH is non-nil, do not modify
9953 visibility around point, thus ignoring
9954 `org-show-hierarchy-above', `org-show-following-heading' and
9955 `org-show-siblings' variables."
9956 (let ((case-fold-search t)
9957 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9958 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9959 (append '(("") (" ") ("\t") ("\n"))
9960 org-emphasis-alist)
9961 "\\|") "\\)"))
9962 (pos (point))
9963 (pre nil) (post nil)
9964 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9965 (cond
9966 ;; First check if there are any special search functions
9967 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9968 ;; Now try the builtin stuff
9969 ((and (equal (string-to-char s0) ?#)
9970 (> (length s0) 1)
9971 (save-excursion
9972 (goto-char (point-min))
9973 (and
9974 (re-search-forward
9975 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9976 (setq type 'dedicated
9977 pos (match-beginning 0))))
9978 ;; There is an exact target for this
9979 (goto-char pos)
9980 (org-back-to-heading t)))
9981 ((save-excursion
9982 (goto-char (point-min))
9983 (and
9984 (re-search-forward
9985 (concat "<<" (regexp-quote s0) ">>") nil t)
9986 (setq type 'dedicated
9987 pos (match-beginning 0))))
9988 ;; There is an exact target for this
9989 (goto-char pos))
9990 ((save-excursion
9991 (goto-char (point-min))
9992 (and
9993 (re-search-forward
9994 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9995 (setq type 'dedicated pos (match-beginning 0))))
9996 ;; Found an invisible target.
9997 (goto-char pos))
9998 ((save-excursion
9999 (goto-char (point-min))
10000 (and
10001 (re-search-forward
10002 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10003 (setq type 'dedicated pos (match-beginning 0))))
10004 ;; Found an element with a matching #+name affiliated keyword.
10005 (goto-char pos))
10006 ((and (string-match "^(\\(.*\\))$" s0)
10007 (save-excursion
10008 (goto-char (point-min))
10009 (and
10010 (re-search-forward
10011 (concat "[^[]" (regexp-quote
10012 (format org-coderef-label-format
10013 (match-string 1 s0))))
10014 nil t)
10015 (setq type 'dedicated
10016 pos (1+ (match-beginning 0))))))
10017 ;; There is a coderef target for this
10018 (goto-char pos))
10019 ((string-match "^/\\(.*\\)/$" s)
10020 ;; A regular expression
10021 (cond
10022 ((derived-mode-p 'org-mode)
10023 (org-occur (match-string 1 s)))
10024 ;;((eq major-mode 'dired-mode)
10025 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10026 (t (org-do-occur (match-string 1 s)))))
10027 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10028 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10029 (goto-char (point-min))
10030 (cond
10031 ((let (case-fold-search)
10032 (re-search-forward (format org-complex-heading-regexp-format
10033 (regexp-quote s))
10034 nil t))
10035 ;; OK, found a match
10036 (setq type 'dedicated)
10037 (goto-char (match-beginning 0)))
10038 ((and (not org-link-search-inhibit-query)
10039 (eq org-link-search-must-match-exact-headline 'query-to-create)
10040 (y-or-n-p "No match - create this as a new heading? "))
10041 (goto-char (point-max))
10042 (or (bolp) (newline))
10043 (insert "* " s "\n")
10044 (beginning-of-line 0))
10046 (goto-char pos)
10047 (error "No match"))))
10049 ;; A normal search string
10050 (when (equal (string-to-char s) ?*)
10051 ;; Anchor on headlines, post may include tags.
10052 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10053 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10054 s (substring s 1)))
10055 (remove-text-properties
10056 0 (length s)
10057 '(face nil mouse-face nil keymap nil fontified nil) s)
10058 ;; Make a series of regular expressions to find a match
10059 (setq words (org-split-string s "[ \n\r\t]+")
10061 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10062 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10063 "\\)" markers)
10064 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10065 re2a (concat "[ \t\r\n]" re2a_)
10066 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10067 re4 (concat "[^a-zA-Z_]" re4_)
10069 re1 (concat pre re2 post)
10070 re3 (concat pre (if pre re4_ re4) post)
10071 re5 (concat pre ".*" re4)
10072 re2 (concat pre re2)
10073 re2a (concat pre (if pre re2a_ re2a))
10074 re4 (concat pre (if pre re4_ re4))
10075 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10076 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10077 re5 "\\)"
10079 (cond
10080 ((eq type 'org-occur) (org-occur reall))
10081 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10082 (t (goto-char (point-min))
10083 (setq type 'fuzzy)
10084 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10085 (org-search-not-self 1 re1 nil t)
10086 (org-search-not-self 1 re2 nil t)
10087 (org-search-not-self 1 re2a nil t)
10088 (org-search-not-self 1 re3 nil t)
10089 (org-search-not-self 1 re4 nil t)
10090 (org-search-not-self 1 re5 nil t)
10092 (goto-char (match-beginning 1))
10093 (goto-char pos)
10094 (error "No match"))))))
10095 (and (derived-mode-p 'org-mode)
10096 (not stealth)
10097 (org-show-context 'link-search))
10098 type))
10100 (defun org-search-not-self (group &rest args)
10101 "Execute `re-search-forward', but only accept matches that do not
10102 enclose the position of `org-open-link-marker'."
10103 (let ((m org-open-link-marker))
10104 (catch 'exit
10105 (while (apply 're-search-forward args)
10106 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10107 (goto-char (match-end group))
10108 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10109 (> (match-beginning 0) (marker-position m))
10110 (< (match-end 0) (marker-position m)))
10111 (save-match-data
10112 (or (not (org-in-regexp
10113 org-bracket-link-analytic-regexp 1))
10114 (not (match-end 4)) ; no description
10115 (and (<= (match-beginning 4) (point))
10116 (>= (match-end 4) (point))))))
10117 (throw 'exit (point))))))))
10119 (defun org-get-buffer-for-internal-link (buffer)
10120 "Return a buffer to be used for displaying the link target of internal links."
10121 (cond
10122 ((not org-display-internal-link-with-indirect-buffer)
10123 buffer)
10124 ((string-match "(Clone)$" (buffer-name buffer))
10125 (message "Buffer is already a clone, not making another one")
10126 ;; we also do not modify visibility in this case
10127 buffer)
10128 (t ; make a new indirect buffer for displaying the link
10129 (let* ((bn (buffer-name buffer))
10130 (ibn (concat bn "(Clone)"))
10131 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10132 (with-current-buffer ib (org-overview))
10133 ib))))
10135 (defun org-do-occur (regexp &optional cleanup)
10136 "Call the Emacs command `occur'.
10137 If CLEANUP is non-nil, remove the printout of the regular expression
10138 in the *Occur* buffer. This is useful if the regex is long and not useful
10139 to read."
10140 (occur regexp)
10141 (when cleanup
10142 (let ((cwin (selected-window)) win beg end)
10143 (when (setq win (get-buffer-window "*Occur*"))
10144 (select-window win))
10145 (goto-char (point-min))
10146 (when (re-search-forward "match[a-z]+" nil t)
10147 (setq beg (match-end 0))
10148 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10149 (setq end (1- (match-beginning 0)))))
10150 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10151 (goto-char (point-min))
10152 (select-window cwin))))
10154 ;;; The mark ring for links jumps
10156 (defvar org-mark-ring nil
10157 "Mark ring for positions before jumps in Org-mode.")
10158 (defvar org-mark-ring-last-goto nil
10159 "Last position in the mark ring used to go back.")
10160 ;; Fill and close the ring
10161 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10162 (loop for i from 1 to org-mark-ring-length do
10163 (push (make-marker) org-mark-ring))
10164 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10165 org-mark-ring)
10167 (defun org-mark-ring-push (&optional pos buffer)
10168 "Put the current position or POS into the mark ring and rotate it."
10169 (interactive)
10170 (setq pos (or pos (point)))
10171 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10172 (move-marker (car org-mark-ring)
10173 (or pos (point))
10174 (or buffer (current-buffer)))
10175 (message "%s"
10176 (substitute-command-keys
10177 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10179 (defun org-mark-ring-goto (&optional n)
10180 "Jump to the previous position in the mark ring.
10181 With prefix arg N, jump back that many stored positions. When
10182 called several times in succession, walk through the entire ring.
10183 Org-mode commands jumping to a different position in the current file,
10184 or to another Org-mode file, automatically push the old position
10185 onto the ring."
10186 (interactive "p")
10187 (let (p m)
10188 (if (eq last-command this-command)
10189 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10190 (setq p org-mark-ring))
10191 (setq org-mark-ring-last-goto p)
10192 (setq m (car p))
10193 (org-pop-to-buffer-same-window (marker-buffer m))
10194 (goto-char m)
10195 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10197 (defun org-remove-angle-brackets (s)
10198 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10199 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10201 (defun org-add-angle-brackets (s)
10202 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10203 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10205 (defun org-remove-double-quotes (s)
10206 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10207 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10210 ;;; Following specific links
10212 (defun org-follow-timestamp-link ()
10213 (cond
10214 ((org-at-date-range-p t)
10215 (let ((org-agenda-start-on-weekday)
10216 (t1 (match-string 1))
10217 (t2 (match-string 2)))
10218 (setq t1 (time-to-days (org-time-string-to-time t1))
10219 t2 (time-to-days (org-time-string-to-time t2)))
10220 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10221 ((org-at-timestamp-p t)
10222 (org-agenda-list nil (time-to-days (org-time-string-to-time
10223 (substring (match-string 1) 0 10)))
10225 (t (error "This should not happen"))))
10228 ;;; Following file links
10229 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10230 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10231 (declare-function mailcap-mime-info
10232 "mailcap" (string &optional request no-decode))
10233 (defvar org-wait nil)
10234 (defun org-open-file (path &optional in-emacs line search)
10235 "Open the file at PATH.
10236 First, this expands any special file name abbreviations. Then the
10237 configuration variable `org-file-apps' is checked if it contains an
10238 entry for this file type, and if yes, the corresponding command is launched.
10240 If no application is found, Emacs simply visits the file.
10242 With optional prefix argument IN-EMACS, Emacs will visit the file.
10243 With a double \\[universal-argument] \\[universal-argument] \
10244 prefix arg, Org tries to avoid opening in Emacs
10245 and to use an external application to visit the file.
10247 Optional LINE specifies a line to go to, optional SEARCH a string
10248 to search for. If LINE or SEARCH is given, the file will be
10249 opened in Emacs, unless an entry from org-file-apps that makes
10250 use of groups in a regexp matches.
10252 If you want to change the way frames are used when following a
10253 link, please customize `org-link-frame-setup'.
10255 If the file does not exist, an error is thrown."
10256 (let* ((file (if (equal path "")
10257 buffer-file-name
10258 (substitute-in-file-name (expand-file-name path))))
10259 (file-apps (append org-file-apps (org-default-apps)))
10260 (apps (org-remove-if
10261 'org-file-apps-entry-match-against-dlink-p file-apps))
10262 (apps-dlink (org-remove-if-not
10263 'org-file-apps-entry-match-against-dlink-p file-apps))
10264 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10265 (dirp (if remp nil (file-directory-p file)))
10266 (file (if (and dirp org-open-directory-means-index-dot-org)
10267 (concat (file-name-as-directory file) "index.org")
10268 file))
10269 (a-m-a-p (assq 'auto-mode apps))
10270 (dfile (downcase file))
10271 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10272 (link (cond ((and (eq line nil)
10273 (eq search nil))
10274 file)
10275 (line
10276 (concat file "::" (number-to-string line)))
10277 (search
10278 (concat file "::" search))))
10279 (dlink (downcase link))
10280 (old-buffer (current-buffer))
10281 (old-pos (point))
10282 (old-mode major-mode)
10283 ext cmd link-match-data)
10284 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10285 (setq ext (match-string 1 dfile))
10286 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10287 (setq ext (match-string 1 dfile))))
10288 (cond
10289 ((member in-emacs '((16) system))
10290 (setq cmd (cdr (assoc 'system apps))))
10291 (in-emacs (setq cmd 'emacs))
10293 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10294 (and dirp (cdr (assoc 'directory apps)))
10295 ; first, try matching against apps-dlink
10296 ; if we get a match here, store the match data for later
10297 (let ((match (assoc-default dlink apps-dlink
10298 'string-match)))
10299 (if match
10300 (progn (setq link-match-data (match-data))
10301 match)
10302 (progn (setq in-emacs (or in-emacs line search))
10303 nil))) ; if we have no match in apps-dlink,
10304 ; always open the file in emacs if line or search
10305 ; is given (for backwards compatibility)
10306 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10307 'string-match)
10308 (cdr (assoc ext apps))
10309 (cdr (assoc t apps))))))
10310 (when (eq cmd 'system)
10311 (setq cmd (cdr (assoc 'system apps))))
10312 (when (eq cmd 'default)
10313 (setq cmd (cdr (assoc t apps))))
10314 (when (eq cmd 'mailcap)
10315 (require 'mailcap)
10316 (mailcap-parse-mailcaps)
10317 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10318 (command (mailcap-mime-info mime-type)))
10319 (if (stringp command)
10320 (setq cmd command)
10321 (setq cmd 'emacs))))
10322 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10323 (not (file-exists-p file))
10324 (not org-open-non-existing-files))
10325 (error "No such file: %s" file))
10326 (cond
10327 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10328 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10329 (while (string-match "['\"]%s['\"]" cmd)
10330 (setq cmd (replace-match "%s" t t cmd)))
10331 (while (string-match "%s" cmd)
10332 (setq cmd (replace-match
10333 (save-match-data
10334 (shell-quote-argument
10335 (convert-standard-filename file)))
10336 t t cmd)))
10338 ;; Replace "%1", "%2" etc. in command with group matches from regex
10339 (save-match-data
10340 (let ((match-index 1)
10341 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10342 (set-match-data link-match-data)
10343 (while (<= match-index number-of-groups)
10344 (let ((regex (concat "%" (number-to-string match-index)))
10345 (replace-with (match-string match-index dlink)))
10346 (while (string-match regex cmd)
10347 (setq cmd (replace-match replace-with t t cmd))))
10348 (setq match-index (+ match-index 1)))))
10350 (save-window-excursion
10351 (start-process-shell-command cmd nil cmd)
10352 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10354 ((or (stringp cmd)
10355 (eq cmd 'emacs))
10356 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10357 (widen)
10358 (if line (org-goto-line line)
10359 (if search (org-link-search search))))
10360 ((consp cmd)
10361 (let ((file (convert-standard-filename file)))
10362 (save-match-data
10363 (set-match-data link-match-data)
10364 (eval cmd))))
10365 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10366 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10367 (or (not (equal old-buffer (current-buffer)))
10368 (not (equal old-pos (point))))
10369 (org-mark-ring-push old-pos old-buffer))))
10371 (defun org-file-apps-entry-match-against-dlink-p (entry)
10372 "This function returns non-nil if `entry' uses a regular
10373 expression which should be matched against the whole link by
10374 org-open-file.
10376 It assumes that is the case when the entry uses a regular
10377 expression which has at least one grouping construct and the
10378 action is either a lisp form or a command string containing
10379 '%1', i.e. using at least one subexpression match as a
10380 parameter."
10381 (let ((selector (car entry))
10382 (action (cdr entry)))
10383 (if (stringp selector)
10384 (and (> (regexp-opt-depth selector) 0)
10385 (or (and (stringp action)
10386 (string-match "%[0-9]" action))
10387 (consp action)))
10388 nil)))
10390 (defun org-default-apps ()
10391 "Return the default applications for this operating system."
10392 (cond
10393 ((eq system-type 'darwin)
10394 org-file-apps-defaults-macosx)
10395 ((eq system-type 'windows-nt)
10396 org-file-apps-defaults-windowsnt)
10397 (t org-file-apps-defaults-gnu)))
10399 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10400 "Convert extensions to regular expressions in the cars of LIST.
10401 Also, weed out any non-string entries, because the return value is used
10402 only for regexp matching.
10403 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10404 point to the symbol `emacs', indicating that the file should
10405 be opened in Emacs."
10406 (append
10407 (delq nil
10408 (mapcar (lambda (x)
10409 (if (not (stringp (car x)))
10411 (if (string-match "\\W" (car x))
10413 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10414 list))
10415 (if add-auto-mode
10416 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10418 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10419 (defun org-file-remote-p (file)
10420 "Test whether FILE specifies a location on a remote system.
10421 Return non-nil if the location is indeed remote.
10423 For example, the filename \"/user@host:/foo\" specifies a location
10424 on the system \"/user@host:\"."
10425 (cond ((fboundp 'file-remote-p)
10426 (file-remote-p file))
10427 ((fboundp 'tramp-handle-file-remote-p)
10428 (tramp-handle-file-remote-p file))
10429 ((and (boundp 'ange-ftp-name-format)
10430 (string-match (car ange-ftp-name-format) file))
10432 (t nil)))
10435 ;;;; Refiling
10437 (defun org-get-org-file ()
10438 "Read a filename, with default directory `org-directory'."
10439 (let ((default (or org-default-notes-file remember-data-file)))
10440 (read-file-name (format "File name [%s]: " default)
10441 (file-name-as-directory org-directory)
10442 default)))
10444 (defun org-notes-order-reversed-p ()
10445 "Check if the current file should receive notes in reversed order."
10446 (cond
10447 ((not org-reverse-note-order) nil)
10448 ((eq t org-reverse-note-order) t)
10449 ((not (listp org-reverse-note-order)) nil)
10450 (t (catch 'exit
10451 (let ((all org-reverse-note-order)
10452 entry)
10453 (while (setq entry (pop all))
10454 (if (string-match (car entry) buffer-file-name)
10455 (throw 'exit (cdr entry))))
10456 nil)))))
10458 (defvar org-refile-target-table nil
10459 "The list of refile targets, created by `org-refile'.")
10461 (defvar org-agenda-new-buffers nil
10462 "Buffers created to visit agenda files.")
10464 (defvar org-refile-cache nil
10465 "Cache for refile targets.")
10467 (defvar org-refile-markers nil
10468 "All the markers used for caching refile locations.")
10470 (defun org-refile-marker (pos)
10471 "Get a new refile marker, but only if caching is in use."
10472 (if (not org-refile-use-cache)
10474 (let ((m (make-marker)))
10475 (move-marker m pos)
10476 (push m org-refile-markers)
10477 m)))
10479 (defun org-refile-cache-clear ()
10480 "Clear the refile cache and disable all the markers."
10481 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10482 (setq org-refile-markers nil)
10483 (setq org-refile-cache nil)
10484 (message "Refile cache has been cleared"))
10486 (defun org-refile-cache-check-set (set)
10487 "Check if all the markers in the cache still have live buffers."
10488 (let (marker)
10489 (catch 'exit
10490 (while (and set (setq marker (nth 3 (pop set))))
10491 ;; if org-refile-use-outline-path is 'file, marker may be nil
10492 (when (and marker (null (marker-buffer marker)))
10493 (message "not found") (sit-for 3)
10494 (throw 'exit nil)))
10495 t)))
10497 (defun org-refile-cache-put (set &rest identifiers)
10498 "Push the refile targets SET into the cache, under IDENTIFIERS."
10499 (let* ((key (sha1 (prin1-to-string identifiers)))
10500 (entry (assoc key org-refile-cache)))
10501 (if entry
10502 (setcdr entry set)
10503 (push (cons key set) org-refile-cache))))
10505 (defun org-refile-cache-get (&rest identifiers)
10506 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10507 (cond
10508 ((not org-refile-cache) nil)
10509 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10511 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10512 org-refile-cache))))
10513 (and set (org-refile-cache-check-set set) set)))))
10515 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10516 "Produce a table with refile targets."
10517 (let ((case-fold-search nil)
10518 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10519 (entries (or org-refile-targets '((nil . (:level . 1)))))
10520 targets tgs txt re files f desc descre fast-path-p level pos0)
10521 (message "Getting targets...")
10522 (with-current-buffer (or default-buffer (current-buffer))
10523 (while (setq entry (pop entries))
10524 (setq files (car entry) desc (cdr entry))
10525 (setq fast-path-p nil)
10526 (cond
10527 ((null files) (setq files (list (current-buffer))))
10528 ((eq files 'org-agenda-files)
10529 (setq files (org-agenda-files 'unrestricted)))
10530 ((and (symbolp files) (fboundp files))
10531 (setq files (funcall files)))
10532 ((and (symbolp files) (boundp files))
10533 (setq files (symbol-value files))))
10534 (if (stringp files) (setq files (list files)))
10535 (cond
10536 ((eq (car desc) :tag)
10537 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10538 ((eq (car desc) :todo)
10539 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10540 ((eq (car desc) :regexp)
10541 (setq descre (cdr desc)))
10542 ((eq (car desc) :level)
10543 (setq descre (concat "^\\*\\{" (number-to-string
10544 (if org-odd-levels-only
10545 (1- (* 2 (cdr desc)))
10546 (cdr desc)))
10547 "\\}[ \t]")))
10548 ((eq (car desc) :maxlevel)
10549 (setq fast-path-p t)
10550 (setq descre (concat "^\\*\\{1," (number-to-string
10551 (if org-odd-levels-only
10552 (1- (* 2 (cdr desc)))
10553 (cdr desc)))
10554 "\\}[ \t]")))
10555 (t (error "Bad refiling target description %s" desc)))
10556 (while (setq f (pop files))
10557 (with-current-buffer
10558 (if (bufferp f) f (org-get-agenda-file-buffer f))
10560 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10561 (progn
10562 (if (bufferp f) (setq f (buffer-file-name
10563 (buffer-base-buffer f))))
10564 (setq f (and f (expand-file-name f)))
10565 (if (eq org-refile-use-outline-path 'file)
10566 (push (list (file-name-nondirectory f) f nil nil) tgs))
10567 (save-excursion
10568 (save-restriction
10569 (widen)
10570 (goto-char (point-min))
10571 (while (re-search-forward descre nil t)
10572 (goto-char (setq pos0 (point-at-bol)))
10573 (catch 'next
10574 (when org-refile-target-verify-function
10575 (save-match-data
10576 (or (funcall org-refile-target-verify-function)
10577 (throw 'next t))))
10578 (when (and (looking-at org-complex-heading-regexp)
10579 (not (member (match-string 4) excluded-entries))
10580 (match-string 4))
10581 (setq level (org-reduced-level
10582 (- (match-end 1) (match-beginning 1)))
10583 txt (org-link-display-format (match-string 4))
10584 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10585 re (format org-complex-heading-regexp-format
10586 (regexp-quote (match-string 4))))
10587 (when org-refile-use-outline-path
10588 (setq txt (mapconcat
10589 'org-protect-slash
10590 (append
10591 (if (eq org-refile-use-outline-path
10592 'file)
10593 (list (file-name-nondirectory
10594 (buffer-file-name
10595 (buffer-base-buffer))))
10596 (if (eq org-refile-use-outline-path
10597 'full-file-path)
10598 (list (buffer-file-name
10599 (buffer-base-buffer)))))
10600 (org-get-outline-path fast-path-p
10601 level txt)
10602 (list txt))
10603 "/")))
10604 (push (list txt f re (org-refile-marker (point)))
10605 tgs)))
10606 (when (= (point) pos0)
10607 ;; verification function has not moved point
10608 (goto-char (point-at-eol))))))))
10609 (when org-refile-use-cache
10610 (org-refile-cache-put tgs (buffer-file-name) descre))
10611 (setq targets (append tgs targets))
10612 ))))
10613 (message "Getting targets...done")
10614 (nreverse targets)))
10616 (defun org-protect-slash (s)
10617 (while (string-match "/" s)
10618 (setq s (replace-match "\\" t t s)))
10621 (defvar org-olpa (make-vector 20 nil))
10623 (defun org-get-outline-path (&optional fastp level heading)
10624 "Return the outline path to the current entry, as a list.
10626 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10627 routine which makes outline path derivations for an entire file,
10628 avoiding backtracing. Refile target collection makes use of that."
10629 (if fastp
10630 (progn
10631 (if (> level 19)
10632 (error "Outline path failure, more than 19 levels"))
10633 (loop for i from level upto 19 do
10634 (aset org-olpa i nil))
10635 (prog1
10636 (delq nil (append org-olpa nil))
10637 (aset org-olpa level heading)))
10638 (let (rtn case-fold-search)
10639 (save-excursion
10640 (save-restriction
10641 (widen)
10642 (while (org-up-heading-safe)
10643 (when (looking-at org-complex-heading-regexp)
10644 (push (org-match-string-no-properties 4) rtn)))
10645 rtn)))))
10647 (defun org-format-outline-path (path &optional width prefix)
10648 "Format the outline path PATH for display.
10649 Width is the maximum number of characters that is available.
10650 Prefix is a prefix to be included in the returned string,
10651 such as the file name."
10652 (setq width (or width 79))
10653 (if prefix (setq width (- width (length prefix))))
10654 (if (not path)
10655 (or prefix "")
10656 (let* ((nsteps (length path))
10657 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10658 (maxwidth (if (<= total-width width)
10659 10000 ;; everything fits
10660 ;; we need to shorten the level headings
10661 (/ (- width nsteps) nsteps)))
10662 (org-odd-levels-only nil)
10663 (n 0)
10664 (total (1+ (length prefix))))
10665 (setq maxwidth (max maxwidth 10))
10666 (concat prefix
10667 (mapconcat
10668 (lambda (h)
10669 (setq n (1+ n))
10670 (if (and (= n nsteps) (< maxwidth 10000))
10671 (setq maxwidth (- total-width total)))
10672 (if (< (length h) maxwidth)
10673 (progn (setq total (+ total (length h) 1)) h)
10674 (setq h (substring h 0 (- maxwidth 2))
10675 total (+ total maxwidth 1))
10676 (if (string-match "[ \t]+\\'" h)
10677 (setq h (substring h 0 (match-beginning 0))))
10678 (setq h (concat h "..")))
10679 (org-add-props h nil 'face
10680 (nth (% (1- n) org-n-level-faces)
10681 org-level-faces))
10683 path "/")))))
10685 (defun org-display-outline-path (&optional file current)
10686 "Display the current outline path in the echo area."
10687 (interactive "P")
10688 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10689 (case-fold-search nil)
10690 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10691 (if current (setq path (append path
10692 (save-excursion
10693 (org-back-to-heading t)
10694 (if (looking-at org-complex-heading-regexp)
10695 (list (match-string 4)))))))
10696 (message "%s"
10697 (org-format-outline-path
10698 path
10699 (1- (frame-width))
10700 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10702 (defvar org-refile-history nil
10703 "History for refiling operations.")
10705 (defvar org-after-refile-insert-hook nil
10706 "Hook run after `org-refile' has inserted its stuff at the new location.
10707 Note that this is still *before* the stuff will be removed from
10708 the *old* location.")
10710 (defvar org-capture-last-stored-marker)
10711 (defun org-refile (&optional goto default-buffer rfloc)
10712 "Move the entry or entries at point to another heading.
10713 The list of target headings is compiled using the information in
10714 `org-refile-targets', which see.
10716 At the target location, the entry is filed as a subitem of the target
10717 heading. Depending on `org-reverse-note-order', the new subitem will
10718 either be the first or the last subitem.
10720 If there is an active region, all entries in that region will be moved.
10721 However, the region must fulfill the requirement that the first heading
10722 is the first one sets the top-level of the moved text - at most siblings
10723 below it are allowed.
10725 With prefix arg GOTO, the command will only visit the target location
10726 and not actually move anything.
10728 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10729 go to the location where the last refiling operation has put the subtree.
10730 With a prefix argument of `2', refile to the running clock.
10732 RFLOC can be a refile location obtained in a different way.
10734 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10736 If you are using target caching (see `org-refile-use-cache'),
10737 you have to clear the target cache in order to find new targets.
10738 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10739 prefix argument (`C-u C-u C-u C-c C-w')."
10741 (interactive "P")
10742 (if (member goto '(0 (64)))
10743 (org-refile-cache-clear)
10744 (let* ((cbuf (current-buffer))
10745 (regionp (org-region-active-p))
10746 (region-start (and regionp (region-beginning)))
10747 (region-end (and regionp (region-end)))
10748 (region-length (and regionp (- region-end region-start)))
10749 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10750 pos it nbuf file re level reversed)
10751 (setq last-command nil)
10752 (when regionp
10753 (goto-char region-start)
10754 (or (bolp) (goto-char (point-at-bol)))
10755 (setq region-start (point))
10756 (unless (or (org-kill-is-subtree-p
10757 (buffer-substring region-start region-end))
10758 (prog1 org-refile-active-region-within-subtree
10759 (org-toggle-heading)))
10760 (error "The region is not a (sequence of) subtree(s)")))
10761 (if (equal goto '(16))
10762 (org-refile-goto-last-stored)
10763 (when (or
10764 (and (equal goto 2)
10765 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10766 (prog1
10767 (setq it (list (or org-clock-heading "running clock")
10768 (buffer-file-name
10769 (marker-buffer org-clock-hd-marker))
10771 (marker-position org-clock-hd-marker)))
10772 (setq goto nil)))
10773 (setq it (or rfloc
10774 (let (heading-text)
10775 (save-excursion
10776 (unless goto
10777 (org-back-to-heading t)
10778 (setq heading-text
10779 (nth 4 (org-heading-components))))
10780 (org-refile-get-location
10781 (cond (goto "Goto")
10782 (regionp "Refile region to")
10783 (t (concat "Refile subtree \""
10784 heading-text "\" to")))
10785 default-buffer
10786 (and (not (equal '(4) goto))
10787 org-refile-allow-creating-parent-nodes)
10788 goto))))))
10789 (setq file (nth 1 it)
10790 re (nth 2 it)
10791 pos (nth 3 it))
10792 (if (and (not goto)
10794 (equal (buffer-file-name) file)
10795 (if regionp
10796 (and (>= pos region-start)
10797 (<= pos region-end))
10798 (and (>= pos (point))
10799 (< pos (save-excursion
10800 (org-end-of-subtree t t))))))
10801 (error "Cannot refile to position inside the tree or region"))
10803 (setq nbuf (or (find-buffer-visiting file)
10804 (find-file-noselect file)))
10805 (if goto
10806 (progn
10807 (org-pop-to-buffer-same-window nbuf)
10808 (goto-char pos)
10809 (org-show-context 'org-goto))
10810 (if regionp
10811 (progn
10812 (org-kill-new (buffer-substring region-start region-end))
10813 (org-save-markers-in-region region-start region-end))
10814 (org-copy-subtree 1 nil t))
10815 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10816 (find-file-noselect file)))
10817 (setq reversed (org-notes-order-reversed-p))
10818 (save-excursion
10819 (save-restriction
10820 (widen)
10821 (if pos
10822 (progn
10823 (goto-char pos)
10824 (looking-at org-outline-regexp)
10825 (setq level (org-get-valid-level (funcall outline-level) 1))
10826 (goto-char
10827 (if reversed
10828 (or (outline-next-heading) (point-max))
10829 (or (save-excursion (org-get-next-sibling))
10830 (org-end-of-subtree t t)
10831 (point-max)))))
10832 (setq level 1)
10833 (if (not reversed)
10834 (goto-char (point-max))
10835 (goto-char (point-min))
10836 (or (outline-next-heading) (goto-char (point-max)))))
10837 (if (not (bolp)) (newline))
10838 (org-paste-subtree level)
10839 (when org-log-refile
10840 (org-add-log-setup 'refile nil nil 'findpos
10841 org-log-refile)
10842 (unless (eq org-log-refile 'note)
10843 (save-excursion (org-add-log-note))))
10844 (and org-auto-align-tags
10845 (let ((org-loop-over-headlines-in-active-region nil))
10846 (org-set-tags nil t)))
10847 (bookmark-set "org-refile-last-stored")
10848 ;; If we are refiling for capture, make sure that the
10849 ;; last-capture pointers point here
10850 (when (org-bound-and-true-p org-refile-for-capture)
10851 (bookmark-set "org-capture-last-stored-marker")
10852 (move-marker org-capture-last-stored-marker (point)))
10853 (if (fboundp 'deactivate-mark) (deactivate-mark))
10854 (run-hooks 'org-after-refile-insert-hook))))
10855 (if regionp
10856 (delete-region (point) (+ (point) region-length))
10857 (org-cut-subtree))
10858 (when (featurep 'org-inlinetask)
10859 (org-inlinetask-remove-END-maybe))
10860 (setq org-markers-to-move nil)
10861 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10863 (defun org-refile-goto-last-stored ()
10864 "Go to the location where the last refile was stored."
10865 (interactive)
10866 (bookmark-jump "org-refile-last-stored")
10867 (message "This is the location of the last refile"))
10869 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10870 no-exclude)
10871 "Prompt the user for a refile location, using PROMPT.
10872 PROMPT should not be suffixed with a colon and a space, because
10873 this function appends the default value from
10874 `org-refile-history' automatically, if that is not empty.
10875 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10876 this is used for the GOTO interface."
10877 (let ((org-refile-targets org-refile-targets)
10878 (org-refile-use-outline-path org-refile-use-outline-path)
10879 excluded-entries)
10880 (when (and (derived-mode-p 'org-mode)
10881 (not org-refile-use-cache)
10882 (not no-exclude))
10883 (org-map-tree
10884 (lambda()
10885 (setq excluded-entries
10886 (append excluded-entries (list (org-get-heading t t)))))))
10887 (setq org-refile-target-table
10888 (org-refile-get-targets default-buffer excluded-entries)))
10889 (unless org-refile-target-table
10890 (error "No refile targets"))
10891 (let* ((prompt (concat prompt
10892 (and (car org-refile-history)
10893 (concat " (default " (car org-refile-history) ")"))
10894 ": "))
10895 (cbuf (current-buffer))
10896 (partial-completion-mode nil)
10897 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10898 (cfunc (if (and org-refile-use-outline-path
10899 org-outline-path-complete-in-steps)
10900 'org-olpath-completing-read
10901 'org-icompleting-read))
10902 (extra (if org-refile-use-outline-path "/" ""))
10903 (filename (and cfn (expand-file-name cfn)))
10904 (tbl (mapcar
10905 (lambda (x)
10906 (if (and (not (member org-refile-use-outline-path
10907 '(file full-file-path)))
10908 (not (equal filename (nth 1 x))))
10909 (cons (concat (car x) extra " ("
10910 (file-name-nondirectory (nth 1 x)) ")")
10911 (cdr x))
10912 (cons (concat (car x) extra) (cdr x))))
10913 org-refile-target-table))
10914 (completion-ignore-case t)
10915 pa answ parent-target child parent old-hist)
10916 (setq old-hist org-refile-history)
10917 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10918 nil 'org-refile-history (car org-refile-history)))
10919 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10920 (org-refile-check-position pa)
10921 (if pa
10922 (progn
10923 (when (or (not org-refile-history)
10924 (not (eq old-hist org-refile-history))
10925 (not (equal (car pa) (car org-refile-history))))
10926 (setq org-refile-history
10927 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10928 org-refile-history
10929 (cdr org-refile-history))))
10930 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10931 (pop org-refile-history)))
10933 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10934 (progn
10935 (setq parent (match-string 1 answ)
10936 child (match-string 2 answ))
10937 (setq parent-target (or (assoc parent tbl)
10938 (assoc (concat parent "/") tbl)))
10939 (when (and parent-target
10940 (or (eq new-nodes t)
10941 (and (eq new-nodes 'confirm)
10942 (y-or-n-p (format "Create new node \"%s\"? "
10943 child)))))
10944 (org-refile-new-child parent-target child)))
10945 (error "Invalid target location")))))
10947 (declare-function org-string-nw-p "org-macs.el" (s))
10948 (defun org-refile-check-position (refile-pointer)
10949 "Check if the refile pointer matches the readline to which it points."
10950 (let* ((file (nth 1 refile-pointer))
10951 (re (nth 2 refile-pointer))
10952 (pos (nth 3 refile-pointer))
10953 buffer)
10954 (when (org-string-nw-p re)
10955 (setq buffer (if (markerp pos)
10956 (marker-buffer pos)
10957 (or (find-buffer-visiting file)
10958 (find-file-noselect file))))
10959 (with-current-buffer buffer
10960 (save-excursion
10961 (save-restriction
10962 (widen)
10963 (goto-char pos)
10964 (beginning-of-line 1)
10965 (unless (org-looking-at-p re)
10966 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10968 (defun org-refile-new-child (parent-target child)
10969 "Use refile target PARENT-TARGET to add new CHILD below it."
10970 (unless parent-target
10971 (error "Cannot find parent for new node"))
10972 (let ((file (nth 1 parent-target))
10973 (pos (nth 3 parent-target))
10974 level)
10975 (with-current-buffer (or (find-buffer-visiting file)
10976 (find-file-noselect file))
10977 (save-excursion
10978 (save-restriction
10979 (widen)
10980 (if pos
10981 (goto-char pos)
10982 (goto-char (point-max))
10983 (if (not (bolp)) (newline)))
10984 (when (looking-at org-outline-regexp)
10985 (setq level (funcall outline-level))
10986 (org-end-of-subtree t t))
10987 (org-back-over-empty-lines)
10988 (insert "\n" (make-string
10989 (if pos (org-get-valid-level level 1) 1) ?*)
10990 " " child "\n")
10991 (beginning-of-line 0)
10992 (list (concat (car parent-target) "/" child) file "" (point)))))))
10994 (defun org-olpath-completing-read (prompt collection &rest args)
10995 "Read an outline path like a file name."
10996 (let ((thetable collection)
10997 (org-completion-use-ido nil) ; does not work with ido.
10998 (org-completion-use-iswitchb nil)) ; or iswitchb
10999 (apply
11000 'org-icompleting-read prompt
11001 (lambda (string predicate &optional flag)
11002 (let (rtn r f (l (length string)))
11003 (cond
11004 ((eq flag nil)
11005 ;; try completion
11006 (try-completion string thetable))
11007 ((eq flag t)
11008 ;; all-completions
11009 (setq rtn (all-completions string thetable predicate))
11010 (mapcar
11011 (lambda (x)
11012 (setq r (substring x l))
11013 (if (string-match " ([^)]*)$" x)
11014 (setq f (match-string 0 x))
11015 (setq f ""))
11016 (if (string-match "/" r)
11017 (concat string (substring r 0 (match-end 0)) f)
11019 rtn))
11020 ((eq flag 'lambda)
11021 ;; exact match?
11022 (assoc string thetable)))))
11023 args)))
11025 ;;;; Dynamic blocks
11027 (defun org-find-dblock (name)
11028 "Find the first dynamic block with name NAME in the buffer.
11029 If not found, stay at current position and return nil."
11030 (let (pos)
11031 (save-excursion
11032 (goto-char (point-min))
11033 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11034 nil t)
11035 (match-beginning 0))))
11036 (if pos (goto-char pos))
11037 pos))
11039 (defconst org-dblock-start-re
11040 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11041 "Matches the start line of a dynamic block, with parameters.")
11043 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11044 "Matches the end of a dynamic block.")
11046 (defun org-create-dblock (plist)
11047 "Create a dynamic block section, with parameters taken from PLIST.
11048 PLIST must contain a :name entry which is used as name of the block."
11049 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11050 (end-of-line 1)
11051 (newline))
11052 (let ((col (current-column))
11053 (name (plist-get plist :name)))
11054 (insert "#+BEGIN: " name)
11055 (while plist
11056 (if (eq (car plist) :name)
11057 (setq plist (cddr plist))
11058 (insert " " (prin1-to-string (pop plist)))))
11059 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11060 (beginning-of-line -2)))
11062 (defun org-prepare-dblock ()
11063 "Prepare dynamic block for refresh.
11064 This empties the block, puts the cursor at the insert position and returns
11065 the property list including an extra property :name with the block name."
11066 (unless (looking-at org-dblock-start-re)
11067 (error "Not at a dynamic block"))
11068 (let* ((begdel (1+ (match-end 0)))
11069 (name (org-no-properties (match-string 1)))
11070 (params (append (list :name name)
11071 (read (concat "(" (match-string 3) ")")))))
11072 (save-excursion
11073 (beginning-of-line 1)
11074 (skip-chars-forward " \t")
11075 (setq params (plist-put params :indentation-column (current-column))))
11076 (unless (re-search-forward org-dblock-end-re nil t)
11077 (error "Dynamic block not terminated"))
11078 (setq params
11079 (append params
11080 (list :content (buffer-substring
11081 begdel (match-beginning 0)))))
11082 (delete-region begdel (match-beginning 0))
11083 (goto-char begdel)
11084 (open-line 1)
11085 params))
11087 (defun org-map-dblocks (&optional command)
11088 "Apply COMMAND to all dynamic blocks in the current buffer.
11089 If COMMAND is not given, use `org-update-dblock'."
11090 (let ((cmd (or command 'org-update-dblock)))
11091 (save-excursion
11092 (goto-char (point-min))
11093 (while (re-search-forward org-dblock-start-re nil t)
11094 (goto-char (match-beginning 0))
11095 (save-excursion
11096 (condition-case nil
11097 (funcall cmd)
11098 (error (message "Error during update of dynamic block"))))
11099 (unless (re-search-forward org-dblock-end-re nil t)
11100 (error "Dynamic block not terminated"))))))
11102 (defun org-dblock-update (&optional arg)
11103 "User command for updating dynamic blocks.
11104 Update the dynamic block at point. With prefix ARG, update all dynamic
11105 blocks in the buffer."
11106 (interactive "P")
11107 (if arg
11108 (org-update-all-dblocks)
11109 (or (looking-at org-dblock-start-re)
11110 (org-beginning-of-dblock))
11111 (org-update-dblock)))
11113 (defun org-update-dblock ()
11114 "Update the dynamic block at point.
11115 This means to empty the block, parse for parameters and then call
11116 the correct writing function."
11117 (interactive)
11118 (save-window-excursion
11119 (let* ((pos (point))
11120 (line (org-current-line))
11121 (params (org-prepare-dblock))
11122 (name (plist-get params :name))
11123 (indent (plist-get params :indentation-column))
11124 (cmd (intern (concat "org-dblock-write:" name))))
11125 (message "Updating dynamic block `%s' at line %d..." name line)
11126 (funcall cmd params)
11127 (message "Updating dynamic block `%s' at line %d...done" name line)
11128 (goto-char pos)
11129 (when (and indent (> indent 0))
11130 (setq indent (make-string indent ?\ ))
11131 (save-excursion
11132 (org-beginning-of-dblock)
11133 (forward-line 1)
11134 (while (not (looking-at org-dblock-end-re))
11135 (insert indent)
11136 (beginning-of-line 2))
11137 (when (looking-at org-dblock-end-re)
11138 (and (looking-at "[ \t]+")
11139 (replace-match ""))
11140 (insert indent)))))))
11142 (defun org-beginning-of-dblock ()
11143 "Find the beginning of the dynamic block at point.
11144 Error if there is no such block at point."
11145 (let ((pos (point))
11146 beg)
11147 (end-of-line 1)
11148 (if (and (re-search-backward org-dblock-start-re nil t)
11149 (setq beg (match-beginning 0))
11150 (re-search-forward org-dblock-end-re nil t)
11151 (> (match-end 0) pos))
11152 (goto-char beg)
11153 (goto-char pos)
11154 (error "Not in a dynamic block"))))
11156 ;;;###autoload
11157 (defun org-update-all-dblocks ()
11158 "Update all dynamic blocks in the buffer.
11159 This function can be used in a hook."
11160 (interactive)
11161 (when (derived-mode-p 'org-mode)
11162 (org-map-dblocks 'org-update-dblock)))
11165 ;;;; Completion
11167 (defconst org-additional-option-like-keywords
11168 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11169 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11170 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11171 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11172 "BEGIN:" "END:"
11173 "ORGTBL" "TBLFM:" "TBLNAME:"
11174 "BEGIN_EXAMPLE" "END_EXAMPLE"
11175 "BEGIN_QUOTE" "END_QUOTE"
11176 "BEGIN_VERSE" "END_VERSE"
11177 "BEGIN_CENTER" "END_CENTER"
11178 "BEGIN_SRC" "END_SRC"
11179 "BEGIN_RESULT" "END_RESULT"
11180 "NAME:" "RESULTS:"
11181 "HEADER:" "HEADERS:"
11182 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11183 "CAPTION:" "LABEL:"
11184 "SETUPFILE:"
11185 "INCLUDE:"
11186 "BIND:"
11187 "MACRO:"))
11189 (defcustom org-structure-template-alist
11191 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11192 "<src lang=\"?\">\n\n</src>")
11193 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11194 "<example>\n?\n</example>")
11195 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11196 "<quote>\n?\n</quote>")
11197 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11198 "<verse>\n?\n</verse>")
11199 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11200 "<center>\n?\n</center>")
11201 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11202 "<literal style=\"latex\">\n?\n</literal>")
11203 ("L" "#+LaTeX: "
11204 "<literal style=\"latex\">?</literal>")
11205 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11206 "<literal style=\"html\">\n?\n</literal>")
11207 ("H" "#+HTML: "
11208 "<literal style=\"html\">?</literal>")
11209 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11210 ("A" "#+ASCII: ")
11211 ("i" "#+INDEX: ?"
11212 "#+INDEX: ?")
11213 ("I" "#+INCLUDE %file ?"
11214 "<include file=%file markup=\"?\">")
11216 "Structure completion elements.
11217 This is a list of abbreviation keys and values. The value gets inserted
11218 if you type `<' followed by the key and then press the completion key,
11219 usually `M-TAB'. %file will be replaced by a file name after prompting
11220 for the file using completion. The cursor will be placed at the position
11221 of the `?` in the template.
11222 There are two templates for each key, the first uses the original Org syntax,
11223 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11224 the default when the /org-mtags.el/ module has been loaded. See also the
11225 variable `org-mtags-prefer-muse-templates'."
11226 :group 'org-completion
11227 :type '(repeat
11228 (string :tag "Key")
11229 (string :tag "Template")
11230 (string :tag "Muse Template")))
11232 (defun org-try-structure-completion ()
11233 "Try to complete a structure template before point.
11234 This looks for strings like \"<e\" on an otherwise empty line and
11235 expands them."
11236 (let ((l (buffer-substring (point-at-bol) (point)))
11238 (when (and (looking-at "[ \t]*$")
11239 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11240 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11241 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11242 (match-beginning 1)) a)
11243 t)))
11245 (defun org-complete-expand-structure-template (start cell)
11246 "Expand a structure template."
11247 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11248 (rpl (nth (if musep 2 1) cell))
11249 (ind ""))
11250 (delete-region start (point))
11251 (when (string-match "\\`#\\+" rpl)
11252 (cond
11253 ((bolp))
11254 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11255 (setq ind (buffer-substring (point-at-bol) (point))))
11256 (t (newline))))
11257 (setq start (point))
11258 (if (string-match "%file" rpl)
11259 (setq rpl (replace-match
11260 (concat
11261 "\""
11262 (save-match-data
11263 (abbreviate-file-name (read-file-name "Include file: ")))
11264 "\"")
11265 t t rpl)))
11266 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11267 (concat "\n" ind)))
11268 (insert rpl)
11269 (if (re-search-backward "\\?" start t) (delete-char 1))))
11271 ;;;; TODO, DEADLINE, Comments
11273 (defun org-toggle-comment ()
11274 "Change the COMMENT state of an entry."
11275 (interactive)
11276 (save-excursion
11277 (org-back-to-heading)
11278 (let (case-fold-search)
11279 (cond
11280 ((looking-at (format org-heading-keyword-regexp-format
11281 org-comment-string))
11282 (goto-char (match-end 1))
11283 (looking-at (concat " +" org-comment-string))
11284 (replace-match "" t t)
11285 (when (eolp) (insert " ")))
11286 ((looking-at org-outline-regexp)
11287 (goto-char (match-end 0))
11288 (insert org-comment-string " "))))))
11290 (defvar org-last-todo-state-is-todo nil
11291 "This is non-nil when the last TODO state change led to a TODO state.
11292 If the last change removed the TODO tag or switched to DONE, then
11293 this is nil.")
11295 (defvar org-setting-tags nil) ; dynamically skipped
11297 (defvar org-todo-setup-filter-hook nil
11298 "Hook for functions that pre-filter todo specs.
11299 Each function takes a todo spec and returns either nil or the spec
11300 transformed into canonical form." )
11302 (defvar org-todo-get-default-hook nil
11303 "Hook for functions that get a default item for todo.
11304 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11305 nil or a string to be used for the todo mark." )
11307 (defvar org-agenda-headline-snapshot-before-repeat)
11309 (defun org-current-effective-time ()
11310 "Return current time adjusted for `org-extend-today-until' variable"
11311 (let* ((ct (org-current-time))
11312 (dct (decode-time ct))
11313 (ct1
11314 (if (and org-use-effective-time
11315 (< (nth 2 dct) org-extend-today-until))
11316 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11317 ct)))
11318 ct1))
11320 (defun org-todo-yesterday (&optional arg)
11321 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11322 (interactive "P")
11323 (if (eq major-mode 'org-agenda-mode)
11324 (apply 'org-agenda-todo-yesterday arg)
11325 (let* ((hour (third (decode-time
11326 (org-current-time))))
11327 (org-extend-today-until (1+ hour)))
11328 (org-todo arg))))
11330 (defun org-todo (&optional arg)
11331 "Change the TODO state of an item.
11332 The state of an item is given by a keyword at the start of the heading,
11333 like
11334 *** TODO Write paper
11335 *** DONE Call mom
11337 The different keywords are specified in the variable `org-todo-keywords'.
11338 By default the available states are \"TODO\" and \"DONE\".
11339 So for this example: when the item starts with TODO, it is changed to DONE.
11340 When it starts with DONE, the DONE is removed. And when neither TODO nor
11341 DONE are present, add TODO at the beginning of the heading.
11343 With \\[universal-argument] prefix arg, use completion to determine the new \
11344 state.
11345 With numeric prefix arg, switch to that state.
11346 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11347 keywords (nextset).
11348 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11349 With a numeric prefix arg of 0, inhibit note taking for the change.
11351 For calling through lisp, arg is also interpreted in the following way:
11352 'none -> empty state
11353 \"\"(empty string) -> switch to empty state
11354 'done -> switch to DONE
11355 'nextset -> switch to the next set of keywords
11356 'previousset -> switch to the previous set of keywords
11357 \"WAITING\" -> switch to the specified keyword, but only if it
11358 really is a member of `org-todo-keywords'."
11359 (interactive "P")
11360 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11361 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11362 'region-start-level 'region))
11363 org-loop-over-headlines-in-active-region)
11364 (org-map-entries
11365 `(org-todo ,arg)
11366 org-loop-over-headlines-in-active-region
11367 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11368 (if (equal arg '(16)) (setq arg 'nextset))
11369 (let ((org-blocker-hook org-blocker-hook)
11370 (case-fold-search nil))
11371 (when (equal arg '(64))
11372 (setq arg nil org-blocker-hook nil))
11373 (when (and org-blocker-hook
11374 (or org-inhibit-blocking
11375 (org-entry-get nil "NOBLOCKING")))
11376 (setq org-blocker-hook nil))
11377 (save-excursion
11378 (catch 'exit
11379 (org-back-to-heading t)
11380 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11381 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11382 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11383 (let* ((match-data (match-data))
11384 (startpos (point-at-bol))
11385 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11386 (org-log-done org-log-done)
11387 (org-log-repeat org-log-repeat)
11388 (org-todo-log-states org-todo-log-states)
11389 (org-inhibit-logging
11390 (if (equal arg 0)
11391 (progn (setq arg nil) 'note) org-inhibit-logging))
11392 (this (match-string 1))
11393 (hl-pos (match-beginning 0))
11394 (head (org-get-todo-sequence-head this))
11395 (ass (assoc head org-todo-kwd-alist))
11396 (interpret (nth 1 ass))
11397 (done-word (nth 3 ass))
11398 (final-done-word (nth 4 ass))
11399 (org-last-state (or this ""))
11400 (completion-ignore-case t)
11401 (member (member this org-todo-keywords-1))
11402 (tail (cdr member))
11403 (org-state (cond
11404 ((and org-todo-key-trigger
11405 (or (and (equal arg '(4))
11406 (eq org-use-fast-todo-selection 'prefix))
11407 (and (not arg) org-use-fast-todo-selection
11408 (not (eq org-use-fast-todo-selection
11409 'prefix)))))
11410 ;; Use fast selection
11411 (org-fast-todo-selection))
11412 ((and (equal arg '(4))
11413 (or (not org-use-fast-todo-selection)
11414 (not org-todo-key-trigger)))
11415 ;; Read a state with completion
11416 (org-icompleting-read
11417 "State: " (mapcar (lambda(x) (list x))
11418 org-todo-keywords-1)
11419 nil t))
11420 ((eq arg 'right)
11421 (if this
11422 (if tail (car tail) nil)
11423 (car org-todo-keywords-1)))
11424 ((eq arg 'left)
11425 (if (equal member org-todo-keywords-1)
11427 (if this
11428 (nth (- (length org-todo-keywords-1)
11429 (length tail) 2)
11430 org-todo-keywords-1)
11431 (org-last org-todo-keywords-1))))
11432 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11433 (setq arg nil))) ; hack to fall back to cycling
11434 (arg
11435 ;; user or caller requests a specific state
11436 (cond
11437 ((equal arg "") nil)
11438 ((eq arg 'none) nil)
11439 ((eq arg 'done) (or done-word (car org-done-keywords)))
11440 ((eq arg 'nextset)
11441 (or (car (cdr (member head org-todo-heads)))
11442 (car org-todo-heads)))
11443 ((eq arg 'previousset)
11444 (let ((org-todo-heads (reverse org-todo-heads)))
11445 (or (car (cdr (member head org-todo-heads)))
11446 (car org-todo-heads))))
11447 ((car (member arg org-todo-keywords-1)))
11448 ((stringp arg)
11449 (error "State `%s' not valid in this file" arg))
11450 ((nth (1- (prefix-numeric-value arg))
11451 org-todo-keywords-1))))
11452 ((null member) (or head (car org-todo-keywords-1)))
11453 ((equal this final-done-word) nil) ;; -> make empty
11454 ((null tail) nil) ;; -> first entry
11455 ((memq interpret '(type priority))
11456 (if (eq this-command last-command)
11457 (car tail)
11458 (if (> (length tail) 0)
11459 (or done-word (car org-done-keywords))
11460 nil)))
11462 (car tail))))
11463 (org-state (or
11464 (run-hook-with-args-until-success
11465 'org-todo-get-default-hook org-state org-last-state)
11466 org-state))
11467 (next (if org-state (concat " " org-state " ") " "))
11468 (change-plist (list :type 'todo-state-change :from this :to org-state
11469 :position startpos))
11470 dolog now-done-p)
11471 (when org-blocker-hook
11472 (setq org-last-todo-state-is-todo
11473 (not (member this org-done-keywords)))
11474 (unless (save-excursion
11475 (save-match-data
11476 (org-with-wide-buffer
11477 (run-hook-with-args-until-failure
11478 'org-blocker-hook change-plist))))
11479 (if (org-called-interactively-p 'interactive)
11480 (error "TODO state change from %s to %s blocked" this org-state)
11481 ;; fail silently
11482 (message "TODO state change from %s to %s blocked" this org-state)
11483 (throw 'exit nil))))
11484 (store-match-data match-data)
11485 (replace-match next t t)
11486 (unless (pos-visible-in-window-p hl-pos)
11487 (message "TODO state changed to %s" (org-trim next)))
11488 (unless head
11489 (setq head (org-get-todo-sequence-head org-state)
11490 ass (assoc head org-todo-kwd-alist)
11491 interpret (nth 1 ass)
11492 done-word (nth 3 ass)
11493 final-done-word (nth 4 ass)))
11494 (when (memq arg '(nextset previousset))
11495 (message "Keyword-Set %d/%d: %s"
11496 (- (length org-todo-sets) -1
11497 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11498 (length org-todo-sets)
11499 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11500 (setq org-last-todo-state-is-todo
11501 (not (member org-state org-done-keywords)))
11502 (setq now-done-p (and (member org-state org-done-keywords)
11503 (not (member this org-done-keywords))))
11504 (and logging (org-local-logging logging))
11505 (when (and (or org-todo-log-states org-log-done)
11506 (not (eq org-inhibit-logging t))
11507 (not (memq arg '(nextset previousset))))
11508 ;; we need to look at recording a time and note
11509 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11510 (nth 2 (assoc this org-todo-log-states))))
11511 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11512 (setq dolog 'time))
11513 (when (and org-state
11514 (member org-state org-not-done-keywords)
11515 (not (member this org-not-done-keywords)))
11516 ;; This is now a todo state and was not one before
11517 ;; If there was a CLOSED time stamp, get rid of it.
11518 (org-add-planning-info nil nil 'closed))
11519 (when (and now-done-p org-log-done)
11520 ;; It is now done, and it was not done before
11521 (org-add-planning-info 'closed (org-current-effective-time))
11522 (if (and (not dolog) (eq 'note org-log-done))
11523 (org-add-log-setup 'done org-state this 'findpos 'note)))
11524 (when (and org-state dolog)
11525 ;; This is a non-nil state, and we need to log it
11526 (org-add-log-setup 'state org-state this 'findpos dolog)))
11527 ;; Fixup tag positioning
11528 (org-todo-trigger-tag-changes org-state)
11529 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11530 (when org-provide-todo-statistics
11531 (org-update-parent-todo-statistics))
11532 (run-hooks 'org-after-todo-state-change-hook)
11533 (if (and arg (not (member org-state org-done-keywords)))
11534 (setq head (org-get-todo-sequence-head org-state)))
11535 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11536 ;; Do we need to trigger a repeat?
11537 (when now-done-p
11538 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11539 ;; This is for the agenda, take a snapshot of the headline.
11540 (save-match-data
11541 (setq org-agenda-headline-snapshot-before-repeat
11542 (org-get-heading))))
11543 (org-auto-repeat-maybe org-state))
11544 ;; Fixup cursor location if close to the keyword
11545 (if (and (outline-on-heading-p)
11546 (not (bolp))
11547 (save-excursion (beginning-of-line 1)
11548 (looking-at org-todo-line-regexp))
11549 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11550 (progn
11551 (goto-char (or (match-end 2) (match-end 1)))
11552 (and (looking-at " ") (just-one-space))))
11553 (when org-trigger-hook
11554 (save-excursion
11555 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11557 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11558 "Block turning an entry into a TODO, using the hierarchy.
11559 This checks whether the current task should be blocked from state
11560 changes. Such blocking occurs when:
11562 1. The task has children which are not all in a completed state.
11564 2. A task has a parent with the property :ORDERED:, and there
11565 are siblings prior to the current task with incomplete
11566 status.
11568 3. The parent of the task is blocked because it has siblings that should
11569 be done first, or is child of a block grandparent TODO entry."
11571 (if (not org-enforce-todo-dependencies)
11572 t ; if locally turned off don't block
11573 (catch 'dont-block
11574 ;; If this is not a todo state change, or if this entry is already DONE,
11575 ;; do not block
11576 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11577 (member (plist-get change-plist :from)
11578 (cons 'done org-done-keywords))
11579 (member (plist-get change-plist :to)
11580 (cons 'todo org-not-done-keywords))
11581 (not (plist-get change-plist :to)))
11582 (throw 'dont-block t))
11583 ;; If this task has children, and any are undone, it's blocked
11584 (save-excursion
11585 (org-back-to-heading t)
11586 (let ((this-level (funcall outline-level)))
11587 (outline-next-heading)
11588 (let ((child-level (funcall outline-level)))
11589 (while (and (not (eobp))
11590 (> child-level this-level))
11591 ;; this todo has children, check whether they are all
11592 ;; completed
11593 (if (and (not (org-entry-is-done-p))
11594 (org-entry-is-todo-p))
11595 (throw 'dont-block nil))
11596 (outline-next-heading)
11597 (setq child-level (funcall outline-level))))))
11598 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11599 ;; any previous siblings are undone, it's blocked
11600 (save-excursion
11601 (org-back-to-heading t)
11602 (let* ((pos (point))
11603 (parent-pos (and (org-up-heading-safe) (point))))
11604 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11605 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11606 (forward-line 1)
11607 (re-search-forward org-not-done-heading-regexp pos t))
11608 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11609 ;; Search further up the hierarchy, to see if an ancestor is blocked
11610 (while t
11611 (goto-char parent-pos)
11612 (if (not (looking-at org-not-done-heading-regexp))
11613 (throw 'dont-block t)) ; do not block, parent is not a TODO
11614 (setq pos (point))
11615 (setq parent-pos (and (org-up-heading-safe) (point)))
11616 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11617 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11618 (forward-line 1)
11619 (re-search-forward org-not-done-heading-regexp pos t))
11620 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11622 (defcustom org-track-ordered-property-with-tag nil
11623 "Should the ORDERED property also be shown as a tag?
11624 The ORDERED property decides if an entry should require subtasks to be
11625 completed in sequence. Since a property is not very visible, setting
11626 this option means that toggling the ORDERED property with the command
11627 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11628 not relevant for the behavior, but it makes things more visible.
11630 Note that toggling the tag with tags commands will not change the property
11631 and therefore not influence behavior!
11633 This can be t, meaning the tag ORDERED should be used, It can also be a
11634 string to select a different tag for this task."
11635 :group 'org-todo
11636 :type '(choice
11637 (const :tag "No tracking" nil)
11638 (const :tag "Track with ORDERED tag" t)
11639 (string :tag "Use other tag")))
11641 (defun org-toggle-ordered-property ()
11642 "Toggle the ORDERED property of the current entry.
11643 For better visibility, you can track the value of this property with a tag.
11644 See variable `org-track-ordered-property-with-tag'."
11645 (interactive)
11646 (let* ((t1 org-track-ordered-property-with-tag)
11647 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11648 (save-excursion
11649 (org-back-to-heading)
11650 (if (org-entry-get nil "ORDERED")
11651 (progn
11652 (org-delete-property "ORDERED")
11653 (and tag (org-toggle-tag tag 'off))
11654 (message "Subtasks can be completed in arbitrary order"))
11655 (org-entry-put nil "ORDERED" "t")
11656 (and tag (org-toggle-tag tag 'on))
11657 (message "Subtasks must be completed in sequence")))))
11659 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11660 (defun org-block-todo-from-checkboxes (change-plist)
11661 "Block turning an entry into a TODO, using checkboxes.
11662 This checks whether the current task should be blocked from state
11663 changes because there are unchecked boxes in this entry."
11664 (if (not org-enforce-todo-checkbox-dependencies)
11665 t ; if locally turned off don't block
11666 (catch 'dont-block
11667 ;; If this is not a todo state change, or if this entry is already DONE,
11668 ;; do not block
11669 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11670 (member (plist-get change-plist :from)
11671 (cons 'done org-done-keywords))
11672 (member (plist-get change-plist :to)
11673 (cons 'todo org-not-done-keywords))
11674 (not (plist-get change-plist :to)))
11675 (throw 'dont-block t))
11676 ;; If this task has checkboxes that are not checked, it's blocked
11677 (save-excursion
11678 (org-back-to-heading t)
11679 (let ((beg (point)) end)
11680 (outline-next-heading)
11681 (setq end (point))
11682 (goto-char beg)
11683 (if (org-list-search-forward
11684 (concat (org-item-beginning-re)
11685 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11686 "\\[[- ]\\]")
11687 end t)
11688 (progn
11689 (if (boundp 'org-blocked-by-checkboxes)
11690 (setq org-blocked-by-checkboxes t))
11691 (throw 'dont-block nil)))))
11692 t))) ; do not block
11694 (defun org-entry-blocked-p ()
11695 "Is the current entry blocked?"
11696 (if (org-entry-get nil "NOBLOCKING")
11697 nil ;; Never block this entry
11698 (not
11699 (run-hook-with-args-until-failure
11700 'org-blocker-hook
11701 (list :type 'todo-state-change
11702 :position (point)
11703 :from 'todo
11704 :to 'done)))))
11706 (defun org-update-statistics-cookies (all)
11707 "Update the statistics cookie, either from TODO or from checkboxes.
11708 This should be called with the cursor in a line with a statistics cookie."
11709 (interactive "P")
11710 (if all
11711 (progn
11712 (org-update-checkbox-count 'all)
11713 (org-map-entries 'org-update-parent-todo-statistics))
11714 (if (not (org-at-heading-p))
11715 (org-update-checkbox-count)
11716 (let ((pos (move-marker (make-marker) (point)))
11717 end l1 l2)
11718 (ignore-errors (org-back-to-heading t))
11719 (if (not (org-at-heading-p))
11720 (org-update-checkbox-count)
11721 (setq l1 (org-outline-level))
11722 (setq end (save-excursion
11723 (outline-next-heading)
11724 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11725 (point)))
11726 (if (and (save-excursion
11727 (re-search-forward
11728 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11729 (not (save-excursion (re-search-forward
11730 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11731 (org-update-checkbox-count)
11732 (if (and l2 (> l2 l1))
11733 (progn
11734 (goto-char end)
11735 (org-update-parent-todo-statistics))
11736 (goto-char pos)
11737 (beginning-of-line 1)
11738 (while (re-search-forward
11739 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11740 (point-at-eol) t)
11741 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11742 (goto-char pos)
11743 (move-marker pos nil)))))
11745 (defvar org-entry-property-inherited-from) ;; defined below
11746 (defun org-update-parent-todo-statistics ()
11747 "Update any statistics cookie in the parent of the current headline.
11748 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11749 the entire subtree and this will travel up the hierarchy and update
11750 statistics everywhere."
11751 (let* ((prop (save-excursion (org-up-heading-safe)
11752 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11753 (recursive (or (not org-hierarchical-todo-statistics)
11754 (and prop (string-match "\\<recursive\\>" prop))))
11755 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11757 (first t)
11758 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11759 level ltoggle l1 new ndel
11760 (cnt-all 0) (cnt-done 0) is-percent kwd
11761 checkbox-beg ov ovs ove cookie-present)
11762 (catch 'exit
11763 (save-excursion
11764 (beginning-of-line 1)
11765 (setq ltoggle (funcall outline-level))
11766 ;; Three situations are to consider:
11768 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11769 ;; to the top-level ancestor on the headline;
11771 ;; 2. If parent has "recursive" property, repeat up to the
11772 ;; headline setting that property, taking inheritance into
11773 ;; account;
11775 ;; 3. Else, move up to direct parent and proceed only once.
11776 (while (and (setq level (org-up-heading-safe))
11777 (or recursive first)
11778 (>= (point) lim))
11779 (setq first nil cookie-present nil)
11780 (unless (and level
11781 (not (string-match
11782 "\\<checkbox\\>"
11783 (downcase (or (org-entry-get nil "COOKIE_DATA")
11784 "")))))
11785 (throw 'exit nil))
11786 (while (re-search-forward box-re (point-at-eol) t)
11787 (setq cnt-all 0 cnt-done 0 cookie-present t)
11788 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11789 (save-match-data
11790 (unless (outline-next-heading) (throw 'exit nil))
11791 (while (and (looking-at org-complex-heading-regexp)
11792 (> (setq l1 (length (match-string 1))) level))
11793 (setq kwd (and (or recursive (= l1 ltoggle))
11794 (match-string 2)))
11795 (if (or (eq org-provide-todo-statistics 'all-headlines)
11796 (and (listp org-provide-todo-statistics)
11797 (or (member kwd org-provide-todo-statistics)
11798 (member kwd org-done-keywords))))
11799 (setq cnt-all (1+ cnt-all))
11800 (if (eq org-provide-todo-statistics t)
11801 (and kwd (setq cnt-all (1+ cnt-all)))))
11802 (and (member kwd org-done-keywords)
11803 (setq cnt-done (1+ cnt-done)))
11804 (outline-next-heading)))
11805 (setq new
11806 (if is-percent
11807 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11808 (format "[%d/%d]" cnt-done cnt-all))
11809 ndel (- (match-end 0) checkbox-beg))
11810 ;; handle overlays when updating cookie from column view
11811 (when (setq ov (car (overlays-at checkbox-beg)))
11812 (setq ovs (overlay-start ov) ove (overlay-end ov))
11813 (delete-overlay ov))
11814 (goto-char checkbox-beg)
11815 (insert new)
11816 (delete-region (point) (+ (point) ndel))
11817 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11818 (when ov (move-overlay ov ovs ove)))
11819 (when cookie-present
11820 (run-hook-with-args 'org-after-todo-statistics-hook
11821 cnt-done (- cnt-all cnt-done))))))
11822 (run-hooks 'org-todo-statistics-hook)))
11824 (defvar org-after-todo-statistics-hook nil
11825 "Hook that is called after a TODO statistics cookie has been updated.
11826 Each function is called with two arguments: the number of not-done entries
11827 and the number of done entries.
11829 For example, the following function, when added to this hook, will switch
11830 an entry to DONE when all children are done, and back to TODO when new
11831 entries are set to a TODO status. Note that this hook is only called
11832 when there is a statistics cookie in the headline!
11834 (defun org-summary-todo (n-done n-not-done)
11835 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11836 (let (org-log-done org-log-states) ; turn off logging
11837 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11840 (defvar org-todo-statistics-hook nil
11841 "Hook that is run whenever Org thinks TODO statistics should be updated.
11842 This hook runs even if there is no statistics cookie present, in which case
11843 `org-after-todo-statistics-hook' would not run.")
11845 (defun org-todo-trigger-tag-changes (state)
11846 "Apply the changes defined in `org-todo-state-tags-triggers'."
11847 (let ((l org-todo-state-tags-triggers)
11848 changes)
11849 (when (or (not state) (equal state ""))
11850 (setq changes (append changes (cdr (assoc "" l)))))
11851 (when (and (stringp state) (> (length state) 0))
11852 (setq changes (append changes (cdr (assoc state l)))))
11853 (when (member state org-not-done-keywords)
11854 (setq changes (append changes (cdr (assoc 'todo l)))))
11855 (when (member state org-done-keywords)
11856 (setq changes (append changes (cdr (assoc 'done l)))))
11857 (dolist (c changes)
11858 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11860 (defun org-local-logging (value)
11861 "Get logging settings from a property VALUE."
11862 (let* (words w a)
11863 ;; directly set the variables, they are already local.
11864 (setq org-log-done nil
11865 org-log-repeat nil
11866 org-todo-log-states nil)
11867 (setq words (org-split-string value))
11868 (while (setq w (pop words))
11869 (cond
11870 ((setq a (assoc w org-startup-options))
11871 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11872 (set (nth 1 a) (nth 2 a))))
11873 ((setq a (org-extract-log-state-settings w))
11874 (and (member (car a) org-todo-keywords-1)
11875 (push a org-todo-log-states)))))))
11877 (defun org-get-todo-sequence-head (kwd)
11878 "Return the head of the TODO sequence to which KWD belongs.
11879 If KWD is not set, check if there is a text property remembering the
11880 right sequence."
11881 (let (p)
11882 (cond
11883 ((not kwd)
11884 (or (get-text-property (point-at-bol) 'org-todo-head)
11885 (progn
11886 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11887 nil (point-at-eol)))
11888 (get-text-property p 'org-todo-head))))
11889 ((not (member kwd org-todo-keywords-1))
11890 (car org-todo-keywords-1))
11891 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11893 (defun org-fast-todo-selection ()
11894 "Fast TODO keyword selection with single keys.
11895 Returns the new TODO keyword, or nil if no state change should occur."
11896 (let* ((fulltable org-todo-key-alist)
11897 (done-keywords org-done-keywords) ;; needed for the faces.
11898 (maxlen (apply 'max (mapcar
11899 (lambda (x)
11900 (if (stringp (car x)) (string-width (car x)) 0))
11901 fulltable)))
11902 (expert nil)
11903 (fwidth (+ maxlen 3 1 3))
11904 (ncol (/ (- (window-width) 4) fwidth))
11905 tg cnt e c tbl
11906 groups ingroup)
11907 (save-excursion
11908 (save-window-excursion
11909 (if expert
11910 (set-buffer (get-buffer-create " *Org todo*"))
11911 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11912 (erase-buffer)
11913 (org-set-local 'org-done-keywords done-keywords)
11914 (setq tbl fulltable cnt 0)
11915 (while (setq e (pop tbl))
11916 (cond
11917 ((equal e '(:startgroup))
11918 (push '() groups) (setq ingroup t)
11919 (when (not (= cnt 0))
11920 (setq cnt 0)
11921 (insert "\n"))
11922 (insert "{ "))
11923 ((equal e '(:endgroup))
11924 (setq ingroup nil cnt 0)
11925 (insert "}\n"))
11926 ((equal e '(:newline))
11927 (when (not (= cnt 0))
11928 (setq cnt 0)
11929 (insert "\n")
11930 (setq e (car tbl))
11931 (while (equal (car tbl) '(:newline))
11932 (insert "\n")
11933 (setq tbl (cdr tbl)))))
11935 (setq tg (car e) c (cdr e))
11936 (if ingroup (push tg (car groups)))
11937 (setq tg (org-add-props tg nil 'face
11938 (org-get-todo-face tg)))
11939 (if (and (= cnt 0) (not ingroup)) (insert " "))
11940 (insert "[" c "] " tg (make-string
11941 (- fwidth 4 (length tg)) ?\ ))
11942 (when (= (setq cnt (1+ cnt)) ncol)
11943 (insert "\n")
11944 (if ingroup (insert " "))
11945 (setq cnt 0)))))
11946 (insert "\n")
11947 (goto-char (point-min))
11948 (if (not expert) (org-fit-window-to-buffer))
11949 (message "[a-z..]:Set [SPC]:clear")
11950 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11951 (cond
11952 ((or (= c ?\C-g)
11953 (and (= c ?q) (not (rassoc c fulltable))))
11954 (setq quit-flag t))
11955 ((= c ?\ ) nil)
11956 ((setq e (rassoc c fulltable) tg (car e))
11958 (t (setq quit-flag t)))))))
11960 (defun org-entry-is-todo-p ()
11961 (member (org-get-todo-state) org-not-done-keywords))
11963 (defun org-entry-is-done-p ()
11964 (member (org-get-todo-state) org-done-keywords))
11966 (defun org-get-todo-state ()
11967 (save-excursion
11968 (org-back-to-heading t)
11969 (and (looking-at org-todo-line-regexp)
11970 (match-end 2)
11971 (match-string 2))))
11973 (defun org-at-date-range-p (&optional inactive-ok)
11974 "Is the cursor inside a date range?"
11975 (interactive)
11976 (save-excursion
11977 (catch 'exit
11978 (let ((pos (point)))
11979 (skip-chars-backward "^[<\r\n")
11980 (skip-chars-backward "<[")
11981 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11982 (>= (match-end 0) pos)
11983 (throw 'exit t))
11984 (skip-chars-backward "^<[\r\n")
11985 (skip-chars-backward "<[")
11986 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11987 (>= (match-end 0) pos)
11988 (throw 'exit t)))
11989 nil)))
11991 (defun org-get-repeat (&optional tagline)
11992 "Check if there is a deadline/schedule with repeater in this entry."
11993 (save-match-data
11994 (save-excursion
11995 (org-back-to-heading t)
11996 (and (re-search-forward (if tagline
11997 (concat tagline "\\s-*" org-repeat-re)
11998 org-repeat-re)
11999 (org-entry-end-position) t)
12000 (match-string-no-properties 1)))))
12002 (defvar org-last-changed-timestamp)
12003 (defvar org-last-inserted-timestamp)
12004 (defvar org-log-post-message)
12005 (defvar org-log-note-purpose)
12006 (defvar org-log-note-how)
12007 (defvar org-log-note-extra)
12008 (defun org-auto-repeat-maybe (done-word)
12009 "Check if the current headline contains a repeated deadline/schedule.
12010 If yes, set TODO state back to what it was and change the base date
12011 of repeating deadline/scheduled time stamps to new date.
12012 This function is run automatically after each state change to a DONE state."
12013 ;; last-state is dynamically scoped into this function
12014 (let* ((repeat (org-get-repeat))
12015 (aa (assoc org-last-state org-todo-kwd-alist))
12016 (interpret (nth 1 aa))
12017 (head (nth 2 aa))
12018 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12019 (msg "Entry repeats: ")
12020 (org-log-done nil)
12021 (org-todo-log-states nil)
12022 re type n what ts time to-state)
12023 (when repeat
12024 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12025 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12026 org-todo-repeat-to-state))
12027 (unless (and to-state (member to-state org-todo-keywords-1))
12028 (setq to-state (if (eq interpret 'type) org-last-state head)))
12029 (org-todo to-state)
12030 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12031 (org-entry-put nil "LAST_REPEAT" (format-time-string
12032 (org-time-stamp-format t t))))
12033 (when org-log-repeat
12034 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12035 (memq 'org-add-log-note post-command-hook))
12036 ;; OK, we are already setup for some record
12037 (if (eq org-log-repeat 'note)
12038 ;; make sure we take a note, not only a time stamp
12039 (setq org-log-note-how 'note))
12040 ;; Set up for taking a record
12041 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12042 org-last-state
12043 'findpos org-log-repeat)))
12044 (org-back-to-heading t)
12045 (org-add-planning-info nil nil 'closed)
12046 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12047 org-deadline-time-regexp "\\)\\|\\("
12048 org-ts-regexp "\\)"))
12049 (while (re-search-forward
12050 re (save-excursion (outline-next-heading) (point)) t)
12051 (setq type (if (match-end 1) org-scheduled-string
12052 (if (match-end 3) org-deadline-string "Plain:"))
12053 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12054 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12055 (setq n (string-to-number (match-string 2 ts))
12056 what (match-string 3 ts))
12057 (if (equal what "w") (setq n (* n 7) what "d"))
12058 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12059 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12060 ;; Preparation, see if we need to modify the start date for the change
12061 (when (match-end 1)
12062 (setq time (save-match-data (org-time-string-to-time ts)))
12063 (cond
12064 ((equal (match-string 1 ts) ".")
12065 ;; Shift starting date to today
12066 (org-timestamp-change
12067 (- (org-today) (time-to-days time))
12068 'day))
12069 ((equal (match-string 1 ts) "+")
12070 (let ((nshiftmax 10) (nshift 0))
12071 (while (or (= nshift 0)
12072 (<= (time-to-days time)
12073 (time-to-days (current-time))))
12074 (when (= (incf nshift) nshiftmax)
12075 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12076 (error "Abort")))
12077 (org-timestamp-change n (cdr (assoc what whata)))
12078 (org-at-timestamp-p t)
12079 (setq ts (match-string 1))
12080 (setq time (save-match-data (org-time-string-to-time ts)))))
12081 (org-timestamp-change (- n) (cdr (assoc what whata)))
12082 ;; rematch, so that we have everything in place for the real shift
12083 (org-at-timestamp-p t)
12084 (setq ts (match-string 1))
12085 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12086 (org-timestamp-change n (cdr (assoc what whata)))
12087 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12088 (setq org-log-post-message msg)
12089 (message "%s" msg))))
12091 (defun org-show-todo-tree (arg)
12092 "Make a compact tree which shows all headlines marked with TODO.
12093 The tree will show the lines where the regexp matches, and all higher
12094 headlines above the match.
12095 With a \\[universal-argument] prefix, prompt for a regexp to match.
12096 With a numeric prefix N, construct a sparse tree for the Nth element
12097 of `org-todo-keywords-1'."
12098 (interactive "P")
12099 (let ((case-fold-search nil)
12100 (kwd-re
12101 (cond ((null arg) org-not-done-regexp)
12102 ((equal arg '(4))
12103 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12104 (mapcar 'list org-todo-keywords-1))))
12105 (concat "\\("
12106 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12107 "\\)\\>")))
12108 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12109 (regexp-quote (nth (1- (prefix-numeric-value arg))
12110 org-todo-keywords-1)))
12111 (t (error "Invalid prefix argument: %s" arg)))))
12112 (message "%d TODO entries found"
12113 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12115 (defun org-deadline (&optional remove time)
12116 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12117 With argument REMOVE, remove any deadline from the item.
12118 With argument TIME, set the deadline at the corresponding date. TIME
12119 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12120 (interactive "P")
12121 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12122 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12123 'region-start-level 'region))
12124 org-loop-over-headlines-in-active-region)
12125 (org-map-entries
12126 `(org-deadline ',remove ,time)
12127 org-loop-over-headlines-in-active-region
12128 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12129 (let* ((old-date (org-entry-get nil "DEADLINE"))
12130 (repeater (and old-date
12131 (string-match
12132 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12133 old-date)
12134 (match-string 1 old-date))))
12135 (if remove
12136 (progn
12137 (when (and old-date org-log-redeadline)
12138 (org-add-log-setup 'deldeadline nil old-date 'findpos
12139 org-log-redeadline))
12140 (org-remove-timestamp-with-keyword org-deadline-string)
12141 (message "Item no longer has a deadline."))
12142 (org-add-planning-info 'deadline time 'closed)
12143 (when (and old-date org-log-redeadline
12144 (not (equal old-date
12145 (substring org-last-inserted-timestamp 1 -1))))
12146 (org-add-log-setup 'redeadline nil old-date 'findpos
12147 org-log-redeadline))
12148 (when repeater
12149 (save-excursion
12150 (org-back-to-heading t)
12151 (when (re-search-forward (concat org-deadline-string " "
12152 org-last-inserted-timestamp)
12153 (save-excursion
12154 (outline-next-heading) (point)) t)
12155 (goto-char (1- (match-end 0)))
12156 (insert " " repeater)
12157 (setq org-last-inserted-timestamp
12158 (concat (substring org-last-inserted-timestamp 0 -1)
12159 " " repeater
12160 (substring org-last-inserted-timestamp -1))))))
12161 (message "Deadline on %s" org-last-inserted-timestamp)))))
12163 (defun org-schedule (&optional remove time)
12164 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12165 With argument REMOVE, remove any scheduling date from the item.
12166 With argument TIME, scheduled at the corresponding date. TIME can
12167 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12168 (interactive "P")
12169 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12170 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12171 'region-start-level 'region))
12172 org-loop-over-headlines-in-active-region)
12173 (org-map-entries
12174 `(org-schedule ',remove ,time)
12175 org-loop-over-headlines-in-active-region
12176 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12177 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12178 (repeater (and old-date
12179 (string-match
12180 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12181 old-date)
12182 (match-string 1 old-date))))
12183 (if remove
12184 (progn
12185 (when (and old-date org-log-reschedule)
12186 (org-add-log-setup 'delschedule nil old-date 'findpos
12187 org-log-reschedule))
12188 (org-remove-timestamp-with-keyword org-scheduled-string)
12189 (message "Item is no longer scheduled."))
12190 (org-add-planning-info 'scheduled time 'closed)
12191 (when (and old-date org-log-reschedule
12192 (not (equal old-date
12193 (substring org-last-inserted-timestamp 1 -1))))
12194 (org-add-log-setup 'reschedule nil old-date 'findpos
12195 org-log-reschedule))
12196 (when repeater
12197 (save-excursion
12198 (org-back-to-heading t)
12199 (when (re-search-forward (concat org-scheduled-string " "
12200 org-last-inserted-timestamp)
12201 (save-excursion
12202 (outline-next-heading) (point)) t)
12203 (goto-char (1- (match-end 0)))
12204 (insert " " repeater)
12205 (setq org-last-inserted-timestamp
12206 (concat (substring org-last-inserted-timestamp 0 -1)
12207 " " repeater
12208 (substring org-last-inserted-timestamp -1))))))
12209 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12211 (defun org-get-scheduled-time (pom &optional inherit)
12212 "Get the scheduled time as a time tuple, of a format suitable
12213 for calling org-schedule with, or if there is no scheduling,
12214 returns nil."
12215 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12216 (when time
12217 (apply 'encode-time (org-parse-time-string time)))))
12219 (defun org-get-deadline-time (pom &optional inherit)
12220 "Get the deadline as a time tuple, of a format suitable for
12221 calling org-deadline with, or if there is no scheduling, returns
12222 nil."
12223 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12224 (when time
12225 (apply 'encode-time (org-parse-time-string time)))))
12227 (defun org-remove-timestamp-with-keyword (keyword)
12228 "Remove all time stamps with KEYWORD in the current entry."
12229 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12230 beg)
12231 (save-excursion
12232 (org-back-to-heading t)
12233 (setq beg (point))
12234 (outline-next-heading)
12235 (while (re-search-backward re beg t)
12236 (replace-match "")
12237 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12238 (equal (char-before) ?\ ))
12239 (backward-delete-char 1)
12240 (if (string-match "^[ \t]*$" (buffer-substring
12241 (point-at-bol) (point-at-eol)))
12242 (delete-region (point-at-bol)
12243 (min (point-max) (1+ (point-at-eol))))))))))
12245 (defun org-add-planning-info (what &optional time &rest remove)
12246 "Insert new timestamp with keyword in the line directly after the headline.
12247 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12248 If non is given, the user is prompted for a date.
12249 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12250 be removed."
12251 (interactive)
12252 (let (org-time-was-given org-end-time-was-given ts
12253 end default-time default-input)
12255 (catch 'exit
12256 (when (and (memq what '(scheduled deadline))
12257 (or (not time)
12258 (and (stringp time)
12259 (string-match "^[-+]+[0-9]" time))))
12260 ;; Try to get a default date/time from existing timestamp
12261 (save-excursion
12262 (org-back-to-heading t)
12263 (setq end (save-excursion (outline-next-heading) (point)))
12264 (when (re-search-forward (if (eq what 'scheduled)
12265 org-scheduled-time-regexp
12266 org-deadline-time-regexp)
12267 end t)
12268 (setq ts (match-string 1)
12269 default-time
12270 (apply 'encode-time (org-parse-time-string ts))
12271 default-input (and ts (org-get-compact-tod ts))))))
12272 (when what
12273 (setq time
12274 (if (stringp time)
12275 ;; This is a string (relative or absolute), set proper date
12276 (apply 'encode-time
12277 (org-read-date-analyze
12278 time default-time (decode-time default-time)))
12279 ;; If necessary, get the time from the user
12280 (or time (org-read-date nil 'to-time nil nil
12281 default-time default-input)))))
12283 (when (and org-insert-labeled-timestamps-at-point
12284 (member what '(scheduled deadline)))
12285 (insert
12286 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12287 (org-insert-time-stamp time org-time-was-given
12288 nil nil nil (list org-end-time-was-given))
12289 (setq what nil))
12290 (save-excursion
12291 (save-restriction
12292 (let (col list elt ts buffer-invisibility-spec)
12293 (org-back-to-heading t)
12294 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12295 (goto-char (match-end 1))
12296 (setq col (current-column))
12297 (goto-char (match-end 0))
12298 (if (eobp) (insert "\n") (forward-char 1))
12299 (when (and (not what)
12300 (not (looking-at
12301 (concat "[ \t]*"
12302 org-keyword-time-not-clock-regexp))))
12303 ;; Nothing to add, nothing to remove...... :-)
12304 (throw 'exit nil))
12305 (if (and (not (looking-at org-outline-regexp))
12306 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12307 "[^\r\n]*"))
12308 (not (equal (match-string 1) org-clock-string)))
12309 (narrow-to-region (match-beginning 0) (match-end 0))
12310 (insert-before-markers "\n")
12311 (backward-char 1)
12312 (narrow-to-region (point) (point))
12313 (and org-adapt-indentation (org-indent-to-column col)))
12314 ;; Check if we have to remove something.
12315 (setq list (cons what remove))
12316 (while list
12317 (setq elt (pop list))
12318 (when (or (and (eq elt 'scheduled)
12319 (re-search-forward org-scheduled-time-regexp nil t))
12320 (and (eq elt 'deadline)
12321 (re-search-forward org-deadline-time-regexp nil t))
12322 (and (eq elt 'closed)
12323 (re-search-forward org-closed-time-regexp nil t)))
12324 (replace-match "")
12325 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12326 (and (looking-at "[ \t]+") (replace-match ""))
12327 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12328 (when what
12329 (insert
12330 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12331 (cond ((eq what 'scheduled) org-scheduled-string)
12332 ((eq what 'deadline) org-deadline-string)
12333 ((eq what 'closed) org-closed-string))
12334 " ")
12335 (setq ts (org-insert-time-stamp
12336 time
12337 (or org-time-was-given
12338 (and (eq what 'closed) org-log-done-with-time))
12339 (eq what 'closed)
12340 nil nil (list org-end-time-was-given)))
12341 (insert
12342 (if (not (or (bolp) (eq (char-before) ?\ )
12343 (memq (char-after) '(32 10))
12344 (eobp))) " " ""))
12345 (end-of-line 1))
12346 (goto-char (point-min))
12347 (widen)
12348 (if (and (looking-at "[ \t]*\n")
12349 (equal (char-before) ?\n))
12350 (delete-region (1- (point)) (point-at-eol)))
12351 ts))))))
12353 (defvar org-log-note-marker (make-marker))
12354 (defvar org-log-note-purpose nil)
12355 (defvar org-log-note-state nil)
12356 (defvar org-log-note-previous-state nil)
12357 (defvar org-log-note-how nil)
12358 (defvar org-log-note-extra nil)
12359 (defvar org-log-note-window-configuration nil)
12360 (defvar org-log-note-return-to (make-marker))
12361 (defvar org-log-note-effective-time nil
12362 "Remembered current time so that dynamically scoped
12363 `org-extend-today-until' affects tha timestamps in state change
12364 log")
12366 (defvar org-log-post-message nil
12367 "Message to be displayed after a log note has been stored.
12368 The auto-repeater uses this.")
12370 (defun org-add-note ()
12371 "Add a note to the current entry.
12372 This is done in the same way as adding a state change note."
12373 (interactive)
12374 (org-add-log-setup 'note nil nil 'findpos nil))
12376 (defvar org-property-end-re)
12377 (defun org-add-log-setup (&optional purpose state prev-state
12378 findpos how extra)
12379 "Set up the post command hook to take a note.
12380 If this is about to TODO state change, the new state is expected in STATE.
12381 When FINDPOS is non-nil, find the correct position for the note in
12382 the current entry. If not, assume that it can be inserted at point.
12383 HOW is an indicator what kind of note should be created.
12384 EXTRA is additional text that will be inserted into the notes buffer."
12385 (let* ((org-log-into-drawer (org-log-into-drawer))
12386 (drawer (cond ((stringp org-log-into-drawer)
12387 org-log-into-drawer)
12388 (org-log-into-drawer "LOGBOOK")
12389 (t nil))))
12390 (save-restriction
12391 (save-excursion
12392 (when findpos
12393 (org-back-to-heading t)
12394 (narrow-to-region (point) (save-excursion
12395 (outline-next-heading) (point)))
12396 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12397 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12398 "[^\r\n]*\\)?"))
12399 (goto-char (match-end 0))
12400 (cond
12401 (drawer
12402 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12403 nil t)
12404 (progn
12405 (goto-char (match-end 0))
12406 (or org-log-states-order-reversed
12407 (and (re-search-forward org-property-end-re nil t)
12408 (goto-char (1- (match-beginning 0))))))
12409 (insert "\n:" drawer ":\n:END:")
12410 (beginning-of-line 0)
12411 (org-indent-line)
12412 (beginning-of-line 2)
12413 (org-indent-line)
12414 (end-of-line 0)))
12415 ((and org-log-state-notes-insert-after-drawers
12416 (save-excursion
12417 (forward-line) (looking-at org-drawer-regexp)))
12418 (forward-line)
12419 (while (looking-at org-drawer-regexp)
12420 (goto-char (match-end 0))
12421 (re-search-forward org-property-end-re (point-max) t)
12422 (forward-line))
12423 (forward-line -1)))
12424 (unless org-log-states-order-reversed
12425 (and (= (char-after) ?\n) (forward-char 1))
12426 (org-skip-over-state-notes)
12427 (skip-chars-backward " \t\n\r")))
12428 (move-marker org-log-note-marker (point))
12429 (setq org-log-note-purpose purpose
12430 org-log-note-state state
12431 org-log-note-previous-state prev-state
12432 org-log-note-how how
12433 org-log-note-extra extra
12434 org-log-note-effective-time (org-current-effective-time))
12435 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12437 (defun org-skip-over-state-notes ()
12438 "Skip past the list of State notes in an entry."
12439 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12440 (when (ignore-errors (goto-char (org-in-item-p)))
12441 (let* ((struct (org-list-struct))
12442 (prevs (org-list-prevs-alist struct)))
12443 (while (looking-at "[ \t]*- State")
12444 (goto-char (or (org-list-get-next-item (point) struct prevs)
12445 (org-list-get-item-end (point) struct)))))))
12447 (defun org-add-log-note (&optional purpose)
12448 "Pop up a window for taking a note, and add this note later at point."
12449 (remove-hook 'post-command-hook 'org-add-log-note)
12450 (setq org-log-note-window-configuration (current-window-configuration))
12451 (delete-other-windows)
12452 (move-marker org-log-note-return-to (point))
12453 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12454 (goto-char org-log-note-marker)
12455 (org-switch-to-buffer-other-window "*Org Note*")
12456 (erase-buffer)
12457 (if (memq org-log-note-how '(time state))
12458 (let (current-prefix-arg) (org-store-log-note))
12459 (let ((org-inhibit-startup t)) (org-mode))
12460 (insert (format "# Insert note for %s.
12461 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12462 (cond
12463 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12464 ((eq org-log-note-purpose 'done) "closed todo item")
12465 ((eq org-log-note-purpose 'state)
12466 (format "state change from \"%s\" to \"%s\""
12467 (or org-log-note-previous-state "")
12468 (or org-log-note-state "")))
12469 ((eq org-log-note-purpose 'reschedule)
12470 "rescheduling")
12471 ((eq org-log-note-purpose 'delschedule)
12472 "no longer scheduled")
12473 ((eq org-log-note-purpose 'redeadline)
12474 "changing deadline")
12475 ((eq org-log-note-purpose 'deldeadline)
12476 "removing deadline")
12477 ((eq org-log-note-purpose 'refile)
12478 "refiling")
12479 ((eq org-log-note-purpose 'note)
12480 "this entry")
12481 (t (error "This should not happen")))))
12482 (if org-log-note-extra (insert org-log-note-extra))
12483 (org-set-local 'org-finish-function 'org-store-log-note)
12484 (run-hooks 'org-log-buffer-setup-hook)))
12486 (defvar org-note-abort nil) ; dynamically scoped
12487 (defun org-store-log-note ()
12488 "Finish taking a log note, and insert it to where it belongs."
12489 (let ((txt (buffer-string))
12490 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12491 lines ind bul)
12492 (kill-buffer (current-buffer))
12493 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12494 (setq txt (replace-match "" t t txt)))
12495 (if (string-match "\\s-+\\'" txt)
12496 (setq txt (replace-match "" t t txt)))
12497 (setq lines (org-split-string txt "\n"))
12498 (when (and note (string-match "\\S-" note))
12499 (setq note
12500 (org-replace-escapes
12501 note
12502 (list (cons "%u" (user-login-name))
12503 (cons "%U" user-full-name)
12504 (cons "%t" (format-time-string
12505 (org-time-stamp-format 'long 'inactive)
12506 org-log-note-effective-time))
12507 (cons "%T" (format-time-string
12508 (org-time-stamp-format 'long nil)
12509 org-log-note-effective-time))
12510 (cons "%d" (format-time-string
12511 (org-time-stamp-format nil 'inactive)
12512 org-log-note-effective-time))
12513 (cons "%D" (format-time-string
12514 (org-time-stamp-format nil nil)
12515 org-log-note-effective-time))
12516 (cons "%s" (if org-log-note-state
12517 (concat "\"" org-log-note-state "\"")
12518 ""))
12519 (cons "%S" (if org-log-note-previous-state
12520 (concat "\"" org-log-note-previous-state "\"")
12521 "\"\"")))))
12522 (if lines (setq note (concat note " \\\\")))
12523 (push note lines))
12524 (when (or current-prefix-arg org-note-abort)
12525 (when org-log-into-drawer
12526 (org-remove-empty-drawer-at
12527 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12528 org-log-note-marker))
12529 (setq lines nil))
12530 (when lines
12531 (with-current-buffer (marker-buffer org-log-note-marker)
12532 (save-excursion
12533 (goto-char org-log-note-marker)
12534 (move-marker org-log-note-marker nil)
12535 (end-of-line 1)
12536 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12537 (setq ind (save-excursion
12538 (if (ignore-errors (goto-char (org-in-item-p)))
12539 (let ((struct (org-list-struct)))
12540 (org-list-get-ind
12541 (org-list-get-top-point struct) struct))
12542 (skip-chars-backward " \r\t\n")
12543 (cond
12544 ((and (org-at-heading-p)
12545 org-adapt-indentation)
12546 (1+ (org-current-level)))
12547 ((org-at-heading-p) 0)
12548 (t (org-get-indentation))))))
12549 (setq bul (org-list-bullet-string "-"))
12550 (org-indent-line-to ind)
12551 (insert bul (pop lines))
12552 (let ((ind-body (+ (length bul) ind)))
12553 (while lines
12554 (insert "\n")
12555 (org-indent-line-to ind-body)
12556 (insert (pop lines))))
12557 (message "Note stored")
12558 (org-back-to-heading t)
12559 (org-cycle-hide-drawers 'children)))))
12560 (set-window-configuration org-log-note-window-configuration)
12561 (with-current-buffer (marker-buffer org-log-note-return-to)
12562 (goto-char org-log-note-return-to))
12563 (move-marker org-log-note-return-to nil)
12564 (and org-log-post-message (message "%s" org-log-post-message)))
12566 (defun org-remove-empty-drawer-at (drawer pos)
12567 "Remove an empty drawer DRAWER at position POS.
12568 POS may also be a marker."
12569 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12570 (save-excursion
12571 (save-restriction
12572 (widen)
12573 (goto-char pos)
12574 (if (org-in-regexp
12575 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12576 (replace-match ""))))))
12578 (defun org-sparse-tree (&optional arg)
12579 "Create a sparse tree, prompt for the details.
12580 This command can create sparse trees. You first need to select the type
12581 of match used to create the tree:
12583 t Show all TODO entries.
12584 T Show entries with a specific TODO keyword.
12585 m Show entries selected by a tags/property match.
12586 p Enter a property name and its value (both with completion on existing
12587 names/values) and show entries with that property.
12588 r Show entries matching a regular expression (`/' can be used as well)
12589 d Show deadlines due within `org-deadline-warning-days'.
12590 b Show deadlines and scheduled items before a date.
12591 a Show deadlines and scheduled items after a date."
12592 (interactive "P")
12593 (let (ans kwd value)
12594 (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")
12595 (setq ans (read-char-exclusive))
12596 (cond
12597 ((equal ans ?d)
12598 (call-interactively 'org-check-deadlines))
12599 ((equal ans ?b)
12600 (call-interactively 'org-check-before-date))
12601 ((equal ans ?a)
12602 (call-interactively 'org-check-after-date))
12603 ((equal ans ?D)
12604 (call-interactively 'org-check-dates-range))
12605 ((equal ans ?t)
12606 (org-show-todo-tree nil))
12607 ((equal ans ?T)
12608 (org-show-todo-tree '(4)))
12609 ((member ans '(?T ?m))
12610 (call-interactively 'org-match-sparse-tree))
12611 ((member ans '(?p ?P))
12612 (setq kwd (org-icompleting-read "Property: "
12613 (mapcar 'list (org-buffer-property-keys))))
12614 (setq value (org-icompleting-read "Value: "
12615 (mapcar 'list (org-property-values kwd))))
12616 (unless (string-match "\\`{.*}\\'" value)
12617 (setq value (concat "\"" value "\"")))
12618 (org-match-sparse-tree arg (concat kwd "=" value)))
12619 ((member ans '(?r ?R ?/))
12620 (call-interactively 'org-occur))
12621 (t (error "No such sparse tree command \"%c\"" ans)))))
12623 (defvar org-occur-highlights nil
12624 "List of overlays used for occur matches.")
12625 (make-variable-buffer-local 'org-occur-highlights)
12626 (defvar org-occur-parameters nil
12627 "Parameters of the active org-occur calls.
12628 This is a list, each call to org-occur pushes as cons cell,
12629 containing the regular expression and the callback, onto the list.
12630 The list can contain several entries if `org-occur' has been called
12631 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12632 will only contain one set of parameters. When the highlights are
12633 removed (for example with `C-c C-c', or with the next edit (depending
12634 on `org-remove-highlights-with-change'), this variable is emptied
12635 as well.")
12636 (make-variable-buffer-local 'org-occur-parameters)
12638 (defun org-occur (regexp &optional keep-previous callback)
12639 "Make a compact tree which shows all matches of REGEXP.
12640 The tree will show the lines where the regexp matches, and all higher
12641 headlines above the match. It will also show the heading after the match,
12642 to make sure editing the matching entry is easy.
12643 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12644 call to `org-occur' will be kept, to allow stacking of calls to this
12645 command.
12646 If CALLBACK is non-nil, it is a function which is called to confirm
12647 that the match should indeed be shown."
12648 (interactive "sRegexp: \nP")
12649 (when (equal regexp "")
12650 (error "Regexp cannot be empty"))
12651 (unless keep-previous
12652 (org-remove-occur-highlights nil nil t))
12653 (push (cons regexp callback) org-occur-parameters)
12654 (let ((cnt 0))
12655 (save-excursion
12656 (goto-char (point-min))
12657 (if (or (not keep-previous) ; do not want to keep
12658 (not org-occur-highlights)) ; no previous matches
12659 ;; hide everything
12660 (org-overview))
12661 (while (re-search-forward regexp nil t)
12662 (when (or (not callback)
12663 (save-match-data (funcall callback)))
12664 (setq cnt (1+ cnt))
12665 (when org-highlight-sparse-tree-matches
12666 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12667 (org-show-context 'occur-tree))))
12668 (when org-remove-highlights-with-change
12669 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12670 nil 'local))
12671 (unless org-sparse-tree-open-archived-trees
12672 (org-hide-archived-subtrees (point-min) (point-max)))
12673 (run-hooks 'org-occur-hook)
12674 (if (org-called-interactively-p 'interactive)
12675 (message "%d match(es) for regexp %s" cnt regexp))
12676 cnt))
12678 (defun org-occur-next-match (&optional n reset)
12679 "Function for `next-error-function' to find sparse tree matches.
12680 N is the number of matches to move, when negative move backwards.
12681 RESET is entirely ignored - this function always goes back to the
12682 starting point when no match is found."
12683 (let* ((limit (if (< n 0) (point-min) (point-max)))
12684 (search-func (if (< n 0)
12685 'previous-single-char-property-change
12686 'next-single-char-property-change))
12687 (n (abs n))
12688 (pos (point))
12690 (catch 'exit
12691 (while (setq p1 (funcall search-func (point) 'org-type))
12692 (when (equal p1 limit)
12693 (goto-char pos)
12694 (error "No more matches"))
12695 (when (equal (get-char-property p1 'org-type) 'org-occur)
12696 (setq n (1- n))
12697 (when (= n 0)
12698 (goto-char p1)
12699 (throw 'exit (point))))
12700 (goto-char p1))
12701 (goto-char p1)
12702 (error "No more matches"))))
12704 (defun org-show-context (&optional key)
12705 "Make sure point and context are visible.
12706 How much context is shown depends upon the variables
12707 `org-show-hierarchy-above', `org-show-following-heading',
12708 `org-show-entry-below' and `org-show-siblings'."
12709 (let ((heading-p (org-at-heading-p t))
12710 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12711 (following-p (org-get-alist-option org-show-following-heading key))
12712 (entry-p (org-get-alist-option org-show-entry-below key))
12713 (siblings-p (org-get-alist-option org-show-siblings key)))
12714 (catch 'exit
12715 ;; Show heading or entry text
12716 (if (and heading-p (not entry-p))
12717 (org-flag-heading nil) ; only show the heading
12718 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12719 (org-show-hidden-entry))) ; show entire entry
12720 (when following-p
12721 ;; Show next sibling, or heading below text
12722 (save-excursion
12723 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12724 (org-flag-heading nil))))
12725 (when siblings-p (org-show-siblings))
12726 (when hierarchy-p
12727 ;; show all higher headings, possibly with siblings
12728 (save-excursion
12729 (while (and (condition-case nil
12730 (progn (org-up-heading-all 1) t)
12731 (error nil))
12732 (not (bobp)))
12733 (org-flag-heading nil)
12734 (when siblings-p (org-show-siblings))))))))
12736 (defvar org-reveal-start-hook nil
12737 "Hook run before revealing a location.")
12739 (defun org-reveal (&optional siblings)
12740 "Show current entry, hierarchy above it, and the following headline.
12741 This can be used to show a consistent set of context around locations
12742 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12743 not t for the search context.
12745 With optional argument SIBLINGS, on each level of the hierarchy all
12746 siblings are shown. This repairs the tree structure to what it would
12747 look like when opened with hierarchical calls to `org-cycle'.
12748 With double optional argument \\[universal-argument] \\[universal-argument], \
12749 go to the parent and show the
12750 entire tree."
12751 (interactive "P")
12752 (run-hooks 'org-reveal-start-hook)
12753 (let ((org-show-hierarchy-above t)
12754 (org-show-following-heading t)
12755 (org-show-siblings (if siblings t org-show-siblings)))
12756 (org-show-context nil))
12757 (when (equal siblings '(16))
12758 (save-excursion
12759 (when (org-up-heading-safe)
12760 (org-show-subtree)
12761 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12763 (defun org-highlight-new-match (beg end)
12764 "Highlight from BEG to END and mark the highlight is an occur headline."
12765 (let ((ov (make-overlay beg end)))
12766 (overlay-put ov 'face 'secondary-selection)
12767 (overlay-put ov 'org-type 'org-occur)
12768 (push ov org-occur-highlights)))
12770 (defun org-remove-occur-highlights (&optional beg end noremove)
12771 "Remove the occur highlights from the buffer.
12772 BEG and END are ignored. If NOREMOVE is nil, remove this function
12773 from the `before-change-functions' in the current buffer."
12774 (interactive)
12775 (unless org-inhibit-highlight-removal
12776 (mapc 'delete-overlay org-occur-highlights)
12777 (setq org-occur-highlights nil)
12778 (setq org-occur-parameters nil)
12779 (unless noremove
12780 (remove-hook 'before-change-functions
12781 'org-remove-occur-highlights 'local))))
12783 ;;;; Priorities
12785 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12786 "Regular expression matching the priority indicator.")
12788 (defvar org-remove-priority-next-time nil)
12790 (defun org-priority-up ()
12791 "Increase the priority of the current item."
12792 (interactive)
12793 (org-priority 'up))
12795 (defun org-priority-down ()
12796 "Decrease the priority of the current item."
12797 (interactive)
12798 (org-priority 'down))
12800 (defun org-priority (&optional action)
12801 "Change the priority of an item by ARG.
12802 ACTION can be `set', `up', `down', or a character."
12803 (interactive)
12804 (unless org-enable-priority-commands
12805 (error "Priority commands are disabled"))
12806 (setq action (or action 'set))
12807 (let (current new news have remove)
12808 (save-excursion
12809 (org-back-to-heading t)
12810 (if (looking-at org-priority-regexp)
12811 (setq current (string-to-char (match-string 2))
12812 have t))
12813 (cond
12814 ((eq action 'remove)
12815 (setq remove t new ?\ ))
12816 ((or (eq action 'set)
12817 (if (featurep 'xemacs) (characterp action) (integerp action)))
12818 (if (not (eq action 'set))
12819 (setq new action)
12820 (message "Priority %c-%c, SPC to remove: "
12821 org-highest-priority org-lowest-priority)
12822 (save-match-data
12823 (setq new (read-char-exclusive))))
12824 (if (and (= (upcase org-highest-priority) org-highest-priority)
12825 (= (upcase org-lowest-priority) org-lowest-priority))
12826 (setq new (upcase new)))
12827 (cond ((equal new ?\ ) (setq remove t))
12828 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12829 (error "Priority must be between `%c' and `%c'"
12830 org-highest-priority org-lowest-priority))))
12831 ((eq action 'up)
12832 (setq new (if have
12833 (1- current) ; normal cycling
12834 ;; last priority was empty
12835 (if (eq last-command this-command)
12836 org-lowest-priority ; wrap around empty to lowest
12837 ;; default
12838 (if org-priority-start-cycle-with-default
12839 org-default-priority
12840 (1- org-default-priority))))))
12841 ((eq action 'down)
12842 (setq new (if have
12843 (1+ current) ; normal cycling
12844 ;; last priority was empty
12845 (if (eq last-command this-command)
12846 org-highest-priority ; wrap around empty to highest
12847 ;; default
12848 (if org-priority-start-cycle-with-default
12849 org-default-priority
12850 (1+ org-default-priority))))))
12851 (t (error "Invalid action")))
12852 (if (or (< (upcase new) org-highest-priority)
12853 (> (upcase new) org-lowest-priority))
12854 (if (and (memq action '(up down))
12855 (not have) (not (eq last-command this-command)))
12856 ;; `new' is from default priority
12857 (error
12858 "The default can not be set, see `org-default-priority' why")
12859 ;; normal cycling: `new' is beyond highest/lowest priority
12860 ;; and is wrapped around to the empty priority
12861 (setq remove t)))
12862 (setq news (format "%c" new))
12863 (if have
12864 (if remove
12865 (replace-match "" t t nil 1)
12866 (replace-match news t t nil 2))
12867 (if remove
12868 (error "No priority cookie found in line")
12869 (let ((case-fold-search nil))
12870 (looking-at org-todo-line-regexp))
12871 (if (match-end 2)
12872 (progn
12873 (goto-char (match-end 2))
12874 (insert " [#" news "]"))
12875 (goto-char (match-beginning 3))
12876 (insert "[#" news "] "))))
12877 (org-preserve-lc (org-set-tags nil 'align)))
12878 (if remove
12879 (message "Priority removed")
12880 (message "Priority of current item set to %s" news))))
12882 (defun org-get-priority (s)
12883 "Find priority cookie and return priority."
12884 (if (functionp org-get-priority-function)
12885 (funcall org-get-priority-function)
12886 (save-match-data
12887 (if (not (string-match org-priority-regexp s))
12888 (* 1000 (- org-lowest-priority org-default-priority))
12889 (* 1000 (- org-lowest-priority
12890 (string-to-char (match-string 2 s))))))))
12892 ;;;; Tags
12894 (defvar org-agenda-archives-mode)
12895 (defvar org-map-continue-from nil
12896 "Position from where mapping should continue.
12897 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12899 (defvar org-scanner-tags nil
12900 "The current tag list while the tags scanner is running.")
12901 (defvar org-trust-scanner-tags nil
12902 "Should `org-get-tags-at' use the tags for the scanner.
12903 This is for internal dynamical scoping only.
12904 When this is non-nil, the function `org-get-tags-at' will return the value
12905 of `org-scanner-tags' instead of building the list by itself. This
12906 can lead to large speed-ups when the tags scanner is used in a file with
12907 many entries, and when the list of tags is retrieved, for example to
12908 obtain a list of properties. Building the tags list for each entry in such
12909 a file becomes an N^2 operation - but with this variable set, it scales
12910 as N.")
12912 (defun org-scan-tags (action matcher todo-only &optional start-level)
12913 "Scan headline tags with inheritance and produce output ACTION.
12915 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12916 or `agenda' to produce an entry list for an agenda view. It can also be
12917 a Lisp form or a function that should be called at each matched headline, in
12918 this case the return value is a list of all return values from these calls.
12920 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12921 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12922 only lines with a not-done TODO keyword are included in the output.
12923 This should be the same variable that was scoped into
12924 and set by `org-make-tags-matcher' when it constructed MATCHER.
12926 START-LEVEL can be a string with asterisks, reducing the scope to
12927 headlines matching this string."
12928 (require 'org-agenda)
12929 (let* ((re (concat "^"
12930 (if start-level
12931 ;; Get the correct level to match
12932 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12933 org-outline-regexp)
12934 " *\\(\\<\\("
12935 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12936 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12937 (props (list 'face 'default
12938 'done-face 'org-agenda-done
12939 'undone-face 'default
12940 'mouse-face 'highlight
12941 'org-not-done-regexp org-not-done-regexp
12942 'org-todo-regexp org-todo-regexp
12943 'org-complex-heading-regexp org-complex-heading-regexp
12944 'help-echo
12945 (format "mouse-2 or RET jump to org file %s"
12946 (abbreviate-file-name
12947 (or (buffer-file-name (buffer-base-buffer))
12948 (buffer-name (buffer-base-buffer)))))))
12949 (case-fold-search nil)
12950 (org-map-continue-from nil)
12951 lspos tags tags-list
12952 (tags-alist (list (cons 0 org-file-tags)))
12953 (llast 0) rtn rtn1 level category i txt
12954 todo marker entry priority)
12955 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12956 (setq action (list 'lambda nil action)))
12957 (save-excursion
12958 (goto-char (point-min))
12959 (when (eq action 'sparse-tree)
12960 (org-overview)
12961 (org-remove-occur-highlights))
12962 (while (re-search-forward re nil t)
12963 (setq org-map-continue-from nil)
12964 (catch :skip
12965 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12966 tags (if (match-end 4) (org-match-string-no-properties 4)))
12967 (goto-char (setq lspos (match-beginning 0)))
12968 (setq level (org-reduced-level (funcall outline-level))
12969 category (org-get-category))
12970 (setq i llast llast level)
12971 ;; remove tag lists from same and sublevels
12972 (while (>= i level)
12973 (when (setq entry (assoc i tags-alist))
12974 (setq tags-alist (delete entry tags-alist)))
12975 (setq i (1- i)))
12976 ;; add the next tags
12977 (when tags
12978 (setq tags (org-split-string tags ":")
12979 tags-alist
12980 (cons (cons level tags) tags-alist)))
12981 ;; compile tags for current headline
12982 (setq tags-list
12983 (if org-use-tag-inheritance
12984 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12985 tags)
12986 org-scanner-tags tags-list)
12987 (when org-use-tag-inheritance
12988 (setcdr (car tags-alist)
12989 (mapcar (lambda (x)
12990 (setq x (copy-sequence x))
12991 (org-add-prop-inherited x))
12992 (cdar tags-alist))))
12993 (when (and tags org-use-tag-inheritance
12994 (or (not (eq t org-use-tag-inheritance))
12995 org-tags-exclude-from-inheritance))
12996 ;; selective inheritance, remove uninherited ones
12997 (setcdr (car tags-alist)
12998 (org-remove-uninherited-tags (cdar tags-alist))))
12999 (when (and
13001 ;; eval matcher only when the todo condition is OK
13002 (and (or (not todo-only) (member todo org-not-done-keywords))
13003 (let ((case-fold-search t) (org-trust-scanner-tags t))
13004 (eval matcher)))
13006 ;; Call the skipper, but return t if it does not skip,
13007 ;; so that the `and' form continues evaluating
13008 (progn
13009 (unless (eq action 'sparse-tree) (org-agenda-skip))
13012 ;; Check if timestamps are deselecting this entry
13013 (or (not todo-only)
13014 (and (member todo org-not-done-keywords)
13015 (or (not org-agenda-tags-todo-honor-ignore-options)
13016 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13018 ;; Extra check for the archive tag
13019 ;; FIXME: Does the skipper already do this????
13021 (not (member org-archive-tag tags-list))
13022 ;; we have an archive tag, should we use this anyway?
13023 (or (not org-agenda-skip-archived-trees)
13024 (and (eq action 'agenda) org-agenda-archives-mode))))
13026 ;; select this headline
13028 (cond
13029 ((eq action 'sparse-tree)
13030 (and org-highlight-sparse-tree-matches
13031 (org-get-heading) (match-end 0)
13032 (org-highlight-new-match
13033 (match-beginning 1) (match-end 1)))
13034 (org-show-context 'tags-tree))
13035 ((eq action 'agenda)
13036 (setq txt (org-agenda-format-item
13038 (concat
13039 (if (eq org-tags-match-list-sublevels 'indented)
13040 (make-string (1- level) ?.) "")
13041 (org-get-heading))
13042 category
13043 tags-list)
13044 priority (org-get-priority txt))
13045 (goto-char lspos)
13046 (setq marker (org-agenda-new-marker))
13047 (org-add-props txt props
13048 'org-marker marker 'org-hd-marker marker 'org-category category
13049 'todo-state todo
13050 'priority priority 'type "tagsmatch")
13051 (push txt rtn))
13052 ((functionp action)
13053 (setq org-map-continue-from nil)
13054 (save-excursion
13055 (setq rtn1 (funcall action))
13056 (push rtn1 rtn)))
13057 (t (error "Invalid action")))
13059 ;; if we are to skip sublevels, jump to end of subtree
13060 (unless org-tags-match-list-sublevels
13061 (org-end-of-subtree t)
13062 (backward-char 1))))
13063 ;; Get the correct position from where to continue
13064 (if org-map-continue-from
13065 (goto-char org-map-continue-from)
13066 (and (= (point) lspos) (end-of-line 1)))))
13067 (when (and (eq action 'sparse-tree)
13068 (not org-sparse-tree-open-archived-trees))
13069 (org-hide-archived-subtrees (point-min) (point-max)))
13070 (nreverse rtn)))
13072 (defun org-remove-uninherited-tags (tags)
13073 "Remove all tags that are not inherited from the list TAGS."
13074 (cond
13075 ((eq org-use-tag-inheritance t)
13076 (if org-tags-exclude-from-inheritance
13077 (org-delete-all org-tags-exclude-from-inheritance tags)
13078 tags))
13079 ((not org-use-tag-inheritance) nil)
13080 ((stringp org-use-tag-inheritance)
13081 (delq nil (mapcar
13082 (lambda (x)
13083 (if (and (string-match org-use-tag-inheritance x)
13084 (not (member x org-tags-exclude-from-inheritance)))
13085 x nil))
13086 tags)))
13087 ((listp org-use-tag-inheritance)
13088 (delq nil (mapcar
13089 (lambda (x)
13090 (if (member x org-use-tag-inheritance) x nil))
13091 tags)))))
13093 (defun org-match-sparse-tree (&optional todo-only match)
13094 "Create a sparse tree according to tags string MATCH.
13095 MATCH can contain positive and negative selection of tags, like
13096 \"+WORK+URGENT-WITHBOSS\".
13097 If optional argument TODO-ONLY is non-nil, only select lines that are
13098 also TODO lines."
13099 (interactive "P")
13100 (org-prepare-agenda-buffers (list (current-buffer)))
13101 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13103 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13105 (defvar org-cached-props nil)
13106 (defun org-cached-entry-get (pom property)
13107 (if (or (eq t org-use-property-inheritance)
13108 (and (stringp org-use-property-inheritance)
13109 (string-match org-use-property-inheritance property))
13110 (and (listp org-use-property-inheritance)
13111 (member property org-use-property-inheritance)))
13112 ;; Caching is not possible, check it directly
13113 (org-entry-get pom property 'inherit)
13114 ;; Get all properties, so that we can do complicated checks easily
13115 (cdr (assoc property (or org-cached-props
13116 (setq org-cached-props
13117 (org-entry-properties pom)))))))
13119 (defun org-global-tags-completion-table (&optional files)
13120 "Return the list of all tags in all agenda buffer/files.
13121 Optional FILES argument is a list of files to which can be used
13122 instead of the agenda files."
13123 (save-excursion
13124 (org-uniquify
13125 (delq nil
13126 (apply 'append
13127 (mapcar
13128 (lambda (file)
13129 (set-buffer (find-file-noselect file))
13130 (append (org-get-buffer-tags)
13131 (mapcar (lambda (x) (if (stringp (car-safe x))
13132 (list (car-safe x)) nil))
13133 org-tag-alist)))
13134 (if (and files (car files))
13135 files
13136 (org-agenda-files))))))))
13138 (defun org-make-tags-matcher (match)
13139 "Create the TAGS/TODO matcher form for the selection string MATCH.
13141 The variable `todo-only' is scoped dynamically into this function; it will be
13142 set to t if the matcher restricts matching to TODO entries,
13143 otherwise will not be touched.
13145 Returns a cons of the selection string MATCH and the constructed
13146 lisp form implementing the matcher. The matcher is to be
13147 evaluated at an Org entry, with point on the headline,
13148 and returns t if the entry matches the
13149 selection string MATCH. The returned lisp form references
13150 two variables with information about the entry, which must be
13151 bound around the form's evaluation: todo, the TODO keyword at the
13152 entry (or nil of none); and tags-list, the list of all tags at the
13153 entry including inherited ones. Additionally, the category
13154 of the entry (if any) must be specified as the text property
13155 'org-category on the headline.
13157 See also `org-scan-tags'.
13159 (declare (special todo-only))
13160 (unless (boundp 'todo-only)
13161 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13162 (unless match
13163 ;; Get a new match request, with completion
13164 (let ((org-last-tags-completion-table
13165 (org-global-tags-completion-table)))
13166 (setq match (org-completing-read-no-i
13167 "Match: " 'org-tags-completion-function nil nil nil
13168 'org-tags-history))))
13170 ;; Parse the string and create a lisp form
13171 (let ((match0 match)
13172 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13173 minus tag mm
13174 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13175 orterms term orlist re-p str-p level-p level-op time-p
13176 prop-p pn pv po gv rest)
13177 (if (string-match "/+" match)
13178 ;; match contains also a todo-matching request
13179 (progn
13180 (setq tagsmatch (substring match 0 (match-beginning 0))
13181 todomatch (substring match (match-end 0)))
13182 (if (string-match "^!" todomatch)
13183 (setq todo-only t todomatch (substring todomatch 1)))
13184 (if (string-match "^\\s-*$" todomatch)
13185 (setq todomatch nil)))
13186 ;; only matching tags
13187 (setq tagsmatch match todomatch nil))
13189 ;; Make the tags matcher
13190 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13191 (setq tagsmatcher t)
13192 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13193 (while (setq term (pop orterms))
13194 (while (and (equal (substring term -1) "\\") orterms)
13195 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13196 (while (string-match re term)
13197 (setq rest (substring term (match-end 0))
13198 minus (and (match-end 1)
13199 (equal (match-string 1 term) "-"))
13200 tag (save-match-data (replace-regexp-in-string
13201 "\\\\-" "-"
13202 (match-string 2 term)))
13203 re-p (equal (string-to-char tag) ?{)
13204 level-p (match-end 4)
13205 prop-p (match-end 5)
13206 mm (cond
13207 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13208 (level-p
13209 (setq level-op (org-op-to-function (match-string 3 term)))
13210 `(,level-op level ,(string-to-number
13211 (match-string 4 term))))
13212 (prop-p
13213 (setq pn (match-string 5 term)
13214 po (match-string 6 term)
13215 pv (match-string 7 term)
13216 re-p (equal (string-to-char pv) ?{)
13217 str-p (equal (string-to-char pv) ?\")
13218 time-p (save-match-data
13219 (string-match "^\"[[<].*[]>]\"$" pv))
13220 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13221 (if time-p (setq pv (org-matcher-time pv)))
13222 (setq po (org-op-to-function po (if time-p 'time str-p)))
13223 (cond
13224 ((equal pn "CATEGORY")
13225 (setq gv '(get-text-property (point) 'org-category)))
13226 ((equal pn "TODO")
13227 (setq gv 'todo))
13229 (setq gv `(org-cached-entry-get nil ,pn))))
13230 (if re-p
13231 (if (eq po 'org<>)
13232 `(not (string-match ,pv (or ,gv "")))
13233 `(string-match ,pv (or ,gv "")))
13234 (if str-p
13235 `(,po (or ,gv "") ,pv)
13236 `(,po (string-to-number (or ,gv ""))
13237 ,(string-to-number pv) ))))
13238 (t `(member ,tag tags-list)))
13239 mm (if minus (list 'not mm) mm)
13240 term rest)
13241 (push mm tagsmatcher))
13242 (push (if (> (length tagsmatcher) 1)
13243 (cons 'and tagsmatcher)
13244 (car tagsmatcher))
13245 orlist)
13246 (setq tagsmatcher nil))
13247 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13248 (setq tagsmatcher
13249 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13250 ;; Make the todo matcher
13251 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13252 (setq todomatcher t)
13253 (setq orterms (org-split-string todomatch "|") orlist nil)
13254 (while (setq term (pop orterms))
13255 (while (string-match re term)
13256 (setq minus (and (match-end 1)
13257 (equal (match-string 1 term) "-"))
13258 kwd (match-string 2 term)
13259 re-p (equal (string-to-char kwd) ?{)
13260 term (substring term (match-end 0))
13261 mm (if re-p
13262 `(string-match ,(substring kwd 1 -1) todo)
13263 (list 'equal 'todo kwd))
13264 mm (if minus (list 'not mm) mm))
13265 (push mm todomatcher))
13266 (push (if (> (length todomatcher) 1)
13267 (cons 'and todomatcher)
13268 (car todomatcher))
13269 orlist)
13270 (setq todomatcher nil))
13271 (setq todomatcher (if (> (length orlist) 1)
13272 (cons 'or orlist) (car orlist))))
13274 ;; Return the string and lisp forms of the matcher
13275 (setq matcher (if todomatcher
13276 (list 'and tagsmatcher todomatcher)
13277 tagsmatcher))
13278 (when todo-only
13279 (setq matcher (list 'and '(member todo org-not-done-keywords)
13280 matcher)))
13281 (cons match0 matcher)))
13283 (defun org-op-to-function (op &optional stringp)
13284 "Turn an operator into the appropriate function."
13285 (setq op
13286 (cond
13287 ((equal op "<" ) '(< string< org-time<))
13288 ((equal op ">" ) '(> org-string> org-time>))
13289 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13290 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13291 ((member op '("=" "==")) '(= string= org-time=))
13292 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13293 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13295 (defun org<> (a b) (not (= a b)))
13296 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13297 (defun org-string>= (a b) (not (string< a b)))
13298 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13299 (defun org-string<> (a b) (not (string= a b)))
13300 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13301 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13302 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13303 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13304 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13305 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13306 (defun org-2ft (s)
13307 "Convert S to a floating point time.
13308 If S is already a number, just return it. If it is a string, parse
13309 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13310 (cond
13311 ((numberp s) s)
13312 ((stringp s)
13313 (condition-case nil
13314 (float-time (apply 'encode-time (org-parse-time-string s)))
13315 (error 0.)))
13316 (t 0.)))
13318 (defun org-time-today ()
13319 "Time in seconds today at 0:00.
13320 Returns the float number of seconds since the beginning of the
13321 epoch to the beginning of today (00:00)."
13322 (float-time (apply 'encode-time
13323 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13325 (defun org-matcher-time (s)
13326 "Interpret a time comparison value."
13327 (save-match-data
13328 (cond
13329 ((string= s "<now>") (float-time))
13330 ((string= s "<today>") (org-time-today))
13331 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13332 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13333 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13334 (+ (org-time-today)
13335 (* (string-to-number (match-string 1 s))
13336 (cdr (assoc (match-string 2 s)
13337 '(("d" . 86400.0) ("w" . 604800.0)
13338 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13339 (t (org-2ft s)))))
13341 (defun org-match-any-p (re list)
13342 "Does re match any element of list?"
13343 (setq list (mapcar (lambda (x) (string-match re x)) list))
13344 (delq nil list))
13346 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13347 (defvar org-tags-overlay (make-overlay 1 1))
13348 (org-detach-overlay org-tags-overlay)
13350 (defun org-get-local-tags-at (&optional pos)
13351 "Get a list of tags defined in the current headline."
13352 (org-get-tags-at pos 'local))
13354 (defun org-get-local-tags ()
13355 "Get a list of tags defined in the current headline."
13356 (org-get-tags-at nil 'local))
13358 (defun org-get-tags-at (&optional pos local)
13359 "Get a list of all headline tags applicable at POS.
13360 POS defaults to point. If tags are inherited, the list contains
13361 the targets in the same sequence as the headlines appear, i.e.
13362 the tags of the current headline come last.
13363 When LOCAL is non-nil, only return tags from the current headline,
13364 ignore inherited ones."
13365 (interactive)
13366 (if (and org-trust-scanner-tags
13367 (or (not pos) (equal pos (point)))
13368 (not local))
13369 org-scanner-tags
13370 (let (tags ltags lastpos parent)
13371 (save-excursion
13372 (save-restriction
13373 (widen)
13374 (goto-char (or pos (point)))
13375 (save-match-data
13376 (catch 'done
13377 (condition-case nil
13378 (progn
13379 (org-back-to-heading t)
13380 (while (not (equal lastpos (point)))
13381 (setq lastpos (point))
13382 (when (looking-at
13383 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13384 (setq ltags (org-split-string
13385 (org-match-string-no-properties 1) ":"))
13386 (when parent
13387 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13388 (setq tags (append
13389 (if parent
13390 (org-remove-uninherited-tags ltags)
13391 ltags)
13392 tags)))
13393 (or org-use-tag-inheritance (throw 'done t))
13394 (if local (throw 'done t))
13395 (or (org-up-heading-safe) (error nil))
13396 (setq parent t)))
13397 (error nil)))))
13398 (if local
13399 tags
13400 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13402 (defun org-add-prop-inherited (s)
13403 (add-text-properties 0 (length s) '(inherited t) s)
13406 (defun org-toggle-tag (tag &optional onoff)
13407 "Toggle the tag TAG for the current line.
13408 If ONOFF is `on' or `off', don't toggle but set to this state."
13409 (let (res current)
13410 (save-excursion
13411 (org-back-to-heading t)
13412 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13413 (point-at-eol) t)
13414 (progn
13415 (setq current (match-string 1))
13416 (replace-match ""))
13417 (setq current ""))
13418 (setq current (nreverse (org-split-string current ":")))
13419 (cond
13420 ((eq onoff 'on)
13421 (setq res t)
13422 (or (member tag current) (push tag current)))
13423 ((eq onoff 'off)
13424 (or (not (member tag current)) (setq current (delete tag current))))
13425 (t (if (member tag current)
13426 (setq current (delete tag current))
13427 (setq res t)
13428 (push tag current))))
13429 (end-of-line 1)
13430 (if current
13431 (progn
13432 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13433 (org-set-tags nil t))
13434 (delete-horizontal-space))
13435 (run-hooks 'org-after-tags-change-hook))
13436 res))
13438 (defun org-align-tags-here (to-col)
13439 ;; Assumes that this is a headline
13440 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13441 (beginning-of-line 1)
13442 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13443 (< pos (match-beginning 2)))
13444 (progn
13445 (setq tags-l (- (match-end 2) (match-beginning 2)))
13446 (goto-char (match-beginning 1))
13447 (insert " ")
13448 (delete-region (point) (1+ (match-beginning 2)))
13449 (setq ncol (max (current-column)
13450 (1+ col)
13451 (if (> to-col 0)
13452 to-col
13453 (- (abs to-col) tags-l))))
13454 (setq p (point))
13455 (insert (make-string (- ncol (current-column)) ?\ ))
13456 (setq ncol (current-column))
13457 (when indent-tabs-mode (tabify p (point-at-eol)))
13458 (org-move-to-column (min ncol col) t))
13459 (goto-char pos))))
13461 (defun org-set-tags-command (&optional arg just-align)
13462 "Call the set-tags command for the current entry."
13463 (interactive "P")
13464 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13465 (org-set-tags arg just-align)
13466 (save-excursion
13467 (org-back-to-heading t)
13468 (org-set-tags arg just-align))))
13470 (defun org-set-tags-to (data)
13471 "Set the tags of the current entry to DATA, replacing the current tags.
13472 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13473 If DATA is nil or the empty string, any tags will be removed."
13474 (interactive "sTags: ")
13475 (setq data
13476 (cond
13477 ((eq data nil) "")
13478 ((equal data "") "")
13479 ((stringp data)
13480 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13481 ":"))
13482 ((listp data)
13483 (concat ":" (mapconcat 'identity data ":") ":"))
13484 (t nil)))
13485 (when data
13486 (save-excursion
13487 (org-back-to-heading t)
13488 (when (looking-at org-complex-heading-regexp)
13489 (if (match-end 5)
13490 (progn
13491 (goto-char (match-beginning 5))
13492 (insert data)
13493 (delete-region (point) (point-at-eol))
13494 (org-set-tags nil 'align))
13495 (goto-char (point-at-eol))
13496 (insert " " data)
13497 (org-set-tags nil 'align)))
13498 (beginning-of-line 1)
13499 (if (looking-at ".*?\\([ \t]+\\)$")
13500 (delete-region (match-beginning 1) (match-end 1))))))
13502 (defun org-align-all-tags ()
13503 "Align the tags i all headings."
13504 (interactive)
13505 (save-excursion
13506 (or (ignore-errors (org-back-to-heading t))
13507 (outline-next-heading))
13508 (if (org-at-heading-p)
13509 (org-set-tags t)
13510 (message "No headings"))))
13512 (defvar org-indent-indentation-per-level)
13513 (defun org-set-tags (&optional arg just-align)
13514 "Set the tags for the current headline.
13515 With prefix ARG, realign all tags in headings in the current buffer."
13516 (interactive "P")
13517 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13518 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13519 'region-start-level 'region))
13520 org-loop-over-headlines-in-active-region)
13521 (org-map-entries
13522 ;; We don't use ARG and JUST-ALIGN here these args are not
13523 ;; useful when looping over headlines
13524 `(org-set-tags)
13525 org-loop-over-headlines-in-active-region
13526 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13527 (let* ((re org-outline-regexp-bol)
13528 (current (unless arg (org-get-tags-string)))
13529 (col (current-column))
13530 (org-setting-tags t)
13531 table current-tags inherited-tags ; computed below when needed
13532 tags p0 c0 c1 rpl di tc level)
13533 (if arg
13534 (save-excursion
13535 (goto-char (point-min))
13536 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13537 (while (re-search-forward re nil t)
13538 (org-set-tags nil t)
13539 (end-of-line 1)))
13540 (message "All tags realigned to column %d" org-tags-column))
13541 (if just-align
13542 (setq tags current)
13543 ;; Get a new set of tags from the user
13544 (save-excursion
13545 (setq table (append org-tag-persistent-alist
13546 (or org-tag-alist (org-get-buffer-tags))
13547 (and
13548 org-complete-tags-always-offer-all-agenda-tags
13549 (org-global-tags-completion-table
13550 (org-agenda-files))))
13551 org-last-tags-completion-table table
13552 current-tags (org-split-string current ":")
13553 inherited-tags (nreverse
13554 (nthcdr (length current-tags)
13555 (nreverse (org-get-tags-at))))
13556 tags
13557 (if (or (eq t org-use-fast-tag-selection)
13558 (and org-use-fast-tag-selection
13559 (delq nil (mapcar 'cdr table))))
13560 (org-fast-tag-selection
13561 current-tags inherited-tags table
13562 (if org-fast-tag-selection-include-todo
13563 org-todo-key-alist))
13564 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13565 (org-trim
13566 (org-icompleting-read "Tags: "
13567 'org-tags-completion-function
13568 nil nil current 'org-tags-history))))))
13569 (while (string-match "[-+&]+" tags)
13570 ;; No boolean logic, just a list
13571 (setq tags (replace-match ":" t t tags))))
13573 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13575 (if org-tags-sort-function
13576 (setq tags (mapconcat 'identity
13577 (sort (org-split-string
13578 tags (org-re "[^[:alnum:]_@#%]+"))
13579 org-tags-sort-function) ":")))
13581 (if (string-match "\\`[\t ]*\\'" tags)
13582 (setq tags "")
13583 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13584 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13586 ;; Insert new tags at the correct column
13587 (beginning-of-line 1)
13588 (setq level (or (and (looking-at org-outline-regexp)
13589 (- (match-end 0) (point) 1))
13591 (cond
13592 ((and (equal current "") (equal tags "")))
13593 ((re-search-forward
13594 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13595 (point-at-eol) t)
13596 (if (equal tags "")
13597 (setq rpl "")
13598 (goto-char (match-beginning 0))
13599 (setq c0 (current-column)
13600 ;; compute offset for the case of org-indent-mode active
13601 di (if org-indent-mode
13602 (* (1- org-indent-indentation-per-level) (1- level))
13604 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13605 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13606 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13607 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13608 (replace-match rpl t t)
13609 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13610 tags)
13611 (t (error "Tags alignment failed")))
13612 (org-move-to-column col)
13613 (unless just-align
13614 (run-hooks 'org-after-tags-change-hook))))))
13616 (defun org-change-tag-in-region (beg end tag off)
13617 "Add or remove TAG for each entry in the region.
13618 This works in the agenda, and also in an org-mode buffer."
13619 (interactive
13620 (list (region-beginning) (region-end)
13621 (let ((org-last-tags-completion-table
13622 (if (derived-mode-p 'org-mode)
13623 (org-get-buffer-tags)
13624 (org-global-tags-completion-table))))
13625 (org-icompleting-read
13626 "Tag: " 'org-tags-completion-function nil nil nil
13627 'org-tags-history))
13628 (progn
13629 (message "[s]et or [r]emove? ")
13630 (equal (read-char-exclusive) ?r))))
13631 (if (fboundp 'deactivate-mark) (deactivate-mark))
13632 (let ((agendap (equal major-mode 'org-agenda-mode))
13633 l1 l2 m buf pos newhead (cnt 0))
13634 (goto-char end)
13635 (setq l2 (1- (org-current-line)))
13636 (goto-char beg)
13637 (setq l1 (org-current-line))
13638 (loop for l from l1 to l2 do
13639 (org-goto-line l)
13640 (setq m (get-text-property (point) 'org-hd-marker))
13641 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13642 (and agendap m))
13643 (setq buf (if agendap (marker-buffer m) (current-buffer))
13644 pos (if agendap m (point)))
13645 (with-current-buffer buf
13646 (save-excursion
13647 (save-restriction
13648 (goto-char pos)
13649 (setq cnt (1+ cnt))
13650 (org-toggle-tag tag (if off 'off 'on))
13651 (setq newhead (org-get-heading)))))
13652 (and agendap (org-agenda-change-all-lines newhead m))))
13653 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13655 (defun org-tags-completion-function (string predicate &optional flag)
13656 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13657 (confirm (lambda (x) (stringp (car x)))))
13658 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13659 (setq s1 (match-string 1 string)
13660 s2 (match-string 2 string))
13661 (setq s1 "" s2 string))
13662 (cond
13663 ((eq flag nil)
13664 ;; try completion
13665 (setq rtn (try-completion s2 ctable confirm))
13666 (if (stringp rtn)
13667 (setq rtn
13668 (concat s1 s2 (substring rtn (length s2))
13669 (if (and org-add-colon-after-tag-completion
13670 (assoc rtn ctable))
13671 ":" ""))))
13672 rtn)
13673 ((eq flag t)
13674 ;; all-completions
13675 (all-completions s2 ctable confirm)
13677 ((eq flag 'lambda)
13678 ;; exact match?
13679 (assoc s2 ctable)))
13682 (defun org-fast-tag-insert (kwd tags face &optional end)
13683 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13684 (insert (format "%-12s" (concat kwd ":"))
13685 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13686 (or end "")))
13688 (defun org-fast-tag-show-exit (flag)
13689 (save-excursion
13690 (org-goto-line 3)
13691 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13692 (replace-match ""))
13693 (when flag
13694 (end-of-line 1)
13695 (org-move-to-column (- (window-width) 19) t)
13696 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13698 (defun org-set-current-tags-overlay (current prefix)
13699 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13700 (if (featurep 'xemacs)
13701 (org-overlay-display org-tags-overlay (concat prefix s)
13702 'secondary-selection)
13703 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13704 (org-overlay-display org-tags-overlay (concat prefix s)))))
13706 (defvar org-last-tag-selection-key nil)
13707 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13708 "Fast tag selection with single keys.
13709 CURRENT is the current list of tags in the headline, INHERITED is the
13710 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13711 possibly with grouping information. TODO-TABLE is a similar table with
13712 TODO keywords, should these have keys assigned to them.
13713 If the keys are nil, a-z are automatically assigned.
13714 Returns the new tags string, or nil to not change the current settings."
13715 (let* ((fulltable (append table todo-table))
13716 (maxlen (apply 'max (mapcar
13717 (lambda (x)
13718 (if (stringp (car x)) (string-width (car x)) 0))
13719 fulltable)))
13720 (buf (current-buffer))
13721 (expert (eq org-fast-tag-selection-single-key 'expert))
13722 (buffer-tags nil)
13723 (fwidth (+ maxlen 3 1 3))
13724 (ncol (/ (- (window-width) 4) fwidth))
13725 (i-face 'org-done)
13726 (c-face 'org-todo)
13727 tg cnt e c char c1 c2 ntable tbl rtn
13728 ov-start ov-end ov-prefix
13729 (exit-after-next org-fast-tag-selection-single-key)
13730 (done-keywords org-done-keywords)
13731 groups ingroup)
13732 (save-excursion
13733 (beginning-of-line 1)
13734 (if (looking-at
13735 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13736 (setq ov-start (match-beginning 1)
13737 ov-end (match-end 1)
13738 ov-prefix "")
13739 (setq ov-start (1- (point-at-eol))
13740 ov-end (1+ ov-start))
13741 (skip-chars-forward "^\n\r")
13742 (setq ov-prefix
13743 (concat
13744 (buffer-substring (1- (point)) (point))
13745 (if (> (current-column) org-tags-column)
13747 (make-string (- org-tags-column (current-column)) ?\ ))))))
13748 (move-overlay org-tags-overlay ov-start ov-end)
13749 (save-window-excursion
13750 (if expert
13751 (set-buffer (get-buffer-create " *Org tags*"))
13752 (delete-other-windows)
13753 (split-window-vertically)
13754 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13755 (erase-buffer)
13756 (org-set-local 'org-done-keywords done-keywords)
13757 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13758 (org-fast-tag-insert "Current" current c-face "\n\n")
13759 (org-fast-tag-show-exit exit-after-next)
13760 (org-set-current-tags-overlay current ov-prefix)
13761 (setq tbl fulltable char ?a cnt 0)
13762 (while (setq e (pop tbl))
13763 (cond
13764 ((equal (car e) :startgroup)
13765 (push '() groups) (setq ingroup t)
13766 (when (not (= cnt 0))
13767 (setq cnt 0)
13768 (insert "\n"))
13769 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13770 ((equal (car e) :endgroup)
13771 (setq ingroup nil cnt 0)
13772 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13773 ((equal e '(:newline))
13774 (when (not (= cnt 0))
13775 (setq cnt 0)
13776 (insert "\n")
13777 (setq e (car tbl))
13778 (while (equal (car tbl) '(:newline))
13779 (insert "\n")
13780 (setq tbl (cdr tbl)))))
13782 (setq tg (copy-sequence (car e)) c2 nil)
13783 (if (cdr e)
13784 (setq c (cdr e))
13785 ;; automatically assign a character.
13786 (setq c1 (string-to-char
13787 (downcase (substring
13788 tg (if (= (string-to-char tg) ?@) 1 0)))))
13789 (if (or (rassoc c1 ntable) (rassoc c1 table))
13790 (while (or (rassoc char ntable) (rassoc char table))
13791 (setq char (1+ char)))
13792 (setq c2 c1))
13793 (setq c (or c2 char)))
13794 (if ingroup (push tg (car groups)))
13795 (setq tg (org-add-props tg nil 'face
13796 (cond
13797 ((not (assoc tg table))
13798 (org-get-todo-face tg))
13799 ((member tg current) c-face)
13800 ((member tg inherited) i-face)
13801 (t nil))))
13802 (if (and (= cnt 0) (not ingroup)) (insert " "))
13803 (insert "[" c "] " tg (make-string
13804 (- fwidth 4 (length tg)) ?\ ))
13805 (push (cons tg c) ntable)
13806 (when (= (setq cnt (1+ cnt)) ncol)
13807 (insert "\n")
13808 (if ingroup (insert " "))
13809 (setq cnt 0)))))
13810 (setq ntable (nreverse ntable))
13811 (insert "\n")
13812 (goto-char (point-min))
13813 (if (not expert) (org-fit-window-to-buffer))
13814 (setq rtn
13815 (catch 'exit
13816 (while t
13817 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13818 (if (not groups) "no " "")
13819 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13820 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13821 (setq org-last-tag-selection-key c)
13822 (cond
13823 ((= c ?\r) (throw 'exit t))
13824 ((= c ?!)
13825 (setq groups (not groups))
13826 (goto-char (point-min))
13827 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13828 ((= c ?\C-c)
13829 (if (not expert)
13830 (org-fast-tag-show-exit
13831 (setq exit-after-next (not exit-after-next)))
13832 (setq expert nil)
13833 (delete-other-windows)
13834 (set-window-buffer (split-window-vertically) " *Org tags*")
13835 (org-switch-to-buffer-other-window " *Org tags*")
13836 (org-fit-window-to-buffer)))
13837 ((or (= c ?\C-g)
13838 (and (= c ?q) (not (rassoc c ntable))))
13839 (org-detach-overlay org-tags-overlay)
13840 (setq quit-flag t))
13841 ((= c ?\ )
13842 (setq current nil)
13843 (if exit-after-next (setq exit-after-next 'now)))
13844 ((= c ?\t)
13845 (condition-case nil
13846 (setq tg (org-icompleting-read
13847 "Tag: "
13848 (or buffer-tags
13849 (with-current-buffer buf
13850 (org-get-buffer-tags)))))
13851 (quit (setq tg "")))
13852 (when (string-match "\\S-" tg)
13853 (add-to-list 'buffer-tags (list tg))
13854 (if (member tg current)
13855 (setq current (delete tg current))
13856 (push tg current)))
13857 (if exit-after-next (setq exit-after-next 'now)))
13858 ((setq e (rassoc c todo-table) tg (car e))
13859 (with-current-buffer buf
13860 (save-excursion (org-todo tg)))
13861 (if exit-after-next (setq exit-after-next 'now)))
13862 ((setq e (rassoc c ntable) tg (car e))
13863 (if (member tg current)
13864 (setq current (delete tg current))
13865 (loop for g in groups do
13866 (if (member tg g)
13867 (mapc (lambda (x)
13868 (setq current (delete x current)))
13869 g)))
13870 (push tg current))
13871 (if exit-after-next (setq exit-after-next 'now))))
13873 ;; Create a sorted list
13874 (setq current
13875 (sort current
13876 (lambda (a b)
13877 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13878 (if (eq exit-after-next 'now) (throw 'exit t))
13879 (goto-char (point-min))
13880 (beginning-of-line 2)
13881 (delete-region (point) (point-at-eol))
13882 (org-fast-tag-insert "Current" current c-face)
13883 (org-set-current-tags-overlay current ov-prefix)
13884 (while (re-search-forward
13885 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13886 (setq tg (match-string 1))
13887 (add-text-properties
13888 (match-beginning 1) (match-end 1)
13889 (list 'face
13890 (cond
13891 ((member tg current) c-face)
13892 ((member tg inherited) i-face)
13893 (t (get-text-property (match-beginning 1) 'face))))))
13894 (goto-char (point-min)))))
13895 (org-detach-overlay org-tags-overlay)
13896 (if rtn
13897 (mapconcat 'identity current ":")
13898 nil))))
13900 (defun org-get-tags-string ()
13901 "Get the TAGS string in the current headline."
13902 (unless (org-at-heading-p t)
13903 (error "Not on a heading"))
13904 (save-excursion
13905 (beginning-of-line 1)
13906 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13907 (org-match-string-no-properties 1)
13908 "")))
13910 (defun org-get-tags ()
13911 "Get the list of tags specified in the current headline."
13912 (org-split-string (org-get-tags-string) ":"))
13914 (defun org-get-buffer-tags ()
13915 "Get a table of all tags used in the buffer, for completion."
13916 (let (tags)
13917 (save-excursion
13918 (goto-char (point-min))
13919 (while (re-search-forward
13920 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13921 (when (equal (char-after (point-at-bol 0)) ?*)
13922 (mapc (lambda (x) (add-to-list 'tags x))
13923 (org-split-string (org-match-string-no-properties 1) ":")))))
13924 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13925 (mapcar 'list tags)))
13927 ;;;; The mapping API
13929 ;;;###autoload
13930 (defun org-map-entries (func &optional match scope &rest skip)
13931 "Call FUNC at each headline selected by MATCH in SCOPE.
13933 FUNC is a function or a lisp form. The function will be called without
13934 arguments, with the cursor positioned at the beginning of the headline.
13935 The return values of all calls to the function will be collected and
13936 returned as a list.
13938 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13939 does not need to preserve point. After evaluation, the cursor will be
13940 moved to the end of the line (presumably of the headline of the
13941 processed entry) and search continues from there. Under some
13942 circumstances, this may not produce the wanted results. For example,
13943 if you have removed (e.g. archived) the current (sub)tree it could
13944 mean that the next entry will be skipped entirely. In such cases, you
13945 can specify the position from where search should continue by making
13946 FUNC set the variable `org-map-continue-from' to the desired buffer
13947 position.
13949 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13950 Only headlines that are matched by this query will be considered during
13951 the iteration. When MATCH is nil or t, all headlines will be
13952 visited by the iteration.
13954 SCOPE determines the scope of this command. It can be any of:
13956 nil The current buffer, respecting the restriction if any
13957 tree The subtree started with the entry at point
13958 region The entries within the active region, if any
13959 region-start-level
13960 The entries within the active region, but only those at
13961 the same level than the first one.
13962 file The current buffer, without restriction
13963 file-with-archives
13964 The current buffer, and any archives associated with it
13965 agenda All agenda files
13966 agenda-with-archives
13967 All agenda files with any archive files associated with them
13968 \(file1 file2 ...)
13969 If this is a list, all files in the list will be scanned
13971 The remaining args are treated as settings for the skipping facilities of
13972 the scanner. The following items can be given here:
13974 archive skip trees with the archive tag.
13975 comment skip trees with the COMMENT keyword
13976 function or Emacs Lisp form:
13977 will be used as value for `org-agenda-skip-function', so whenever
13978 the function returns t, FUNC will not be called for that
13979 entry and search will continue from the point where the
13980 function leaves it.
13982 If your function needs to retrieve the tags including inherited tags
13983 at the *current* entry, you can use the value of the variable
13984 `org-scanner-tags' which will be much faster than getting the value
13985 with `org-get-tags-at'. If your function gets properties with
13986 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13987 to t around the call to `org-entry-properties' to get the same speedup.
13988 Note that if your function moves around to retrieve tags and properties at
13989 a *different* entry, you cannot use these techniques."
13990 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13991 (not (org-region-active-p)))
13992 (let* ((org-agenda-archives-mode nil) ; just to make sure
13993 (org-agenda-skip-archived-trees (memq 'archive skip))
13994 (org-agenda-skip-comment-trees (memq 'comment skip))
13995 (org-agenda-skip-function
13996 (car (org-delete-all '(comment archive) skip)))
13997 (org-tags-match-list-sublevels t)
13998 (start-level (eq scope 'region-start-level))
13999 matcher file res
14000 org-todo-keywords-for-agenda
14001 org-done-keywords-for-agenda
14002 org-todo-keyword-alist-for-agenda
14003 org-drawers-for-agenda
14004 org-tag-alist-for-agenda
14005 todo-only)
14007 (cond
14008 ((eq match t) (setq matcher t))
14009 ((eq match nil) (setq matcher t))
14010 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14012 (save-excursion
14013 (save-restriction
14014 (cond ((eq scope 'tree)
14015 (org-back-to-heading t)
14016 (org-narrow-to-subtree)
14017 (setq scope nil))
14018 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14019 (org-region-active-p))
14020 ;; If needed, set start-level to a string like "2"
14021 (when start-level
14022 (save-excursion
14023 (goto-char (region-beginning))
14024 (unless (org-at-heading-p) (outline-next-heading))
14025 (setq start-level (org-current-level))))
14026 (narrow-to-region (region-beginning)
14027 (save-excursion
14028 (goto-char (region-end))
14029 (unless (and (bolp) (org-at-heading-p))
14030 (outline-next-heading))
14031 (point)))
14032 (setq scope nil)))
14034 (if (not scope)
14035 (progn
14036 (org-prepare-agenda-buffers
14037 (list (buffer-file-name (current-buffer))))
14038 (setq res (org-scan-tags func matcher todo-only start-level)))
14039 ;; Get the right scope
14040 (cond
14041 ((and scope (listp scope) (symbolp (car scope)))
14042 (setq scope (eval scope)))
14043 ((eq scope 'agenda)
14044 (setq scope (org-agenda-files t)))
14045 ((eq scope 'agenda-with-archives)
14046 (setq scope (org-agenda-files t))
14047 (setq scope (org-add-archive-files scope)))
14048 ((eq scope 'file)
14049 (setq scope (list (buffer-file-name))))
14050 ((eq scope 'file-with-archives)
14051 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14052 (org-prepare-agenda-buffers scope)
14053 (while (setq file (pop scope))
14054 (with-current-buffer (org-find-base-buffer-visiting file)
14055 (save-excursion
14056 (save-restriction
14057 (widen)
14058 (goto-char (point-min))
14059 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14060 res)))
14062 ;;;; Properties
14064 ;;; Setting and retrieving properties
14066 (defconst org-special-properties
14067 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14068 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14069 "The special properties valid in Org-mode.
14071 These are properties that are not defined in the property drawer,
14072 but in some other way.")
14074 (defconst org-default-properties
14075 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14076 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14077 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14078 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14079 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14080 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14081 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14082 "Some properties that are used by Org-mode for various purposes.
14083 Being in this list makes sure that they are offered for completion.")
14085 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14086 "Regular expression matching the first line of a property drawer.")
14088 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14089 "Regular expression matching the last line of a property drawer.")
14091 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14092 "Regular expression matching the first line of a property drawer.")
14094 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14095 "Regular expression matching the first line of a property drawer.")
14097 (defconst org-property-drawer-re
14098 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14099 org-property-end-re "\\)\n?")
14100 "Matches an entire property drawer.")
14102 (defconst org-clock-drawer-re
14103 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14104 org-property-end-re "\\)\n?")
14105 "Matches an entire clock drawer.")
14107 (defsubst org-re-property (property)
14108 "Return a regexp matching a PROPERTY line.
14109 Match group 1 will be set to the value."
14110 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14112 (defsubst org-re-property-keyword (property)
14113 "Return a regexp matching a PROPERTY line, possibly with no
14114 value for the property."
14115 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14117 (defun org-property-action ()
14118 "Do an action on properties."
14119 (interactive)
14120 (let (c)
14121 (org-at-property-p)
14122 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14123 (setq c (read-char-exclusive))
14124 (cond
14125 ((equal c ?s)
14126 (call-interactively 'org-set-property))
14127 ((equal c ?d)
14128 (call-interactively 'org-delete-property))
14129 ((equal c ?D)
14130 (call-interactively 'org-delete-property-globally))
14131 ((equal c ?c)
14132 (call-interactively 'org-compute-property-at-point))
14133 (t (error "No such property action %c" c)))))
14135 (defun org-inc-effort ()
14136 "Increment the value of the effort property in the current entry."
14137 (interactive)
14138 (org-set-effort nil t))
14140 (defun org-set-effort (&optional value increment)
14141 "Set the effort property of the current entry.
14142 With numerical prefix arg, use the nth allowed value, 0 stands for the
14143 10th allowed value.
14145 When INCREMENT is non-nil, set the property to the next allowed value."
14146 (interactive "P")
14147 (if (equal value 0) (setq value 10))
14148 (let* ((completion-ignore-case t)
14149 (prop org-effort-property)
14150 (cur (org-entry-get nil prop))
14151 (allowed (org-property-get-allowed-values nil prop 'table))
14152 (existing (mapcar 'list (org-property-values prop)))
14154 (val (cond
14155 ((stringp value) value)
14156 ((and allowed (integerp value))
14157 (or (car (nth (1- value) allowed))
14158 (car (org-last allowed))))
14159 ((and allowed increment)
14160 (or (caadr (member (list cur) allowed))
14161 (error "Allowed effort values are not set")))
14162 (allowed
14163 (message "Select 1-9,0, [RET%s]: %s"
14164 (if cur (concat "=" cur) "")
14165 (mapconcat 'car allowed " "))
14166 (setq rpl (read-char-exclusive))
14167 (if (equal rpl ?\r)
14169 (setq rpl (- rpl ?0))
14170 (if (equal rpl 0) (setq rpl 10))
14171 (if (and (> rpl 0) (<= rpl (length allowed)))
14172 (car (nth (1- rpl) allowed))
14173 (org-completing-read "Effort: " allowed nil))))
14175 (let (org-completion-use-ido org-completion-use-iswitchb)
14176 (org-completing-read
14177 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14178 (concat "[" cur "]") "")
14179 ": ")
14180 existing nil nil "" nil cur))))))
14181 (unless (equal (org-entry-get nil prop) val)
14182 (org-entry-put nil prop val))
14183 (message "%s is now %s" prop val)))
14185 (defun org-at-property-p ()
14186 "Is cursor inside a property drawer?"
14187 (save-excursion
14188 (beginning-of-line 1)
14189 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14190 (save-match-data ;; Used by calling procedures
14191 (let ((p (point))
14192 (range (unless (org-before-first-heading-p)
14193 (org-get-property-block))))
14194 (and range (<= (car range) p) (< p (cdr range))))))))
14196 (defun org-get-property-block (&optional beg end force)
14197 "Return the (beg . end) range of the body of the property drawer.
14198 BEG and END can be beginning and end of subtree, if not given
14199 they will be found.
14200 If the drawer does not exist and FORCE is non-nil, create the drawer."
14201 (catch 'exit
14202 (save-excursion
14203 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14204 (end (or end (progn (outline-next-heading) (point)))))
14205 (goto-char beg)
14206 (if (re-search-forward org-property-start-re end t)
14207 (setq beg (1+ (match-end 0)))
14208 (if force
14209 (save-excursion
14210 (org-insert-property-drawer)
14211 (setq end (progn (outline-next-heading) (point))))
14212 (throw 'exit nil))
14213 (goto-char beg)
14214 (if (re-search-forward org-property-start-re end t)
14215 (setq beg (1+ (match-end 0)))))
14216 (if (re-search-forward org-property-end-re end t)
14217 (setq end (match-beginning 0))
14218 (or force (throw 'exit nil))
14219 (goto-char beg)
14220 (setq end beg)
14221 (org-indent-line)
14222 (insert ":END:\n"))
14223 (cons beg end)))))
14225 (defun org-entry-properties (&optional pom which specific)
14226 "Get all properties of the entry at point-or-marker POM.
14227 This includes the TODO keyword, the tags, time strings for deadline,
14228 scheduled, and clocking, and any additional properties defined in the
14229 entry. The return value is an alist, keys may occur multiple times
14230 if the property key was used several times.
14231 POM may also be nil, in which case the current entry is used.
14232 If WHICH is nil or `all', get all properties. If WHICH is
14233 `special' or `standard', only get that subclass. If WHICH
14234 is a string only get exactly this property. SPECIFIC can be a string, the
14235 specific property we are interested in. Specifying it can speed
14236 things up because then unnecessary parsing is avoided."
14237 (setq which (or which 'all))
14238 (org-with-point-at pom
14239 (let ((clockstr (substring org-clock-string 0 -1))
14240 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14241 (case-fold-search nil)
14242 beg end range props sum-props key key1 value string clocksum)
14243 (save-excursion
14244 (when (condition-case nil
14245 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14246 (error nil))
14247 (setq beg (point))
14248 (setq sum-props (get-text-property (point) 'org-summaries))
14249 (setq clocksum (get-text-property (point) :org-clock-minutes))
14250 (outline-next-heading)
14251 (setq end (point))
14252 (when (memq which '(all special))
14253 ;; Get the special properties, like TODO and tags
14254 (goto-char beg)
14255 (when (and (or (not specific) (string= specific "TODO"))
14256 (looking-at org-todo-line-regexp) (match-end 2))
14257 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14258 (when (and (or (not specific) (string= specific "PRIORITY"))
14259 (looking-at org-priority-regexp))
14260 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14261 (when (or (not specific) (string= specific "FILE"))
14262 (push (cons "FILE" buffer-file-name) props))
14263 (when (and (or (not specific) (string= specific "TAGS"))
14264 (setq value (org-get-tags-string))
14265 (string-match "\\S-" value))
14266 (push (cons "TAGS" value) props))
14267 (when (and (or (not specific) (string= specific "ALLTAGS"))
14268 (setq value (org-get-tags-at)))
14269 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14270 ":"))
14271 props))
14272 (when (or (not specific) (string= specific "BLOCKED"))
14273 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14274 (when (or (not specific)
14275 (member specific
14276 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14277 "TIMESTAMP" "TIMESTAMP_IA")))
14278 (catch 'match
14279 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14280 (setq key (if (match-end 1)
14281 (substring (org-match-string-no-properties 1)
14282 0 -1))
14283 string (if (equal key clockstr)
14284 (org-no-properties
14285 (org-trim
14286 (buffer-substring
14287 (match-beginning 3) (goto-char
14288 (point-at-eol)))))
14289 (substring (org-match-string-no-properties 3)
14290 1 -1)))
14291 ;; Get the correct property name from the key. This is
14292 ;; necessary if the user has configured time keywords.
14293 (setq key1 (concat key ":"))
14294 (cond
14295 ((not key)
14296 (setq key
14297 (if (= (char-after (match-beginning 3)) ?\[)
14298 "TIMESTAMP_IA" "TIMESTAMP")))
14299 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14300 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14301 ((equal key1 org-closed-string) (setq key "CLOSED"))
14302 ((equal key1 org-clock-string) (setq key "CLOCK")))
14303 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14304 (progn
14305 (push (cons key string) props)
14306 ;; no need to search further if match is found
14307 (throw 'match t))
14308 (when (or (equal key "CLOCK") (not (assoc key props)))
14309 (push (cons key string) props))))))
14312 (when (memq which '(all standard))
14313 ;; Get the standard properties, like :PROP: ...
14314 (setq range (org-get-property-block beg end))
14315 (when range
14316 (goto-char (car range))
14317 (while (re-search-forward
14318 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14319 (cdr range) t)
14320 (setq key (org-match-string-no-properties 1)
14321 value (org-trim (or (org-match-string-no-properties 2) "")))
14322 (unless (member key excluded)
14323 (push (cons key (or value "")) props)))))
14324 (if clocksum
14325 (push (cons "CLOCKSUM"
14326 (org-columns-number-to-string (/ (float clocksum) 60.)
14327 'add_times))
14328 props))
14329 (unless (assoc "CATEGORY" props)
14330 (push (cons "CATEGORY" (org-get-category)) props))
14331 (append sum-props (nreverse props)))))))
14333 (defun org-entry-get (pom property &optional inherit literal-nil)
14334 "Get value of PROPERTY for entry at point-or-marker POM.
14335 If INHERIT is non-nil and the entry does not have the property,
14336 then also check higher levels of the hierarchy.
14337 If INHERIT is the symbol `selective', use inheritance only if the setting
14338 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14339 If the property is present but empty, the return value is the empty string.
14340 If the property is not present at all, nil is returned.
14342 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14343 do not interpret it as the list atom nil. This is used for inheritance
14344 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14345 (org-with-point-at pom
14346 (if (and inherit (if (eq inherit 'selective)
14347 (org-property-inherit-p property)
14349 (org-entry-get-with-inheritance property literal-nil)
14350 (if (member property org-special-properties)
14351 ;; We need a special property. Use `org-entry-properties' to
14352 ;; retrieve it, but specify the wanted property
14353 (cdr (assoc property (org-entry-properties nil 'special property)))
14354 (let ((range (unless (org-before-first-heading-p)
14355 (org-get-property-block)))
14356 (props (list (or (assoc property org-file-properties)
14357 (assoc property org-global-properties)
14358 (assoc property org-global-properties-fixed))))
14359 val)
14360 (org-flet ((ap (key)
14361 (when (re-search-forward
14362 (org-re-property key) (cdr range) t)
14363 (setq props
14364 (org-update-property-plist
14366 (if (match-end 1)
14367 (org-match-string-no-properties 1) "")
14368 props)))))
14369 (when (and range (goto-char (car range)))
14370 (ap property)
14371 (goto-char (car range))
14372 (while (ap (concat property "+")))
14373 (setq val (cdr (assoc property props)))
14374 (when val (if literal-nil val (org-not-nil val))))))))))
14376 (defun org-property-or-variable-value (var &optional inherit)
14377 "Check if there is a property fixing the value of VAR.
14378 If yes, return this value. If not, return the current value of the variable."
14379 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14380 (if (and prop (stringp prop) (string-match "\\S-" prop))
14381 (read prop)
14382 (symbol-value var))))
14384 (defun org-entry-delete (pom property)
14385 "Delete the property PROPERTY from entry at point-or-marker POM."
14386 (org-with-point-at pom
14387 (if (member property org-special-properties)
14388 nil ; cannot delete these properties.
14389 (let ((range (org-get-property-block)))
14390 (if (and range
14391 (goto-char (car range))
14392 (re-search-forward
14393 (org-re-property property)
14394 (cdr range) t))
14395 (progn
14396 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14398 nil)))))
14400 ;; Multi-values properties are properties that contain multiple values
14401 ;; These values are assumed to be single words, separated by whitespace.
14402 (defun org-entry-add-to-multivalued-property (pom property value)
14403 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14404 (let* ((old (org-entry-get pom property))
14405 (values (and old (org-split-string old "[ \t]"))))
14406 (setq value (org-entry-protect-space value))
14407 (unless (member value values)
14408 (setq values (cons value values))
14409 (org-entry-put pom property
14410 (mapconcat 'identity values " ")))))
14412 (defun org-entry-remove-from-multivalued-property (pom property value)
14413 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14414 (let* ((old (org-entry-get pom property))
14415 (values (and old (org-split-string old "[ \t]"))))
14416 (setq value (org-entry-protect-space value))
14417 (when (member value values)
14418 (setq values (delete value values))
14419 (org-entry-put pom property
14420 (mapconcat 'identity values " ")))))
14422 (defun org-entry-member-in-multivalued-property (pom property value)
14423 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14424 (let* ((old (org-entry-get pom property))
14425 (values (and old (org-split-string old "[ \t]"))))
14426 (setq value (org-entry-protect-space value))
14427 (member value values)))
14429 (defun org-entry-get-multivalued-property (pom property)
14430 "Return a list of values in a multivalued property."
14431 (let* ((value (org-entry-get pom property))
14432 (values (and value (org-split-string value "[ \t]"))))
14433 (mapcar 'org-entry-restore-space values)))
14435 (defun org-entry-put-multivalued-property (pom property &rest values)
14436 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14437 VALUES should be a list of strings. Spaces will be protected."
14438 (org-entry-put pom property
14439 (mapconcat 'org-entry-protect-space values " "))
14440 (let* ((value (org-entry-get pom property))
14441 (values (and value (org-split-string value "[ \t]"))))
14442 (mapcar 'org-entry-restore-space values)))
14444 (defun org-entry-protect-space (s)
14445 "Protect spaces and newline in string S."
14446 (while (string-match " " s)
14447 (setq s (replace-match "%20" t t s)))
14448 (while (string-match "\n" s)
14449 (setq s (replace-match "%0A" t t s)))
14452 (defun org-entry-restore-space (s)
14453 "Restore spaces and newline in string S."
14454 (while (string-match "%20" s)
14455 (setq s (replace-match " " t t s)))
14456 (while (string-match "%0A" s)
14457 (setq s (replace-match "\n" t t s)))
14460 (defvar org-entry-property-inherited-from (make-marker)
14461 "Marker pointing to the entry from where a property was inherited.
14462 Each call to `org-entry-get-with-inheritance' will set this marker to the
14463 location of the entry where the inheritance search matched. If there was
14464 no match, the marker will point nowhere.
14465 Note that also `org-entry-get' calls this function, if the INHERIT flag
14466 is set.")
14468 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14469 "Get entry property, and search higher levels if not present.
14470 The search will stop at the first ancestor which has the property defined.
14471 If the value found is \"nil\", return nil to show that the property
14472 should be considered as undefined (this is the meaning of nil here).
14473 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14474 (move-marker org-entry-property-inherited-from nil)
14475 (let (tmp)
14476 (unless (org-before-first-heading-p)
14477 (save-excursion
14478 (save-restriction
14479 (widen)
14480 (catch 'ex
14481 (while t
14482 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14483 (org-back-to-heading t)
14484 (move-marker org-entry-property-inherited-from (point))
14485 (throw 'ex tmp))
14486 (or (org-up-heading-safe) (throw 'ex nil)))))))
14487 (setq tmp (or tmp
14488 (cdr (assoc property org-file-properties))
14489 (cdr (assoc property org-global-properties))
14490 (cdr (assoc property org-global-properties-fixed))))
14491 (if literal-nil tmp (org-not-nil tmp))))
14493 (defvar org-property-changed-functions nil
14494 "Hook called when the value of a property has changed.
14495 Each hook function should accept two arguments, the name of the property
14496 and the new value.")
14498 (defun org-entry-put (pom property value)
14499 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14500 (org-with-point-at pom
14501 (org-back-to-heading t)
14502 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14503 range)
14504 (cond
14505 ((equal property "TODO")
14506 (when (and (stringp value) (string-match "\\S-" value)
14507 (not (member value org-todo-keywords-1)))
14508 (error "\"%s\" is not a valid TODO state" value))
14509 (if (or (not value)
14510 (not (string-match "\\S-" value)))
14511 (setq value 'none))
14512 (org-todo value)
14513 (org-set-tags nil 'align))
14514 ((equal property "PRIORITY")
14515 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14516 (string-to-char value) ?\ ))
14517 (org-set-tags nil 'align))
14518 ((equal property "SCHEDULED")
14519 (if (re-search-forward org-scheduled-time-regexp end t)
14520 (cond
14521 ((eq value 'earlier) (org-timestamp-change -1 'day))
14522 ((eq value 'later) (org-timestamp-change 1 'day))
14523 (t (call-interactively 'org-schedule)))
14524 (call-interactively 'org-schedule)))
14525 ((equal property "DEADLINE")
14526 (if (re-search-forward org-deadline-time-regexp end t)
14527 (cond
14528 ((eq value 'earlier) (org-timestamp-change -1 'day))
14529 ((eq value 'later) (org-timestamp-change 1 'day))
14530 (t (call-interactively 'org-deadline)))
14531 (call-interactively 'org-deadline)))
14532 ((member property org-special-properties)
14533 (error "The %s property can not yet be set with `org-entry-put'"
14534 property))
14535 (t ; a non-special property
14536 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14537 (setq range (org-get-property-block beg end 'force))
14538 (goto-char (car range))
14539 (if (re-search-forward
14540 (org-re-property-keyword property) (cdr range) t)
14541 (progn
14542 (delete-region (match-beginning 0) (match-end 0))
14543 (goto-char (match-beginning 0)))
14544 (goto-char (cdr range))
14545 (insert "\n")
14546 (backward-char 1)
14547 (org-indent-line))
14548 (insert ":" property ":")
14549 (and value (insert " " value))
14550 (org-indent-line)))))
14551 (run-hook-with-args 'org-property-changed-functions property value)))
14553 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14554 "Get all property keys in the current buffer.
14555 With INCLUDE-SPECIALS, also list the special properties that reflect things
14556 like tags and TODO state.
14557 With INCLUDE-DEFAULTS, also include properties that has special meaning
14558 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14559 and others.
14560 With INCLUDE-COLUMNS, also include property names given in COLUMN
14561 formats in the current buffer."
14562 (let (rtn range cfmt s p)
14563 (save-excursion
14564 (save-restriction
14565 (widen)
14566 (goto-char (point-min))
14567 (while (re-search-forward org-property-start-re nil t)
14568 (setq range (org-get-property-block))
14569 (goto-char (car range))
14570 (while (re-search-forward
14571 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14572 (cdr range) t)
14573 (add-to-list 'rtn (org-match-string-no-properties 1)))
14574 (outline-next-heading))))
14576 (when include-specials
14577 (setq rtn (append org-special-properties rtn)))
14579 (when include-defaults
14580 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14581 (add-to-list 'rtn org-effort-property))
14583 (when include-columns
14584 (save-excursion
14585 (save-restriction
14586 (widen)
14587 (goto-char (point-min))
14588 (while (re-search-forward
14589 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14590 nil t)
14591 (setq cfmt (match-string 2) s 0)
14592 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14593 cfmt s)
14594 (setq s (match-end 0)
14595 p (match-string 1 cfmt))
14596 (unless (or (equal p "ITEM")
14597 (member p org-special-properties))
14598 (add-to-list 'rtn (match-string 1 cfmt))))))))
14600 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14602 (defun org-property-values (key)
14603 "Return a list of all values of property KEY in the current buffer."
14604 (save-excursion
14605 (save-restriction
14606 (widen)
14607 (goto-char (point-min))
14608 (let ((re (org-re-property key))
14609 values)
14610 (while (re-search-forward re nil t)
14611 (add-to-list 'values (org-trim (match-string 1))))
14612 (delete "" values)))))
14614 (defun org-insert-property-drawer ()
14615 "Insert a property drawer into the current entry."
14616 (org-back-to-heading t)
14617 (looking-at org-outline-regexp)
14618 (let ((indent (if org-adapt-indentation
14619 (- (match-end 0) (match-beginning 0))
14621 (beg (point))
14622 (re (concat "^[ \t]*" org-keyword-time-regexp))
14623 end hiddenp)
14624 (outline-next-heading)
14625 (setq end (point))
14626 (goto-char beg)
14627 (while (re-search-forward re end t))
14628 (setq hiddenp (outline-invisible-p))
14629 (end-of-line 1)
14630 (and (equal (char-after) ?\n) (forward-char 1))
14631 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14632 (if (member (match-string 1) '("CLOCK:" ":END:"))
14633 ;; just skip this line
14634 (beginning-of-line 2)
14635 ;; Drawer start, find the end
14636 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14637 (beginning-of-line 1)))
14638 (org-skip-over-state-notes)
14639 (skip-chars-backward " \t\n\r")
14640 (if (eq (char-before) ?*) (forward-char 1))
14641 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14642 (beginning-of-line 0)
14643 (org-indent-to-column indent)
14644 (beginning-of-line 2)
14645 (org-indent-to-column indent)
14646 (beginning-of-line 0)
14647 (if hiddenp
14648 (save-excursion
14649 (org-back-to-heading t)
14650 (hide-entry))
14651 (org-flag-drawer t))))
14653 (defun org-insert-drawer (&optional arg drawer)
14654 "Insert a drawer at point.
14656 Optional argument DRAWER, when non-nil, is a string representing
14657 drawer's name. Otherwise, the user is prompted for a name.
14659 If a region is active, insert the drawer around that region
14660 instead.
14662 Point is left between drawer's boundaries."
14663 (interactive "P")
14664 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14665 "LOGBOOK"))
14666 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14667 ;; internally by Org. They are meant to be inserted
14668 ;; automatically.
14669 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14670 ;; Remove system drawers from list. Note: For some reason,
14671 ;; `org-completing-read' ignores the predicate while
14672 ;; `completing-read' handles it fine.
14673 (drawer (if arg "PROPERTIES"
14674 (or drawer
14675 (completing-read
14676 "Drawer: " org-drawers
14677 (lambda (d) (not (member d system-drawers))))))))
14678 (cond
14679 ;; With C-u, fall back on `org-insert-property-drawer'
14680 (arg (org-insert-property-drawer))
14681 ;; With an active region, insert a drawer at point.
14682 ((not (org-region-active-p))
14683 (progn
14684 (unless (bolp) (insert "\n"))
14685 (insert (format ":%s:\n\n:END:\n" drawer))
14686 (forward-line -2)))
14687 ;; Otherwise, insert the drawer at point
14689 (let ((rbeg (region-beginning))
14690 (rend (copy-marker (region-end))))
14691 (unwind-protect
14692 (progn
14693 (goto-char rbeg)
14694 (beginning-of-line)
14695 (when (save-excursion
14696 (re-search-forward org-outline-regexp-bol rend t))
14697 (error "Drawers cannot contain headlines"))
14698 ;; Position point at the beginning of the first
14699 ;; non-blank line in region. Insert drawer's opening
14700 ;; there, then indent it.
14701 (org-skip-whitespace)
14702 (beginning-of-line)
14703 (insert ":" drawer ":\n")
14704 (forward-line -1)
14705 (indent-for-tab-command)
14706 ;; Move point to the beginning of the first blank line
14707 ;; after the last non-blank line in region. Insert
14708 ;; drawer's closing, then indent it.
14709 (goto-char rend)
14710 (skip-chars-backward " \r\t\n")
14711 (insert "\n:END:")
14712 (indent-for-tab-command)
14713 (unless (eolp) (insert "\n")))
14714 ;; Clear marker, whatever the outcome of insertion is.
14715 (set-marker rend nil)))))))
14717 (defvar org-property-set-functions-alist nil
14718 "Property set function alist.
14719 Each entry should have the following format:
14721 (PROPERTY . READ-FUNCTION)
14723 The read function will be called with the same argument as
14724 `org-completing-read'.")
14726 (defun org-set-property-function (property)
14727 "Get the function that should be used to set PROPERTY.
14728 This is computed according to `org-property-set-functions-alist'."
14729 (or (cdr (assoc property org-property-set-functions-alist))
14730 'org-completing-read))
14732 (defun org-read-property-value (property)
14733 "Read PROPERTY value from user."
14734 (let* ((completion-ignore-case t)
14735 (allowed (org-property-get-allowed-values nil property 'table))
14736 (cur (org-entry-get nil property))
14737 (prompt (concat property " value"
14738 (if (and cur (string-match "\\S-" cur))
14739 (concat " [" cur "]") "") ": "))
14740 (set-function (org-set-property-function property))
14741 (val (if allowed
14742 (funcall set-function prompt allowed nil
14743 (not (get-text-property 0 'org-unrestricted
14744 (caar allowed))))
14745 (let (org-completion-use-ido org-completion-use-iswitchb)
14746 (funcall set-function prompt
14747 (mapcar 'list (org-property-values property))
14748 nil nil "" nil cur)))))
14749 (if (equal val "")
14751 val)))
14753 (defvar org-last-set-property nil)
14754 (defun org-read-property-name ()
14755 "Read a property name."
14756 (let* ((completion-ignore-case t)
14757 (keys (org-buffer-property-keys nil t t))
14758 (default-prop (or (save-excursion
14759 (save-match-data
14760 (beginning-of-line)
14761 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14762 (null (string= (match-string 1) "END"))
14763 (match-string 1))))
14764 org-last-set-property))
14765 (property (org-icompleting-read
14766 (concat "Property"
14767 (if default-prop (concat " [" default-prop "]") "")
14768 ": ")
14769 (mapcar 'list keys)
14770 nil nil nil nil
14771 default-prop
14773 (if (member property keys)
14774 property
14775 (or (cdr (assoc (downcase property)
14776 (mapcar (lambda (x) (cons (downcase x) x))
14777 keys)))
14778 property))))
14780 (defun org-set-property (property value)
14781 "In the current entry, set PROPERTY to VALUE.
14782 When called interactively, this will prompt for a property name, offering
14783 completion on existing and default properties. And then it will prompt
14784 for a value, offering completion either on allowed values (via an inherited
14785 xxx_ALL property) or on existing values in other instances of this property
14786 in the current file."
14787 (interactive (list nil nil))
14788 (let* ((property (or property (org-read-property-name)))
14789 (value (or value (org-read-property-value property)))
14790 (fn (cdr (assoc property org-properties-postprocess-alist))))
14791 (setq org-last-set-property property)
14792 ;; Possibly postprocess the inserted value:
14793 (when fn (setq value (funcall fn value)))
14794 (unless (equal (org-entry-get nil property) value)
14795 (org-entry-put nil property value))))
14797 (defun org-delete-property (property)
14798 "In the current entry, delete PROPERTY."
14799 (interactive
14800 (let* ((completion-ignore-case t)
14801 (prop (org-icompleting-read "Property: "
14802 (org-entry-properties nil 'standard))))
14803 (list prop)))
14804 (message "Property %s %s" property
14805 (if (org-entry-delete nil property)
14806 "deleted"
14807 "was not present in the entry")))
14809 (defun org-delete-property-globally (property)
14810 "Remove PROPERTY globally, from all entries."
14811 (interactive
14812 (let* ((completion-ignore-case t)
14813 (prop (org-icompleting-read
14814 "Globally remove property: "
14815 (mapcar 'list (org-buffer-property-keys)))))
14816 (list prop)))
14817 (save-excursion
14818 (save-restriction
14819 (widen)
14820 (goto-char (point-min))
14821 (let ((cnt 0))
14822 (while (re-search-forward
14823 (org-re-property property)
14824 nil t)
14825 (setq cnt (1+ cnt))
14826 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14827 (message "Property \"%s\" removed from %d entries" property cnt)))))
14829 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14831 (defun org-compute-property-at-point ()
14832 "Compute the property at point.
14833 This looks for an enclosing column format, extracts the operator and
14834 then applies it to the property in the column format's scope."
14835 (interactive)
14836 (unless (org-at-property-p)
14837 (error "Not at a property"))
14838 (let ((prop (org-match-string-no-properties 2)))
14839 (org-columns-get-format-and-top-level)
14840 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14841 (error "No operator defined for property %s" prop))
14842 (org-columns-compute prop)))
14844 (defvar org-property-allowed-value-functions nil
14845 "Hook for functions supplying allowed values for a specific property.
14846 The functions must take a single argument, the name of the property, and
14847 return a flat list of allowed values. If \":ETC\" is one of
14848 the values, this means that these values are intended as defaults for
14849 completion, but that other values should be allowed too.
14850 The functions must return nil if they are not responsible for this
14851 property.")
14853 (defun org-property-get-allowed-values (pom property &optional table)
14854 "Get allowed values for the property PROPERTY.
14855 When TABLE is non-nil, return an alist that can directly be used for
14856 completion."
14857 (let (vals)
14858 (cond
14859 ((equal property "TODO")
14860 (setq vals (org-with-point-at pom
14861 (append org-todo-keywords-1 '("")))))
14862 ((equal property "PRIORITY")
14863 (let ((n org-lowest-priority))
14864 (while (>= n org-highest-priority)
14865 (push (char-to-string n) vals)
14866 (setq n (1- n)))))
14867 ((member property org-special-properties))
14868 ((setq vals (run-hook-with-args-until-success
14869 'org-property-allowed-value-functions property)))
14871 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14872 (when (and vals (string-match "\\S-" vals))
14873 (setq vals (car (read-from-string (concat "(" vals ")"))))
14874 (setq vals (mapcar (lambda (x)
14875 (cond ((stringp x) x)
14876 ((numberp x) (number-to-string x))
14877 ((symbolp x) (symbol-name x))
14878 (t "???")))
14879 vals)))))
14880 (when (member ":ETC" vals)
14881 (setq vals (remove ":ETC" vals))
14882 (org-add-props (car vals) '(org-unrestricted t)))
14883 (if table (mapcar 'list vals) vals)))
14885 (defun org-property-previous-allowed-value (&optional previous)
14886 "Switch to the next allowed value for this property."
14887 (interactive)
14888 (org-property-next-allowed-value t))
14890 (defun org-property-next-allowed-value (&optional previous)
14891 "Switch to the next allowed value for this property."
14892 (interactive)
14893 (unless (org-at-property-p)
14894 (error "Not at a property"))
14895 (let* ((key (match-string 2))
14896 (value (match-string 3))
14897 (allowed (or (org-property-get-allowed-values (point) key)
14898 (and (member value '("[ ]" "[-]" "[X]"))
14899 '("[ ]" "[X]"))))
14900 nval)
14901 (unless allowed
14902 (error "Allowed values for this property have not been defined"))
14903 (if previous (setq allowed (reverse allowed)))
14904 (if (member value allowed)
14905 (setq nval (car (cdr (member value allowed)))))
14906 (setq nval (or nval (car allowed)))
14907 (if (equal nval value)
14908 (error "Only one allowed value for this property"))
14909 (org-at-property-p)
14910 (replace-match (concat " :" key ": " nval) t t)
14911 (org-indent-line)
14912 (beginning-of-line 1)
14913 (skip-chars-forward " \t")
14914 (run-hook-with-args 'org-property-changed-functions key nval)))
14916 (defun org-find-olp (path &optional this-buffer)
14917 "Return a marker pointing to the entry at outline path OLP.
14918 If anything goes wrong, throw an error.
14919 You can wrap this call to catch the error like this:
14921 (condition-case msg
14922 (org-mobile-locate-entry (match-string 4))
14923 (error (nth 1 msg)))
14925 The return value will then be either a string with the error message,
14926 or a marker if everything is OK.
14928 If THIS-BUFFER is set, the outline path does not contain a file,
14929 only headings."
14930 (let* ((file (if this-buffer buffer-file-name (pop path)))
14931 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14932 (level 1)
14933 (lmin 1)
14934 (lmax 1)
14935 limit re end found pos heading cnt flevel)
14936 (unless buffer (error "File not found :%s" file))
14937 (with-current-buffer buffer
14938 (save-excursion
14939 (save-restriction
14940 (widen)
14941 (setq limit (point-max))
14942 (goto-char (point-min))
14943 (while (setq heading (pop path))
14944 (setq re (format org-complex-heading-regexp-format
14945 (regexp-quote heading)))
14946 (setq cnt 0 pos (point))
14947 (while (re-search-forward re end t)
14948 (setq level (- (match-end 1) (match-beginning 1)))
14949 (if (and (>= level lmin) (<= level lmax))
14950 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14951 (when (= cnt 0) (error "Heading not found on level %d: %s"
14952 lmax heading))
14953 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14954 lmax heading))
14955 (goto-char found)
14956 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14957 (setq end (save-excursion (org-end-of-subtree t t))))
14958 (when (org-at-heading-p)
14959 (move-marker (make-marker) (point))))))))
14961 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14962 "Find node HEADING in BUFFER.
14963 Return a marker to the heading if it was found, or nil if not.
14964 If POS-ONLY is set, return just the position instead of a marker.
14966 The heading text must match exact, but it may have a TODO keyword,
14967 a priority cookie and tags in the standard locations."
14968 (with-current-buffer (or buffer (current-buffer))
14969 (save-excursion
14970 (save-restriction
14971 (widen)
14972 (goto-char (point-min))
14973 (let (case-fold-search)
14974 (if (re-search-forward
14975 (format org-complex-heading-regexp-format
14976 (regexp-quote heading)) nil t)
14977 (if pos-only
14978 (match-beginning 0)
14979 (move-marker (make-marker) (match-beginning 0)))))))))
14981 (defun org-find-exact-heading-in-directory (heading &optional dir)
14982 "Find Org node headline HEADING in all .org files in directory DIR.
14983 When the target headline is found, return a marker to this location."
14984 (let ((files (directory-files (or dir default-directory)
14985 nil "\\`[^.#].*\\.org\\'"))
14986 file visiting m buffer)
14987 (catch 'found
14988 (while (setq file (pop files))
14989 (message "trying %s" file)
14990 (setq visiting (org-find-base-buffer-visiting file))
14991 (setq buffer (or visiting (find-file-noselect file)))
14992 (setq m (org-find-exact-headline-in-buffer
14993 heading buffer))
14994 (when (and (not m) (not visiting)) (kill-buffer buffer))
14995 (and m (throw 'found m))))))
14997 (defun org-find-entry-with-id (ident)
14998 "Locate the entry that contains the ID property with exact value IDENT.
14999 IDENT can be a string, a symbol or a number, this function will search for
15000 the string representation of it.
15001 Return the position where this entry starts, or nil if there is no such entry."
15002 (interactive "sID: ")
15003 (let ((id (cond
15004 ((stringp ident) ident)
15005 ((symbol-name ident) (symbol-name ident))
15006 ((numberp ident) (number-to-string ident))
15007 (t (error "IDENT %s must be a string, symbol or number" ident))))
15008 (case-fold-search nil))
15009 (save-excursion
15010 (save-restriction
15011 (widen)
15012 (goto-char (point-min))
15013 (when (re-search-forward
15014 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15015 nil t)
15016 (org-back-to-heading t)
15017 (point))))))
15019 ;;;; Timestamps
15021 (defvar org-last-changed-timestamp nil)
15022 (defvar org-last-inserted-timestamp nil
15023 "The last time stamp inserted with `org-insert-time-stamp'.")
15024 (defvar org-time-was-given) ; dynamically scoped parameter
15025 (defvar org-end-time-was-given) ; dynamically scoped parameter
15026 (defvar org-ts-what) ; dynamically scoped parameter
15028 (defun org-time-stamp (arg &optional inactive)
15029 "Prompt for a date/time and insert a time stamp.
15030 If the user specifies a time like HH:MM or if this command is
15031 called with at least one prefix argument, the time stamp contains
15032 the date and the time. Otherwise, only the date is be included.
15034 All parts of a date not specified by the user is filled in from
15035 the current date/time. So if you just press return without
15036 typing anything, the time stamp will represent the current
15037 date/time.
15039 If there is already a timestamp at the cursor, it will be
15040 modified.
15042 With two universal prefix arguments, insert an active timestamp
15043 with the current time without prompting the user."
15044 (interactive "P")
15045 (let* ((ts nil)
15046 (default-time
15047 ;; Default time is either today, or, when entering a range,
15048 ;; the range start.
15049 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15050 (save-excursion
15051 (re-search-backward
15052 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15053 (- (point) 20) t)))
15054 (apply 'encode-time (org-parse-time-string (match-string 1)))
15055 (current-time)))
15056 (default-input (and ts (org-get-compact-tod ts)))
15057 (repeater (save-excursion
15058 (save-match-data
15059 (beginning-of-line)
15060 (when (re-search-forward
15061 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15062 (save-excursion (progn (end-of-line) (point))) t)
15063 (match-string 0)))))
15064 org-time-was-given org-end-time-was-given time)
15065 (cond
15066 ((and (org-at-timestamp-p t)
15067 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15068 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15069 (insert "--")
15070 (setq time (let ((this-command this-command))
15071 (org-read-date arg 'totime nil nil
15072 default-time default-input inactive)))
15073 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15074 ((org-at-timestamp-p t)
15075 (setq time (let ((this-command this-command))
15076 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15077 (when (org-at-timestamp-p t) ; just to get the match data
15078 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15079 (replace-match "")
15080 (setq org-last-changed-timestamp
15081 (org-insert-time-stamp
15082 time (or org-time-was-given arg)
15083 inactive nil nil (list org-end-time-was-given)))
15084 (when repeater (goto-char (1- (point))) (insert " " repeater)
15085 (setq org-last-changed-timestamp
15086 (concat (substring org-last-inserted-timestamp 0 -1)
15087 " " repeater ">"))))
15088 (message "Timestamp updated"))
15089 ((equal arg '(16))
15090 (org-insert-time-stamp (current-time) t))
15092 (setq time (let ((this-command this-command))
15093 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15094 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15095 nil nil (list org-end-time-was-given))))))
15097 ;; FIXME: can we use this for something else, like computing time differences?
15098 (defun org-get-compact-tod (s)
15099 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15100 (let* ((t1 (match-string 1 s))
15101 (h1 (string-to-number (match-string 2 s)))
15102 (m1 (string-to-number (match-string 3 s)))
15103 (t2 (and (match-end 4) (match-string 5 s)))
15104 (h2 (and t2 (string-to-number (match-string 6 s))))
15105 (m2 (and t2 (string-to-number (match-string 7 s))))
15106 dh dm)
15107 (if (not t2)
15109 (setq dh (- h2 h1) dm (- m2 m1))
15110 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15111 (concat t1 "+" (number-to-string dh)
15112 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15114 (defun org-time-stamp-inactive (&optional arg)
15115 "Insert an inactive time stamp.
15116 An inactive time stamp is enclosed in square brackets instead of angle
15117 brackets. It is inactive in the sense that it does not trigger agenda entries,
15118 does not link to the calendar and cannot be changed with the S-cursor keys.
15119 So these are more for recording a certain time/date."
15120 (interactive "P")
15121 (org-time-stamp arg 'inactive))
15123 (defvar org-date-ovl (make-overlay 1 1))
15124 (overlay-put org-date-ovl 'face 'org-date-selected)
15125 (org-detach-overlay org-date-ovl)
15127 (defvar org-ans1) ; dynamically scoped parameter
15128 (defvar org-ans2) ; dynamically scoped parameter
15130 (defvar org-plain-time-of-day-regexp) ; defined below
15132 (defvar org-overriding-default-time nil) ; dynamically scoped
15133 (defvar org-read-date-overlay nil)
15134 (defvar org-dcst nil) ; dynamically scoped
15135 (defvar org-read-date-history nil)
15136 (defvar org-read-date-final-answer nil)
15137 (defvar org-read-date-analyze-futurep nil)
15138 (defvar org-read-date-analyze-forced-year nil)
15139 (defvar org-read-date-inactive)
15141 (defun org-read-date (&optional org-with-time to-time from-string prompt
15142 default-time default-input inactive)
15143 "Read a date, possibly a time, and make things smooth for the user.
15144 The prompt will suggest to enter an ISO date, but you can also enter anything
15145 which will at least partially be understood by `parse-time-string'.
15146 Unrecognized parts of the date will default to the current day, month, year,
15147 hour and minute. If this command is called to replace a timestamp at point,
15148 or to enter the second timestamp of a range, the default time is taken
15149 from the existing stamp. Furthermore, the command prefers the future,
15150 so if you are giving a date where the year is not given, and the day-month
15151 combination is already past in the current year, it will assume you
15152 mean next year. For details, see the manual. A few examples:
15154 3-2-5 --> 2003-02-05
15155 feb 15 --> currentyear-02-15
15156 2/15 --> currentyear-02-15
15157 sep 12 9 --> 2009-09-12
15158 12:45 --> today 12:45
15159 22 sept 0:34 --> currentyear-09-22 0:34
15160 12 --> currentyear-currentmonth-12
15161 Fri --> nearest Friday (today or later)
15162 etc.
15164 Furthermore you can specify a relative date by giving, as the *first* thing
15165 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15166 change in days weeks, months, years.
15167 With a single plus or minus, the date is relative to today. With a double
15168 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15169 +4d --> four days from today
15170 +4 --> same as above
15171 +2w --> two weeks from today
15172 ++5 --> five days from default date
15174 The function understands only English month and weekday abbreviations.
15176 While prompting, a calendar is popped up - you can also select the
15177 date with the mouse (button 1). The calendar shows a period of three
15178 months. To scroll it to other months, use the keys `>' and `<'.
15179 If you don't like the calendar, turn it off with
15180 \(setq org-read-date-popup-calendar nil)
15182 With optional argument TO-TIME, the date will immediately be converted
15183 to an internal time.
15184 With an optional argument WITH-TIME, the prompt will suggest to also
15185 insert a time. Note that when WITH-TIME is not set, you can still
15186 enter a time, and this function will inform the calling routine about
15187 this change. The calling routine may then choose to change the format
15188 used to insert the time stamp into the buffer to include the time.
15189 With optional argument FROM-STRING, read from this string instead from
15190 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15191 the time/date that is used for everything that is not specified by the
15192 user."
15193 (require 'parse-time)
15194 (let* ((org-time-stamp-rounding-minutes
15195 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15196 (org-dcst org-display-custom-times)
15197 (ct (org-current-time))
15198 (org-def (or org-overriding-default-time default-time ct))
15199 (org-defdecode (decode-time org-def))
15200 (dummy (progn
15201 (when (< (nth 2 org-defdecode) org-extend-today-until)
15202 (setcar (nthcdr 2 org-defdecode) -1)
15203 (setcar (nthcdr 1 org-defdecode) 59)
15204 (setq org-def (apply 'encode-time org-defdecode)
15205 org-defdecode (decode-time org-def)))))
15206 (calendar-frame-setup nil)
15207 (calendar-setup nil)
15208 (calendar-move-hook nil)
15209 (calendar-view-diary-initially-flag nil)
15210 (calendar-view-holidays-initially-flag nil)
15211 (timestr (format-time-string
15212 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15213 (prompt (concat (if prompt (concat prompt " ") "")
15214 (format "Date+time [%s]: " timestr)))
15215 ans (org-ans0 "") org-ans1 org-ans2 final)
15217 (cond
15218 (from-string (setq ans from-string))
15219 (org-read-date-popup-calendar
15220 (save-excursion
15221 (save-window-excursion
15222 (calendar)
15223 (org-eval-in-calendar '(setq cursor-type nil) t)
15224 (unwind-protect
15225 (progn
15226 (calendar-forward-day (- (time-to-days org-def)
15227 (calendar-absolute-from-gregorian
15228 (calendar-current-date))))
15229 (org-eval-in-calendar nil t)
15230 (let* ((old-map (current-local-map))
15231 (map (copy-keymap calendar-mode-map))
15232 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15233 (org-defkey map (kbd "RET") 'org-calendar-select)
15234 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15235 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15236 (org-defkey minibuffer-local-map [(meta shift left)]
15237 (lambda () (interactive)
15238 (org-eval-in-calendar '(calendar-backward-month 1))))
15239 (org-defkey minibuffer-local-map [(meta shift right)]
15240 (lambda () (interactive)
15241 (org-eval-in-calendar '(calendar-forward-month 1))))
15242 (org-defkey minibuffer-local-map [(meta shift up)]
15243 (lambda () (interactive)
15244 (org-eval-in-calendar '(calendar-backward-year 1))))
15245 (org-defkey minibuffer-local-map [(meta shift down)]
15246 (lambda () (interactive)
15247 (org-eval-in-calendar '(calendar-forward-year 1))))
15248 (org-defkey minibuffer-local-map [?\e (shift left)]
15249 (lambda () (interactive)
15250 (org-eval-in-calendar '(calendar-backward-month 1))))
15251 (org-defkey minibuffer-local-map [?\e (shift right)]
15252 (lambda () (interactive)
15253 (org-eval-in-calendar '(calendar-forward-month 1))))
15254 (org-defkey minibuffer-local-map [?\e (shift up)]
15255 (lambda () (interactive)
15256 (org-eval-in-calendar '(calendar-backward-year 1))))
15257 (org-defkey minibuffer-local-map [?\e (shift down)]
15258 (lambda () (interactive)
15259 (org-eval-in-calendar '(calendar-forward-year 1))))
15260 (org-defkey minibuffer-local-map [(shift up)]
15261 (lambda () (interactive)
15262 (org-eval-in-calendar '(calendar-backward-week 1))))
15263 (org-defkey minibuffer-local-map [(shift down)]
15264 (lambda () (interactive)
15265 (org-eval-in-calendar '(calendar-forward-week 1))))
15266 (org-defkey minibuffer-local-map [(shift left)]
15267 (lambda () (interactive)
15268 (org-eval-in-calendar '(calendar-backward-day 1))))
15269 (org-defkey minibuffer-local-map [(shift right)]
15270 (lambda () (interactive)
15271 (org-eval-in-calendar '(calendar-forward-day 1))))
15272 (org-defkey minibuffer-local-map ">"
15273 (lambda () (interactive)
15274 (org-eval-in-calendar '(scroll-calendar-left 1))))
15275 (org-defkey minibuffer-local-map "<"
15276 (lambda () (interactive)
15277 (org-eval-in-calendar '(scroll-calendar-right 1))))
15278 (org-defkey minibuffer-local-map "\C-v"
15279 (lambda () (interactive)
15280 (org-eval-in-calendar
15281 '(calendar-scroll-left-three-months 1))))
15282 (org-defkey minibuffer-local-map "\M-v"
15283 (lambda () (interactive)
15284 (org-eval-in-calendar
15285 '(calendar-scroll-right-three-months 1))))
15286 (run-hooks 'org-read-date-minibuffer-setup-hook)
15287 (unwind-protect
15288 (progn
15289 (use-local-map map)
15290 (setq org-read-date-inactive inactive)
15291 (add-hook 'post-command-hook 'org-read-date-display)
15292 (setq org-ans0 (read-string prompt default-input
15293 'org-read-date-history nil))
15294 ;; org-ans0: from prompt
15295 ;; org-ans1: from mouse click
15296 ;; org-ans2: from calendar motion
15297 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15298 (remove-hook 'post-command-hook 'org-read-date-display)
15299 (use-local-map old-map)
15300 (when org-read-date-overlay
15301 (delete-overlay org-read-date-overlay)
15302 (setq org-read-date-overlay nil)))))
15303 (bury-buffer "*Calendar*")))))
15305 (t ; Naked prompt only
15306 (unwind-protect
15307 (setq ans (read-string prompt default-input
15308 'org-read-date-history timestr))
15309 (when org-read-date-overlay
15310 (delete-overlay org-read-date-overlay)
15311 (setq org-read-date-overlay nil)))))
15313 (setq final (org-read-date-analyze ans org-def org-defdecode))
15315 (when org-read-date-analyze-forced-year
15316 (message "Year was forced into %s"
15317 (if org-read-date-force-compatible-dates
15318 "compatible range (1970-2037)"
15319 "range representable on this machine"))
15320 (ding))
15322 ;; One round trip to get rid of 34th of August and stuff like that....
15323 (setq final (decode-time (apply 'encode-time final)))
15325 (setq org-read-date-final-answer ans)
15327 (if to-time
15328 (apply 'encode-time final)
15329 (if (and (boundp 'org-time-was-given) org-time-was-given)
15330 (format "%04d-%02d-%02d %02d:%02d"
15331 (nth 5 final) (nth 4 final) (nth 3 final)
15332 (nth 2 final) (nth 1 final))
15333 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15335 (defvar org-def)
15336 (defvar org-defdecode)
15337 (defvar org-with-time)
15338 (defun org-read-date-display ()
15339 "Display the current date prompt interpretation in the minibuffer."
15340 (when org-read-date-display-live
15341 (when org-read-date-overlay
15342 (delete-overlay org-read-date-overlay))
15343 (when (minibufferp (current-buffer))
15344 (save-excursion
15345 (end-of-line 1)
15346 (while (not (equal (buffer-substring
15347 (max (point-min) (- (point) 4)) (point))
15348 " "))
15349 (insert " ")))
15350 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15351 " " (or org-ans1 org-ans2)))
15352 (org-end-time-was-given nil)
15353 (f (org-read-date-analyze ans org-def org-defdecode))
15354 (fmts (if org-dcst
15355 org-time-stamp-custom-formats
15356 org-time-stamp-formats))
15357 (fmt (if (or org-with-time
15358 (and (boundp 'org-time-was-given) org-time-was-given))
15359 (cdr fmts)
15360 (car fmts)))
15361 (txt (format-time-string fmt (apply 'encode-time f)))
15362 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15363 (txt (concat "=> " txt)))
15364 (when (and org-end-time-was-given
15365 (string-match org-plain-time-of-day-regexp txt))
15366 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15367 org-end-time-was-given
15368 (substring txt (match-end 0)))))
15369 (when org-read-date-analyze-futurep
15370 (setq txt (concat txt " (=>F)")))
15371 (setq org-read-date-overlay
15372 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15373 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15375 (defun org-read-date-analyze (ans org-def org-defdecode)
15376 "Analyze the combined answer of the date prompt."
15377 ;; FIXME: cleanup and comment
15378 (let ((nowdecode (decode-time (current-time)))
15379 delta deltan deltaw deltadef year month day
15380 hour minute second wday pm h2 m2 tl wday1
15381 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15382 (setq org-read-date-analyze-futurep nil
15383 org-read-date-analyze-forced-year nil)
15384 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15385 (setq ans "+0"))
15387 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15388 (setq ans (replace-match "" t t ans)
15389 deltan (car delta)
15390 deltaw (nth 1 delta)
15391 deltadef (nth 2 delta)))
15393 ;; Check if there is an iso week date in there
15394 ;; If yes, store the info and postpone interpreting it until the rest
15395 ;; of the parsing is done
15396 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15397 (setq iso-year (if (match-end 1)
15398 (org-small-year-to-year
15399 (string-to-number (match-string 1 ans))))
15400 iso-weekday (if (match-end 3)
15401 (string-to-number (match-string 3 ans)))
15402 iso-week (string-to-number (match-string 2 ans)))
15403 (setq ans (replace-match "" t t ans)))
15405 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15406 (when (string-match
15407 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15408 (setq year (if (match-end 2)
15409 (string-to-number (match-string 2 ans))
15410 (progn (setq kill-year t)
15411 (string-to-number (format-time-string "%Y"))))
15412 month (string-to-number (match-string 3 ans))
15413 day (string-to-number (match-string 4 ans)))
15414 (if (< year 100) (setq year (+ 2000 year)))
15415 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15416 t nil ans)))
15418 ;; Help matching dotted european dates
15419 (when (string-match
15420 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15421 (setq year (if (match-end 3)
15422 (string-to-number (match-string 3 ans))
15423 (progn (setq kill-year t)
15424 (string-to-number (format-time-string "%Y"))))
15425 day (string-to-number (match-string 1 ans))
15426 month (string-to-number (match-string 2 ans))
15427 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15428 t nil ans)))
15430 ;; Help matching american dates, like 5/30 or 5/30/7
15431 (when (string-match
15432 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15433 (setq year (if (match-end 4)
15434 (string-to-number (match-string 4 ans))
15435 (progn (setq kill-year t)
15436 (string-to-number (format-time-string "%Y"))))
15437 month (string-to-number (match-string 1 ans))
15438 day (string-to-number (match-string 2 ans)))
15439 (if (< year 100) (setq year (+ 2000 year)))
15440 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15441 t nil ans)))
15442 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15443 ;; If there is a time with am/pm, and *no* time without it, we convert
15444 ;; so that matching will be successful.
15445 (loop for i from 1 to 2 do ; twice, for end time as well
15446 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15447 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15448 (setq hour (string-to-number (match-string 1 ans))
15449 minute (if (match-end 3)
15450 (string-to-number (match-string 3 ans))
15452 pm (equal ?p
15453 (string-to-char (downcase (match-string 4 ans)))))
15454 (if (and (= hour 12) (not pm))
15455 (setq hour 0)
15456 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15457 (setq ans (replace-match (format "%02d:%02d" hour minute)
15458 t t ans))))
15460 ;; Check if a time range is given as a duration
15461 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15462 (setq hour (string-to-number (match-string 1 ans))
15463 h2 (+ hour (string-to-number (match-string 3 ans)))
15464 minute (string-to-number (match-string 2 ans))
15465 m2 (+ minute (if (match-end 5) (string-to-number
15466 (match-string 5 ans))0)))
15467 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15468 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15469 t t ans)))
15471 ;; Check if there is a time range
15472 (when (boundp 'org-end-time-was-given)
15473 (setq org-time-was-given nil)
15474 (when (and (string-match org-plain-time-of-day-regexp ans)
15475 (match-end 8))
15476 (setq org-end-time-was-given (match-string 8 ans))
15477 (setq ans (concat (substring ans 0 (match-beginning 7))
15478 (substring ans (match-end 7))))))
15480 (setq tl (parse-time-string ans)
15481 day (or (nth 3 tl) (nth 3 org-defdecode))
15482 month (or (nth 4 tl)
15483 (if (and org-read-date-prefer-future
15484 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15485 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15486 (nth 4 org-defdecode)))
15487 year (or (and (not kill-year) (nth 5 tl))
15488 (if (and org-read-date-prefer-future
15489 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15490 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15491 (nth 5 org-defdecode)))
15492 hour (or (nth 2 tl) (nth 2 org-defdecode))
15493 minute (or (nth 1 tl) (nth 1 org-defdecode))
15494 second (or (nth 0 tl) 0)
15495 wday (nth 6 tl))
15497 (when (and (eq org-read-date-prefer-future 'time)
15498 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15499 (equal day (nth 3 nowdecode))
15500 (equal month (nth 4 nowdecode))
15501 (equal year (nth 5 nowdecode))
15502 (nth 2 tl)
15503 (or (< (nth 2 tl) (nth 2 nowdecode))
15504 (and (= (nth 2 tl) (nth 2 nowdecode))
15505 (nth 1 tl)
15506 (< (nth 1 tl) (nth 1 nowdecode)))))
15507 (setq day (1+ day)
15508 futurep t))
15510 ;; Special date definitions below
15511 (cond
15512 (iso-week
15513 ;; There was an iso week
15514 (require 'cal-iso)
15515 (setq futurep nil)
15516 (setq year (or iso-year year)
15517 day (or iso-weekday wday 1)
15518 wday nil ; to make sure that the trigger below does not match
15519 iso-date (calendar-gregorian-from-absolute
15520 (calendar-absolute-from-iso
15521 (list iso-week day year))))
15522 ; FIXME: Should we also push ISO weeks into the future?
15523 ; (when (and org-read-date-prefer-future
15524 ; (not iso-year)
15525 ; (< (calendar-absolute-from-gregorian iso-date)
15526 ; (time-to-days (current-time))))
15527 ; (setq year (1+ year)
15528 ; iso-date (calendar-gregorian-from-absolute
15529 ; (calendar-absolute-from-iso
15530 ; (list iso-week day year)))))
15531 (setq month (car iso-date)
15532 year (nth 2 iso-date)
15533 day (nth 1 iso-date)))
15534 (deltan
15535 (setq futurep nil)
15536 (unless deltadef
15537 (let ((now (decode-time (current-time))))
15538 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15539 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15540 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15541 ((equal deltaw "m") (setq month (+ month deltan)))
15542 ((equal deltaw "y") (setq year (+ year deltan)))))
15543 ((and wday (not (nth 3 tl)))
15544 (setq futurep nil)
15545 ;; Weekday was given, but no day, so pick that day in the week
15546 ;; on or after the derived date.
15547 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15548 (unless (equal wday wday1)
15549 (setq day (+ day (% (- wday wday1 -7) 7))))))
15550 (if (and (boundp 'org-time-was-given)
15551 (nth 2 tl))
15552 (setq org-time-was-given t))
15553 (if (< year 100) (setq year (+ 2000 year)))
15554 ;; Check of the date is representable
15555 (if org-read-date-force-compatible-dates
15556 (progn
15557 (if (< year 1970)
15558 (setq year 1970 org-read-date-analyze-forced-year t))
15559 (if (> year 2037)
15560 (setq year 2037 org-read-date-analyze-forced-year t)))
15561 (condition-case nil
15562 (ignore (encode-time second minute hour day month year))
15563 (error
15564 (setq year (nth 5 org-defdecode))
15565 (setq org-read-date-analyze-forced-year t))))
15566 (setq org-read-date-analyze-futurep futurep)
15567 (list second minute hour day month year)))
15569 (defvar parse-time-weekdays)
15570 (defun org-read-date-get-relative (s today default)
15571 "Check string S for special relative date string.
15572 TODAY and DEFAULT are internal times, for today and for a default.
15573 Return shift list (N what def-flag)
15574 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15575 N is the number of WHATs to shift.
15576 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15577 the DEFAULT date rather than TODAY."
15578 (require 'parse-time)
15579 (when (and
15580 (string-match
15581 (concat
15582 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15583 "\\([0-9]+\\)?"
15584 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15585 "\\([ \t]\\|$\\)") s)
15586 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15587 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15588 (string-to-char (substring (match-string 1 s) -1))
15589 ?+))
15590 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15591 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15592 (what (if (match-end 3) (match-string 3 s) "d"))
15593 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15594 (date (if rel default today))
15595 (wday (nth 6 (decode-time date)))
15596 delta)
15597 (if wday1
15598 (progn
15599 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15600 (if (= dir ?-) (setq delta (- delta 7)))
15601 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15602 (list delta "d" rel))
15603 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15605 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15606 "Turn a user-specified date into the internal representation.
15607 The internal representation needed by the calendar is (month day year).
15608 This is a wrapper to handle the brain-dead convention in calendar that
15609 user function argument order change dependent on argument order."
15610 (if (boundp 'calendar-date-style)
15611 (cond
15612 ((eq calendar-date-style 'american)
15613 (list arg1 arg2 arg3))
15614 ((eq calendar-date-style 'european)
15615 (list arg2 arg1 arg3))
15616 ((eq calendar-date-style 'iso)
15617 (list arg2 arg3 arg1)))
15618 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15619 (if (org-bound-and-true-p european-calendar-style)
15620 (list arg2 arg1 arg3)
15621 (list arg1 arg2 arg3)))))
15623 (defun org-eval-in-calendar (form &optional keepdate)
15624 "Eval FORM in the calendar window and return to current window.
15625 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15626 otherwise stick to the current value of `org-ans2'."
15627 (let ((sf (selected-frame))
15628 (sw (selected-window)))
15629 (select-window (get-buffer-window "*Calendar*" t))
15630 (eval form)
15631 (when (and (not keepdate) (calendar-cursor-to-date))
15632 (let* ((date (calendar-cursor-to-date))
15633 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15634 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15635 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15636 (select-window sw)
15637 (org-select-frame-set-input-focus sf)))
15639 (defun org-calendar-select ()
15640 "Return to `org-read-date' with the date currently selected.
15641 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15642 (interactive)
15643 (when (calendar-cursor-to-date)
15644 (let* ((date (calendar-cursor-to-date))
15645 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15646 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15647 (if (active-minibuffer-window) (exit-minibuffer))))
15649 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15650 "Insert a date stamp for the date given by the internal TIME.
15651 WITH-HM means use the stamp format that includes the time of the day.
15652 INACTIVE means use square brackets instead of angular ones, so that the
15653 stamp will not contribute to the agenda.
15654 PRE and POST are optional strings to be inserted before and after the
15655 stamp.
15656 The command returns the inserted time stamp."
15657 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15658 stamp)
15659 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15660 (insert-before-markers (or pre ""))
15661 (when (listp extra)
15662 (setq extra (car extra))
15663 (if (and (stringp extra)
15664 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15665 (setq extra (format "-%02d:%02d"
15666 (string-to-number (match-string 1 extra))
15667 (string-to-number (match-string 2 extra))))
15668 (setq extra nil)))
15669 (when extra
15670 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15671 (insert-before-markers (setq stamp (format-time-string fmt time)))
15672 (insert-before-markers (or post ""))
15673 (setq org-last-inserted-timestamp stamp)))
15675 (defun org-toggle-time-stamp-overlays ()
15676 "Toggle the use of custom time stamp formats."
15677 (interactive)
15678 (setq org-display-custom-times (not org-display-custom-times))
15679 (unless org-display-custom-times
15680 (let ((p (point-min)) (bmp (buffer-modified-p)))
15681 (while (setq p (next-single-property-change p 'display))
15682 (if (and (get-text-property p 'display)
15683 (eq (get-text-property p 'face) 'org-date))
15684 (remove-text-properties
15685 p (setq p (next-single-property-change p 'display))
15686 '(display t))))
15687 (set-buffer-modified-p bmp)))
15688 (if (featurep 'xemacs)
15689 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15690 (org-restart-font-lock)
15691 (setq org-table-may-need-update t)
15692 (if org-display-custom-times
15693 (message "Time stamps are overlaid with custom format")
15694 (message "Time stamp overlays removed")))
15696 (defun org-display-custom-time (beg end)
15697 "Overlay modified time stamp format over timestamp between BEG and END."
15698 (let* ((ts (buffer-substring beg end))
15699 t1 w1 with-hm tf time str w2 (off 0))
15700 (save-match-data
15701 (setq t1 (org-parse-time-string ts t))
15702 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15703 (setq off (- (match-end 0) (match-beginning 0)))))
15704 (setq end (- end off))
15705 (setq w1 (- end beg)
15706 with-hm (and (nth 1 t1) (nth 2 t1))
15707 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15708 time (org-fix-decoded-time t1)
15709 str (org-add-props
15710 (format-time-string
15711 (substring tf 1 -1) (apply 'encode-time time))
15712 nil 'mouse-face 'highlight)
15713 w2 (length str))
15714 (if (not (= w2 w1))
15715 (add-text-properties (1+ beg) (+ 2 beg)
15716 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15717 (if (featurep 'xemacs)
15718 (progn
15719 (put-text-property beg end 'invisible t)
15720 (put-text-property beg end 'end-glyph (make-glyph str)))
15721 (put-text-property beg end 'display str))))
15723 (defun org-translate-time (string)
15724 "Translate all timestamps in STRING to custom format.
15725 But do this only if the variable `org-display-custom-times' is set."
15726 (when org-display-custom-times
15727 (save-match-data
15728 (let* ((start 0)
15729 (re org-ts-regexp-both)
15730 t1 with-hm inactive tf time str beg end)
15731 (while (setq start (string-match re string start))
15732 (setq beg (match-beginning 0)
15733 end (match-end 0)
15734 t1 (save-match-data
15735 (org-parse-time-string (substring string beg end) t))
15736 with-hm (and (nth 1 t1) (nth 2 t1))
15737 inactive (equal (substring string beg (1+ beg)) "[")
15738 tf (funcall (if with-hm 'cdr 'car)
15739 org-time-stamp-custom-formats)
15740 time (org-fix-decoded-time t1)
15741 str (format-time-string
15742 (concat
15743 (if inactive "[" "<") (substring tf 1 -1)
15744 (if inactive "]" ">"))
15745 (apply 'encode-time time))
15746 string (replace-match str t t string)
15747 start (+ start (length str)))))))
15748 string)
15750 (defun org-fix-decoded-time (time)
15751 "Set 0 instead of nil for the first 6 elements of time.
15752 Don't touch the rest."
15753 (let ((n 0))
15754 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15756 (defun org-days-to-time (timestamp-string)
15757 "Difference between TIMESTAMP-STRING and now in days."
15758 (- (time-to-days (org-time-string-to-time timestamp-string))
15759 (time-to-days (current-time))))
15761 (defun org-deadline-close (timestamp-string &optional ndays)
15762 "Is the time in TIMESTAMP-STRING close to the current date?"
15763 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15764 (and (< (org-days-to-time timestamp-string) ndays)
15765 (not (org-entry-is-done-p))))
15767 (defun org-get-wdays (ts)
15768 "Get the deadline lead time appropriate for timestring TS."
15769 (cond
15770 ((<= org-deadline-warning-days 0)
15771 ;; 0 or negative, enforce this value no matter what
15772 (- org-deadline-warning-days))
15773 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15774 ;; lead time is specified.
15775 (floor (* (string-to-number (match-string 1 ts))
15776 (cdr (assoc (match-string 2 ts)
15777 '(("d" . 1) ("w" . 7)
15778 ("m" . 30.4) ("y" . 365.25)))))))
15779 ;; go for the default.
15780 (t org-deadline-warning-days)))
15782 (defun org-calendar-select-mouse (ev)
15783 "Return to `org-read-date' with the date currently selected.
15784 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15785 (interactive "e")
15786 (mouse-set-point ev)
15787 (when (calendar-cursor-to-date)
15788 (let* ((date (calendar-cursor-to-date))
15789 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15790 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15791 (if (active-minibuffer-window) (exit-minibuffer))))
15793 (defun org-check-deadlines (ndays)
15794 "Check if there are any deadlines due or past due.
15795 A deadline is considered due if it happens within `org-deadline-warning-days'
15796 days from today's date. If the deadline appears in an entry marked DONE,
15797 it is not shown. The prefix arg NDAYS can be used to test that many
15798 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15799 (interactive "P")
15800 (let* ((org-warn-days
15801 (cond
15802 ((equal ndays '(4)) 100000)
15803 (ndays (prefix-numeric-value ndays))
15804 (t (abs org-deadline-warning-days))))
15805 (case-fold-search nil)
15806 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15807 (callback
15808 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15810 (message "%d deadlines past-due or due within %d days"
15811 (org-occur regexp nil callback)
15812 org-warn-days)))
15814 (defun org-check-before-date (date)
15815 "Check if there are deadlines or scheduled entries before DATE."
15816 (interactive (list (org-read-date)))
15817 (let ((case-fold-search nil)
15818 (regexp (concat "\\<\\(" org-deadline-string
15819 "\\|" org-scheduled-string
15820 "\\) *<\\([^>]+\\)>"))
15821 (callback
15822 (lambda () (time-less-p
15823 (org-time-string-to-time (match-string 2))
15824 (org-time-string-to-time date)))))
15825 (message "%d entries before %s"
15826 (org-occur regexp nil callback) date)))
15828 (defun org-check-after-date (date)
15829 "Check if there are deadlines or scheduled entries after DATE."
15830 (interactive (list (org-read-date)))
15831 (let ((case-fold-search nil)
15832 (regexp (concat "\\<\\(" org-deadline-string
15833 "\\|" org-scheduled-string
15834 "\\) *<\\([^>]+\\)>"))
15835 (callback
15836 (lambda () (not
15837 (time-less-p
15838 (org-time-string-to-time (match-string 2))
15839 (org-time-string-to-time date))))))
15840 (message "%d entries after %s"
15841 (org-occur regexp nil callback) date)))
15843 (defun org-check-dates-range (start-date end-date)
15844 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15845 (interactive (list (org-read-date nil nil nil "Range starts")
15846 (org-read-date nil nil nil "Range end")))
15847 (let ((case-fold-search nil)
15848 (regexp (concat "\\<\\(" org-deadline-string
15849 "\\|" org-scheduled-string
15850 "\\) *<\\([^>]+\\)>"))
15851 (callback
15852 (lambda ()
15853 (let ((match (match-string 2)))
15854 (and
15855 (not (time-less-p
15856 (org-time-string-to-time match)
15857 (org-time-string-to-time start-date)))
15858 (time-less-p
15859 (org-time-string-to-time match)
15860 (org-time-string-to-time end-date)))))))
15861 (message "%d entries between %s and %s"
15862 (org-occur regexp nil callback) start-date end-date)))
15864 (defun org-evaluate-time-range (&optional to-buffer)
15865 "Evaluate a time range by computing the difference between start and end.
15866 Normally the result is just printed in the echo area, but with prefix arg
15867 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15868 If the time range is actually in a table, the result is inserted into the
15869 next column.
15870 For time difference computation, a year is assumed to be exactly 365
15871 days in order to avoid rounding problems."
15872 (interactive "P")
15874 (org-clock-update-time-maybe)
15875 (save-excursion
15876 (unless (org-at-date-range-p t)
15877 (goto-char (point-at-bol))
15878 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15879 (if (not (org-at-date-range-p t))
15880 (error "Not at a time-stamp range, and none found in current line")))
15881 (let* ((ts1 (match-string 1))
15882 (ts2 (match-string 2))
15883 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15884 (match-end (match-end 0))
15885 (time1 (org-time-string-to-time ts1))
15886 (time2 (org-time-string-to-time ts2))
15887 (t1 (org-float-time time1))
15888 (t2 (org-float-time time2))
15889 (diff (abs (- t2 t1)))
15890 (negative (< (- t2 t1) 0))
15891 ;; (ys (floor (* 365 24 60 60)))
15892 (ds (* 24 60 60))
15893 (hs (* 60 60))
15894 (fy "%dy %dd %02d:%02d")
15895 (fy1 "%dy %dd")
15896 (fd "%dd %02d:%02d")
15897 (fd1 "%dd")
15898 (fh "%02d:%02d")
15899 y d h m align)
15900 (if havetime
15901 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15903 d (floor (/ diff ds)) diff (mod diff ds)
15904 h (floor (/ diff hs)) diff (mod diff hs)
15905 m (floor (/ diff 60)))
15906 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15908 d (floor (+ (/ diff ds) 0.5))
15909 h 0 m 0))
15910 (if (not to-buffer)
15911 (message "%s" (org-make-tdiff-string y d h m))
15912 (if (org-at-table-p)
15913 (progn
15914 (goto-char match-end)
15915 (setq align t)
15916 (and (looking-at " *|") (goto-char (match-end 0))))
15917 (goto-char match-end))
15918 (if (looking-at
15919 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15920 (replace-match ""))
15921 (if negative (insert " -"))
15922 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15923 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15924 (insert " " (format fh h m))))
15925 (if align (org-table-align))
15926 (message "Time difference inserted")))))
15928 (defun org-make-tdiff-string (y d h m)
15929 (let ((fmt "")
15930 (l nil))
15931 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15932 l (push y l)))
15933 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15934 l (push d l)))
15935 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15936 l (push h l)))
15937 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15938 l (push m l)))
15939 (apply 'format fmt (nreverse l))))
15941 (defun org-time-string-to-time (s &optional buffer pos)
15942 (condition-case errdata
15943 (apply 'encode-time (org-parse-time-string s))
15944 (error (error "Bad timestamp `%s'%s\nError was: %s"
15945 s (if (not (and buffer pos))
15947 (format " at %d in buffer `%s'" pos buffer))
15948 (cdr errdata)))))
15950 (defun org-time-string-to-seconds (s)
15951 (org-float-time (org-time-string-to-time s)))
15953 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15954 "Convert a time stamp to an absolute day number.
15955 If there is a specifier for a cyclic time stamp, get the closest date to
15956 DAYNR.
15957 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15958 The variable date is bound by the calendar when this is called."
15959 (cond
15960 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15961 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15962 daynr
15963 (+ daynr 1000)))
15964 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15965 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15966 (time-to-days (current-time))) (match-string 0 s)
15967 prefer show-all))
15968 (t (time-to-days
15969 (condition-case errdata
15970 (apply 'encode-time (org-parse-time-string s))
15971 (error (error "Bad timestamp `%s'%s\nError was: %s"
15972 s (if (not (and buffer pos))
15974 (format " at %d in buffer `%s'" pos buffer))
15975 (cdr errdata))))))))
15977 (defun org-days-to-iso-week (days)
15978 "Return the iso week number."
15979 (require 'cal-iso)
15980 (car (calendar-iso-from-absolute days)))
15982 (defun org-small-year-to-year (year)
15983 "Convert 2-digit years into 4-digit years.
15984 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15985 The year 2000 cannot be abbreviated. Any year larger than 99
15986 is returned unchanged."
15987 (if (< year 38)
15988 (setq year (+ 2000 year))
15989 (if (< year 100)
15990 (setq year (+ 1900 year))))
15991 year)
15993 (defun org-time-from-absolute (d)
15994 "Return the time corresponding to date D.
15995 D may be an absolute day number, or a calendar-type list (month day year)."
15996 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15997 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15999 (defun org-calendar-holiday ()
16000 "List of holidays, for Diary display in Org-mode."
16001 (require 'holidays)
16002 (let ((hl (funcall
16003 (if (fboundp 'calendar-check-holidays)
16004 'calendar-check-holidays 'check-calendar-holidays) date)))
16005 (if hl (mapconcat 'identity hl "; "))))
16007 (defun org-diary-sexp-entry (sexp entry date)
16008 "Process a SEXP diary ENTRY for DATE."
16009 (require 'diary-lib)
16010 (let ((result (if calendar-debug-sexp
16011 (let ((stack-trace-on-error t))
16012 (eval (car (read-from-string sexp))))
16013 (condition-case nil
16014 (eval (car (read-from-string sexp)))
16015 (error
16016 (beep)
16017 (message "Bad sexp at line %d in %s: %s"
16018 (org-current-line)
16019 (buffer-file-name) sexp)
16020 (sleep-for 2))))))
16021 (cond ((stringp result) (split-string result "; "))
16022 ((and (consp result)
16023 (not (consp (cdr result)))
16024 (stringp (cdr result))) (cdr result))
16025 ((and (consp result)
16026 (stringp (car result))) result)
16027 (result entry)
16028 (t nil))))
16030 (defun org-diary-to-ical-string (frombuf)
16031 "Get iCalendar entries from diary entries in buffer FROMBUF.
16032 This uses the icalendar.el library."
16033 (let* ((tmpdir (if (featurep 'xemacs)
16034 (temp-directory)
16035 temporary-file-directory))
16036 (tmpfile (make-temp-name
16037 (expand-file-name "orgics" tmpdir)))
16038 buf rtn b e)
16039 (with-current-buffer frombuf
16040 (icalendar-export-region (point-min) (point-max) tmpfile)
16041 (setq buf (find-buffer-visiting tmpfile))
16042 (set-buffer buf)
16043 (goto-char (point-min))
16044 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16045 (setq b (match-beginning 0)))
16046 (goto-char (point-max))
16047 (if (re-search-backward "^END:VEVENT" nil t)
16048 (setq e (match-end 0)))
16049 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16050 (kill-buffer buf)
16051 (delete-file tmpfile)
16052 rtn))
16054 (defun org-closest-date (start current change prefer show-all)
16055 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16056 When PREFER is `past', return a date that is either CURRENT or past.
16057 When PREFER is `future', return a date that is either CURRENT or future.
16058 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16059 ;; Make the proper lists from the dates
16060 (catch 'exit
16061 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16062 dn dw sday cday n1 n2 n0
16063 d m y y1 y2 date1 date2 nmonths nm ny m2)
16065 (setq start (org-date-to-gregorian start)
16066 current (org-date-to-gregorian
16067 (if show-all
16068 current
16069 (time-to-days (current-time))))
16070 sday (calendar-absolute-from-gregorian start)
16071 cday (calendar-absolute-from-gregorian current))
16073 (if (<= cday sday) (throw 'exit sday))
16075 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16076 (setq dn (string-to-number (match-string 1 change))
16077 dw (cdr (assoc (match-string 2 change) a1)))
16078 (error "Invalid change specifier: %s" change))
16079 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16080 (cond
16081 ((eq dw 'day)
16082 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16083 n2 (+ n1 dn)))
16084 ((eq dw 'year)
16085 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16086 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16087 (setq date1 (list m d y1)
16088 n1 (calendar-absolute-from-gregorian date1)
16089 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16090 n2 (calendar-absolute-from-gregorian date2)))
16091 ((eq dw 'month)
16092 ;; approx number of month between the two dates
16093 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16094 ;; How often does dn fit in there?
16095 (setq d (nth 1 start) m (car start) y (nth 2 start)
16096 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16097 m (+ m nm)
16098 ny (floor (/ m 12))
16099 y (+ y ny)
16100 m (- m (* ny 12)))
16101 (while (> m 12) (setq m (- m 12) y (1+ y)))
16102 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16103 (setq m2 (+ m dn) y2 y)
16104 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16105 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16106 (while (<= n2 cday)
16107 (setq n1 n2 m m2 y y2)
16108 (setq m2 (+ m dn) y2 y)
16109 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16110 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16111 ;; Make sure n1 is the earlier date
16112 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16113 (if show-all
16114 (cond
16115 ((eq prefer 'past) (if (= cday n2) n2 n1))
16116 ((eq prefer 'future) (if (= cday n1) n1 n2))
16117 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16118 (cond
16119 ((eq prefer 'past) (if (= cday n2) n2 n1))
16120 ((eq prefer 'future) (if (= cday n1) n1 n2))
16121 (t (if (= cday n1) n1 n2)))))))
16123 (defun org-date-to-gregorian (date)
16124 "Turn any specification of DATE into a Gregorian date for the calendar."
16125 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16126 ((and (listp date) (= (length date) 3)) date)
16127 ((stringp date)
16128 (setq date (org-parse-time-string date))
16129 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16130 ((listp date)
16131 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16133 (defun org-parse-time-string (s &optional nodefault)
16134 "Parse the standard Org-mode time string.
16135 This should be a lot faster than the normal `parse-time-string'.
16136 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16137 hour and minute fields will be nil if not given."
16138 (if (string-match org-ts-regexp0 s)
16139 (list 0
16140 (if (or (match-beginning 8) (not nodefault))
16141 (string-to-number (or (match-string 8 s) "0")))
16142 (if (or (match-beginning 7) (not nodefault))
16143 (string-to-number (or (match-string 7 s) "0")))
16144 (string-to-number (match-string 4 s))
16145 (string-to-number (match-string 3 s))
16146 (string-to-number (match-string 2 s))
16147 nil nil nil)
16148 (error "Not a standard Org-mode time string: %s" s)))
16150 (defun org-timestamp-up (&optional arg)
16151 "Increase the date item at the cursor by one.
16152 If the cursor is on the year, change the year. If it is on the month,
16153 the day or the time, change that.
16154 With prefix ARG, change by that many units."
16155 (interactive "p")
16156 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16158 (defun org-timestamp-down (&optional arg)
16159 "Decrease the date item at the cursor by one.
16160 If the cursor is on the year, change the year. If it is on the month,
16161 the day or the time, change that.
16162 With prefix ARG, change by that many units."
16163 (interactive "p")
16164 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16166 (defun org-timestamp-up-day (&optional arg)
16167 "Increase the date in the time stamp by one day.
16168 With prefix ARG, change that many days."
16169 (interactive "p")
16170 (if (and (not (org-at-timestamp-p t))
16171 (org-at-heading-p))
16172 (org-todo 'up)
16173 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16175 (defun org-timestamp-down-day (&optional arg)
16176 "Decrease the date in the time stamp by one day.
16177 With prefix ARG, change that many days."
16178 (interactive "p")
16179 (if (and (not (org-at-timestamp-p t))
16180 (org-at-heading-p))
16181 (org-todo 'down)
16182 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16184 (defun org-at-timestamp-p (&optional inactive-ok)
16185 "Determine if the cursor is in or at a timestamp."
16186 (interactive)
16187 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16188 (pos (point))
16189 (ans (or (looking-at tsr)
16190 (save-excursion
16191 (skip-chars-backward "^[<\n\r\t")
16192 (if (> (point) (point-min)) (backward-char 1))
16193 (and (looking-at tsr)
16194 (> (- (match-end 0) pos) -1))))))
16195 (and ans
16196 (boundp 'org-ts-what)
16197 (setq org-ts-what
16198 (cond
16199 ((= pos (match-beginning 0)) 'bracket)
16200 ;; Point is considered to be "on the bracket" whether
16201 ;; it's really on it or right after it.
16202 ((= pos (1- (match-end 0))) 'bracket)
16203 ((= pos (match-end 0)) 'after)
16204 ((org-pos-in-match-range pos 2) 'year)
16205 ((org-pos-in-match-range pos 3) 'month)
16206 ((org-pos-in-match-range pos 7) 'hour)
16207 ((org-pos-in-match-range pos 8) 'minute)
16208 ((or (org-pos-in-match-range pos 4)
16209 (org-pos-in-match-range pos 5)) 'day)
16210 ((and (> pos (or (match-end 8) (match-end 5)))
16211 (< pos (match-end 0)))
16212 (- pos (or (match-end 8) (match-end 5))))
16213 (t 'day))))
16214 ans))
16216 (defun org-toggle-timestamp-type ()
16217 "Toggle the type (<active> or [inactive]) of a time stamp."
16218 (interactive)
16219 (when (org-at-timestamp-p t)
16220 (let ((beg (match-beginning 0)) (end (match-end 0))
16221 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16222 (save-excursion
16223 (goto-char beg)
16224 (while (re-search-forward "[][<>]" end t)
16225 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16226 t t)))
16227 (message "Timestamp is now %sactive"
16228 (if (equal (char-after beg) ?<) "" "in")))))
16230 (defvar org-clock-history) ; defined in org-clock.el
16231 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16232 (defun org-timestamp-change (n &optional what updown)
16233 "Change the date in the time stamp at point.
16234 The date will be changed by N times WHAT. WHAT can be `day', `month',
16235 `year', `minute', `second'. If WHAT is not given, the cursor position
16236 in the timestamp determines what will be changed."
16237 (let ((origin (point)) origin-cat
16238 with-hm inactive
16239 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16240 org-ts-what
16241 extra rem
16242 ts time time0 fixnext clrgx)
16243 (if (not (org-at-timestamp-p t))
16244 (error "Not at a timestamp"))
16245 (if (and (not what) (eq org-ts-what 'bracket))
16246 (org-toggle-timestamp-type)
16247 ;; Point isn't on brackets. Remember the part of the time-stamp
16248 ;; the point was in. Indeed, size of time-stamps may change,
16249 ;; but point must be kept in the same category nonetheless.
16250 (setq origin-cat org-ts-what)
16251 (if (and (not what) (not (eq org-ts-what 'day))
16252 org-display-custom-times
16253 (get-text-property (point) 'display)
16254 (not (get-text-property (1- (point)) 'display)))
16255 (setq org-ts-what 'day))
16256 (setq org-ts-what (or what org-ts-what)
16257 inactive (= (char-after (match-beginning 0)) ?\[)
16258 ts (match-string 0))
16259 (replace-match "")
16260 (if (string-match
16261 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16263 (setq extra (match-string 1 ts)))
16264 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16265 (setq with-hm t))
16266 (setq time0 (org-parse-time-string ts))
16267 (when (and updown
16268 (eq org-ts-what 'minute)
16269 (not current-prefix-arg))
16270 ;; This looks like s-up and s-down. Change by one rounding step.
16271 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16272 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16273 (setcar (cdr time0) (+ (nth 1 time0)
16274 (if (> n 0) (- rem) (- dm rem))))))
16275 (setq time
16276 (encode-time (or (car time0) 0)
16277 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16278 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16279 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16280 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16281 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16282 (nthcdr 6 time0)))
16283 (when (and (member org-ts-what '(hour minute))
16284 extra
16285 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16286 (setq extra (org-modify-ts-extra
16287 extra
16288 (if (eq org-ts-what 'hour) 2 5)
16289 n dm)))
16290 (when (integerp org-ts-what)
16291 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16292 (if (eq what 'calendar)
16293 (let ((cal-date (org-get-date-from-calendar)))
16294 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16295 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16296 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16297 (setcar time0 (or (car time0) 0))
16298 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16299 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16300 (setq time (apply 'encode-time time0))))
16301 ;; Insert the new time-stamp, and ensure point stays in the same
16302 ;; category as before (i.e. not after the last position in that
16303 ;; category).
16304 (let ((pos (point)))
16305 ;; Stay before inserted string. `save-excursion' is of no use.
16306 (setq org-last-changed-timestamp
16307 (org-insert-time-stamp time with-hm inactive nil nil extra))
16308 (goto-char pos))
16309 (save-match-data
16310 (looking-at org-ts-regexp3)
16311 (goto-char (cond
16312 ;; `day' category ends before `hour' if any, or at
16313 ;; the end of the day name.
16314 ((eq origin-cat 'day)
16315 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16316 ((eq origin-cat 'hour) (min (match-end 7) origin))
16317 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16318 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16319 ;; `year' and `month' have both fixed size: point
16320 ;; couldn't have moved into another part.
16321 (t origin))))
16322 ;; Update clock if on a CLOCK line.
16323 (org-clock-update-time-maybe)
16324 ;; Maybe adjust the closest clock in `org-clock-history'
16325 (when org-clock-adjust-closest
16326 (if (not (and (org-at-clock-log-p)
16327 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16328 org-clock-history))))))
16329 (message "No clock to adjust")
16330 (cond ((save-excursion ; fix previous clock?
16331 (re-search-backward org-ts-regexp0 nil t)
16332 (looking-back (concat org-clock-string " \\[")))
16333 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16334 ((save-excursion ; fix next clock?
16335 (re-search-backward org-ts-regexp0 nil t)
16336 (looking-at (concat org-ts-regexp0 "\\] =>")))
16337 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16338 (save-window-excursion
16339 ;; Find closest clock to point, adjust the previous/next one in history
16340 (let* ((p (save-excursion (org-back-to-heading t)))
16341 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16342 (clfixnth
16343 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16344 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16345 (if (not clfixpos)
16346 (message "No clock to adjust")
16347 (org-goto-marker-or-bmk clfixpos)
16348 (org-show-subtree)
16349 (when (re-search-forward clrgx nil t)
16350 (goto-char (match-beginning 1))
16351 (let (org-clock-adjust-closest)
16352 (org-timestamp-change n org-ts-what updown))
16353 (message "Clock adjusted in %s for heading: %s"
16354 (file-name-nondirectory (buffer-file-name))
16355 (org-get-heading t t))))))))
16356 ;; Try to recenter the calendar window, if any.
16357 (if (and org-calendar-follow-timestamp-change
16358 (get-buffer-window "*Calendar*" t)
16359 (memq org-ts-what '(day month year)))
16360 (org-recenter-calendar (time-to-days time))))))
16362 (defun org-modify-ts-extra (s pos n dm)
16363 "Change the different parts of the lead-time and repeat fields in timestamp."
16364 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16365 ng h m new rem)
16366 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16367 (cond
16368 ((or (org-pos-in-match-range pos 2)
16369 (org-pos-in-match-range pos 3))
16370 (setq m (string-to-number (match-string 3 s))
16371 h (string-to-number (match-string 2 s)))
16372 (if (org-pos-in-match-range pos 2)
16373 (setq h (+ h n))
16374 (setq n (* dm (org-no-warnings (signum n))))
16375 (when (not (= 0 (setq rem (% m dm))))
16376 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16377 (setq m (+ m n)))
16378 (if (< m 0) (setq m (+ m 60) h (1- h)))
16379 (if (> m 59) (setq m (- m 60) h (1+ h)))
16380 (setq h (min 24 (max 0 h)))
16381 (setq ng 1 new (format "-%02d:%02d" h m)))
16382 ((org-pos-in-match-range pos 6)
16383 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16384 ((org-pos-in-match-range pos 5)
16385 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16387 ((org-pos-in-match-range pos 9)
16388 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16389 ((org-pos-in-match-range pos 8)
16390 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16392 (when ng
16393 (setq s (concat
16394 (substring s 0 (match-beginning ng))
16396 (substring s (match-end ng))))))
16399 (defun org-recenter-calendar (date)
16400 "If the calendar is visible, recenter it to DATE."
16401 (let ((cwin (get-buffer-window "*Calendar*" t)))
16402 (when cwin
16403 (let ((calendar-move-hook nil))
16404 (with-selected-window cwin
16405 (calendar-goto-date (if (listp date) date
16406 (calendar-gregorian-from-absolute date))))))))
16408 (defun org-goto-calendar (&optional arg)
16409 "Go to the Emacs calendar at the current date.
16410 If there is a time stamp in the current line, go to that date.
16411 A prefix ARG can be used to force the current date."
16412 (interactive "P")
16413 (let ((tsr org-ts-regexp) diff
16414 (calendar-move-hook nil)
16415 (calendar-view-holidays-initially-flag nil)
16416 (calendar-view-diary-initially-flag nil))
16417 (if (or (org-at-timestamp-p)
16418 (save-excursion
16419 (beginning-of-line 1)
16420 (looking-at (concat ".*" tsr))))
16421 (let ((d1 (time-to-days (current-time)))
16422 (d2 (time-to-days
16423 (org-time-string-to-time (match-string 1)))))
16424 (setq diff (- d2 d1))))
16425 (calendar)
16426 (calendar-goto-today)
16427 (if (and diff (not arg)) (calendar-forward-day diff))))
16429 (defun org-get-date-from-calendar ()
16430 "Return a list (month day year) of date at point in calendar."
16431 (with-current-buffer "*Calendar*"
16432 (save-match-data
16433 (calendar-cursor-to-date))))
16435 (defun org-date-from-calendar ()
16436 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16437 If there is already a time stamp at the cursor position, update it."
16438 (interactive)
16439 (if (org-at-timestamp-p t)
16440 (org-timestamp-change 0 'calendar)
16441 (let ((cal-date (org-get-date-from-calendar)))
16442 (org-insert-time-stamp
16443 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16445 (defun org-minutes-to-hh:mm-string (m)
16446 "Compute H:MM from a number of minutes."
16447 (let ((h (/ m 60)))
16448 (setq m (- m (* 60 h)))
16449 (format org-time-clocksum-format h m)))
16451 (defun org-hh:mm-string-to-minutes (s)
16452 "Convert a string H:MM to a number of minutes.
16453 If the string is just a number, interpret it as minutes.
16454 In fact, the first hh:mm or number in the string will be taken,
16455 there can be extra stuff in the string.
16456 If no number is found, the return value is 0."
16457 (cond
16458 ((integerp s) s)
16459 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16460 (+ (* (string-to-number (match-string 1 s)) 60)
16461 (string-to-number (match-string 2 s))))
16462 ((string-match "\\([0-9]+\\)" s)
16463 (string-to-number (match-string 1 s)))
16464 (t 0)))
16466 (defcustom org-effort-durations
16467 `(("h" . 60)
16468 ("d" . ,(* 60 8))
16469 ("w" . ,(* 60 8 5))
16470 ("m" . ,(* 60 8 5 4))
16471 ("y" . ,(* 60 8 5 40)))
16472 "Conversion factor to minutes for an effort modifier.
16474 Each entry has the form (MODIFIER . MINUTES).
16476 In an effort string, a number followed by MODIFIER is multiplied
16477 by the specified number of MINUTES to obtain an effort in
16478 minutes.
16480 For example, if the value of this variable is ((\"hours\" . 60)), then an
16481 effort string \"2hours\" is equivalent to 120 minutes."
16482 :group 'org-agenda
16483 :version "24.1"
16484 :type '(alist :key-type (string :tag "Modifier")
16485 :value-type (number :tag "Minutes")))
16487 (defun org-duration-string-to-minutes (s &optional output-to-string)
16488 "Convert a duration string S to minutes.
16490 A bare number is interpreted as minutes, modifiers can be set by
16491 customizing `org-effort-durations' (which see).
16493 Entries containing a colon are interpreted as H:MM by
16494 `org-hh:mm-string-to-minutes'."
16495 (let ((result 0)
16496 (re (concat "\\([0-9.]+\\) *\\("
16497 (regexp-opt (mapcar 'car org-effort-durations))
16498 "\\)")))
16499 (while (string-match re s)
16500 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16501 (string-to-number (match-string 1 s))))
16502 (setq s (replace-match "" nil t s)))
16503 (setq result (floor result))
16504 (incf result (org-hh:mm-string-to-minutes s))
16505 (if output-to-string (number-to-string result) result)))
16507 ;;;; Files
16509 (defun org-save-all-org-buffers ()
16510 "Save all Org-mode buffers without user confirmation."
16511 (interactive)
16512 (message "Saving all Org-mode buffers...")
16513 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16514 (when (featurep 'org-id) (org-id-locations-save))
16515 (message "Saving all Org-mode buffers... done"))
16517 (defun org-revert-all-org-buffers ()
16518 "Revert all Org-mode buffers.
16519 Prompt for confirmation when there are unsaved changes.
16520 Be sure you know what you are doing before letting this function
16521 overwrite your changes.
16523 This function is useful in a setup where one tracks org files
16524 with a version control system, to revert on one machine after pulling
16525 changes from another. I believe the procedure must be like this:
16527 1. M-x org-save-all-org-buffers
16528 2. Pull changes from the other machine, resolve conflicts
16529 3. M-x org-revert-all-org-buffers"
16530 (interactive)
16531 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16532 (error "Abort"))
16533 (save-excursion
16534 (save-window-excursion
16535 (mapc
16536 (lambda (b)
16537 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16538 (with-current-buffer b buffer-file-name))
16539 (org-pop-to-buffer-same-window b)
16540 (revert-buffer t 'no-confirm)))
16541 (buffer-list))
16542 (when (and (featurep 'org-id) org-id-track-globally)
16543 (org-id-locations-load)))))
16545 ;;;; Agenda files
16547 ;;;###autoload
16548 (defun org-switchb (&optional arg)
16549 "Switch between Org buffers.
16550 With one prefix argument, restrict available buffers to files.
16551 With two prefix arguments, restrict available buffers to agenda files.
16553 Defaults to `iswitchb' for buffer name completion.
16554 Set `org-completion-use-ido' to make it use ido instead."
16555 (interactive "P")
16556 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16557 ((equal arg '(16)) (org-buffer-list 'agenda))
16558 (t (org-buffer-list))))
16559 (org-completion-use-iswitchb org-completion-use-iswitchb)
16560 (org-completion-use-ido org-completion-use-ido))
16561 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16562 (setq org-completion-use-iswitchb t))
16563 (org-pop-to-buffer-same-window
16564 (org-icompleting-read "Org buffer: "
16565 (mapcar 'list (mapcar 'buffer-name blist))
16566 nil t))))
16568 ;;; Define some older names previously used for this functionality
16569 ;;;###autoload
16570 (defalias 'org-ido-switchb 'org-switchb)
16571 ;;;###autoload
16572 (defalias 'org-iswitchb 'org-switchb)
16574 (defun org-buffer-list (&optional predicate exclude-tmp)
16575 "Return a list of Org buffers.
16576 PREDICATE can be `export', `files' or `agenda'.
16578 export restrict the list to Export buffers.
16579 files restrict the list to buffers visiting Org files.
16580 agenda restrict the list to buffers visiting agenda files.
16582 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16583 (let* ((bfn nil)
16584 (agenda-files (and (eq predicate 'agenda)
16585 (mapcar 'file-truename (org-agenda-files t))))
16586 (filter
16587 (cond
16588 ((eq predicate 'files)
16589 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16590 ((eq predicate 'export)
16591 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16592 ((eq predicate 'agenda)
16593 (lambda (b)
16594 (with-current-buffer b
16595 (and (derived-mode-p 'org-mode)
16596 (setq bfn (buffer-file-name b))
16597 (member (file-truename bfn) agenda-files)))))
16598 (t (lambda (b) (with-current-buffer b
16599 (or (derived-mode-p 'org-mode)
16600 (string-match "\*Org .*Export"
16601 (buffer-name b)))))))))
16602 (delq nil
16603 (mapcar
16604 (lambda(b)
16605 (if (and (funcall filter b)
16606 (or (not exclude-tmp)
16607 (not (string-match "tmp" (buffer-name b)))))
16609 nil))
16610 (buffer-list)))))
16612 (defun org-agenda-files (&optional unrestricted archives)
16613 "Get the list of agenda files.
16614 Optional UNRESTRICTED means return the full list even if a restriction
16615 is currently in place.
16616 When ARCHIVES is t, include all archive files that are really being
16617 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16618 `org-agenda-archives-mode' is t."
16619 (let ((files
16620 (cond
16621 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16622 ((stringp org-agenda-files) (org-read-agenda-file-list))
16623 ((listp org-agenda-files) org-agenda-files)
16624 (t (error "Invalid value of `org-agenda-files'")))))
16625 (setq files (apply 'append
16626 (mapcar (lambda (f)
16627 (if (file-directory-p f)
16628 (directory-files
16629 f t org-agenda-file-regexp)
16630 (list f)))
16631 files)))
16632 (when org-agenda-skip-unavailable-files
16633 (setq files (delq nil
16634 (mapcar (function
16635 (lambda (file)
16636 (and (file-readable-p file) file)))
16637 files))))
16638 (when (or (eq archives t)
16639 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16640 (setq files (org-add-archive-files files)))
16641 files))
16643 (defun org-agenda-file-p (&optional file)
16644 "Return non-nil, if FILE is an agenda file.
16645 If FILE is omitted, use the file associated with the current
16646 buffer."
16647 (member (or file (buffer-file-name))
16648 (org-agenda-files t)))
16650 (defun org-edit-agenda-file-list ()
16651 "Edit the list of agenda files.
16652 Depending on setup, this either uses customize to edit the variable
16653 `org-agenda-files', or it visits the file that is holding the list. In the
16654 latter case, the buffer is set up in a way that saving it automatically kills
16655 the buffer and restores the previous window configuration."
16656 (interactive)
16657 (if (stringp org-agenda-files)
16658 (let ((cw (current-window-configuration)))
16659 (find-file org-agenda-files)
16660 (org-set-local 'org-window-configuration cw)
16661 (org-add-hook 'after-save-hook
16662 (lambda ()
16663 (set-window-configuration
16664 (prog1 org-window-configuration
16665 (kill-buffer (current-buffer))))
16666 (org-install-agenda-files-menu)
16667 (message "New agenda file list installed"))
16668 nil 'local)
16669 (message "%s" (substitute-command-keys
16670 "Edit list and finish with \\[save-buffer]")))
16671 (customize-variable 'org-agenda-files)))
16673 (defun org-store-new-agenda-file-list (list)
16674 "Set new value for the agenda file list and save it correctly."
16675 (if (stringp org-agenda-files)
16676 (let ((fe (org-read-agenda-file-list t)) b u)
16677 (while (setq b (find-buffer-visiting org-agenda-files))
16678 (kill-buffer b))
16679 (with-temp-file org-agenda-files
16680 (insert
16681 (mapconcat
16682 (lambda (f) ;; Keep un-expanded entries.
16683 (if (setq u (assoc f fe))
16684 (cdr u)
16686 list "\n")
16687 "\n")))
16688 (let ((org-mode-hook nil) (org-inhibit-startup t)
16689 (org-insert-mode-line-in-empty-file nil))
16690 (setq org-agenda-files list)
16691 (customize-save-variable 'org-agenda-files org-agenda-files))))
16693 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16694 "Read the list of agenda files from a file.
16695 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16696 filenames, used by `org-store-new-agenda-file-list' to write back
16697 un-expanded file names."
16698 (when (file-directory-p org-agenda-files)
16699 (error "`org-agenda-files' cannot be a single directory"))
16700 (when (stringp org-agenda-files)
16701 (with-temp-buffer
16702 (insert-file-contents org-agenda-files)
16703 (mapcar
16704 (lambda (f)
16705 (let ((e (expand-file-name (substitute-in-file-name f)
16706 org-directory)))
16707 (if pair-with-expansion
16708 (cons e f)
16709 e)))
16710 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16712 ;;;###autoload
16713 (defun org-cycle-agenda-files ()
16714 "Cycle through the files in `org-agenda-files'.
16715 If the current buffer visits an agenda file, find the next one in the list.
16716 If the current buffer does not, find the first agenda file."
16717 (interactive)
16718 (let* ((fs (org-agenda-files t))
16719 (files (append fs (list (car fs))))
16720 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16721 file)
16722 (unless files (error "No agenda files"))
16723 (catch 'exit
16724 (while (setq file (pop files))
16725 (if (equal (file-truename file) tcf)
16726 (when (car files)
16727 (find-file (car files))
16728 (throw 'exit t))))
16729 (find-file (car fs)))
16730 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16732 (defun org-agenda-file-to-front (&optional to-end)
16733 "Move/add the current file to the top of the agenda file list.
16734 If the file is not present in the list, it is added to the front. If it is
16735 present, it is moved there. With optional argument TO-END, add/move to the
16736 end of the list."
16737 (interactive "P")
16738 (let ((org-agenda-skip-unavailable-files nil)
16739 (file-alist (mapcar (lambda (x)
16740 (cons (file-truename x) x))
16741 (org-agenda-files t)))
16742 (ctf (file-truename buffer-file-name))
16743 x had)
16744 (setq x (assoc ctf file-alist) had x)
16746 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16747 (if to-end
16748 (setq file-alist (append (delq x file-alist) (list x)))
16749 (setq file-alist (cons x (delq x file-alist))))
16750 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16751 (org-install-agenda-files-menu)
16752 (message "File %s to %s of agenda file list"
16753 (if had "moved" "added") (if to-end "end" "front"))))
16755 (defun org-remove-file (&optional file)
16756 "Remove current file from the list of files in variable `org-agenda-files'.
16757 These are the files which are being checked for agenda entries.
16758 Optional argument FILE means use this file instead of the current."
16759 (interactive)
16760 (let* ((org-agenda-skip-unavailable-files nil)
16761 (file (or file buffer-file-name))
16762 (true-file (file-truename file))
16763 (afile (abbreviate-file-name file))
16764 (files (delq nil (mapcar
16765 (lambda (x)
16766 (if (equal true-file
16767 (file-truename x))
16768 nil x))
16769 (org-agenda-files t)))))
16770 (if (not (= (length files) (length (org-agenda-files t))))
16771 (progn
16772 (org-store-new-agenda-file-list files)
16773 (org-install-agenda-files-menu)
16774 (message "Removed file: %s" afile))
16775 (message "File was not in list: %s (not removed)" afile))))
16777 (defun org-file-menu-entry (file)
16778 (vector file (list 'find-file file) t))
16780 (defun org-check-agenda-file (file)
16781 "Make sure FILE exists. If not, ask user what to do."
16782 (when (not (file-exists-p file))
16783 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16784 (abbreviate-file-name file))
16785 (let ((r (downcase (read-char-exclusive))))
16786 (cond
16787 ((equal r ?r)
16788 (org-remove-file file)
16789 (throw 'nextfile t))
16790 (t (error "Abort"))))))
16792 (defun org-get-agenda-file-buffer (file)
16793 "Get a buffer visiting FILE. If the buffer needs to be created, add
16794 it to the list of buffers which might be released later."
16795 (let ((buf (org-find-base-buffer-visiting file)))
16796 (if buf
16797 buf ; just return it
16798 ;; Make a new buffer and remember it
16799 (setq buf (find-file-noselect file))
16800 (if buf (push buf org-agenda-new-buffers))
16801 buf)))
16803 (defun org-release-buffers (blist)
16804 "Release all buffers in list, asking the user for confirmation when needed.
16805 When a buffer is unmodified, it is just killed. When modified, it is saved
16806 \(if the user agrees) and then killed."
16807 (let (buf file)
16808 (while (setq buf (pop blist))
16809 (setq file (buffer-file-name buf))
16810 (when (and (buffer-modified-p buf)
16811 file
16812 (y-or-n-p (format "Save file %s? " file)))
16813 (with-current-buffer buf (save-buffer)))
16814 (kill-buffer buf))))
16816 (defun org-prepare-agenda-buffers (files)
16817 "Create buffers for all agenda files, protect archived trees and comments."
16818 (interactive)
16819 (let ((pa '(:org-archived t))
16820 (pc '(:org-comment t))
16821 (pall '(:org-archived t :org-comment t))
16822 (inhibit-read-only t)
16823 (rea (concat ":" org-archive-tag ":"))
16824 bmp file re)
16825 (save-excursion
16826 (save-restriction
16827 (while (setq file (pop files))
16828 (catch 'nextfile
16829 (if (bufferp file)
16830 (set-buffer file)
16831 (org-check-agenda-file file)
16832 (set-buffer (org-get-agenda-file-buffer file)))
16833 (widen)
16834 (setq bmp (buffer-modified-p))
16835 (org-refresh-category-properties)
16836 (setq org-todo-keywords-for-agenda
16837 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16838 (setq org-done-keywords-for-agenda
16839 (append org-done-keywords-for-agenda org-done-keywords))
16840 (setq org-todo-keyword-alist-for-agenda
16841 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16842 (setq org-drawers-for-agenda
16843 (append org-drawers-for-agenda org-drawers))
16844 (setq org-tag-alist-for-agenda
16845 (append org-tag-alist-for-agenda org-tag-alist))
16847 (save-excursion
16848 (remove-text-properties (point-min) (point-max) pall)
16849 (when org-agenda-skip-archived-trees
16850 (goto-char (point-min))
16851 (while (re-search-forward rea nil t)
16852 (if (org-at-heading-p t)
16853 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16854 (goto-char (point-min))
16855 (setq re (format org-heading-keyword-regexp-format
16856 org-comment-string))
16857 (while (re-search-forward re nil t)
16858 (add-text-properties
16859 (match-beginning 0) (org-end-of-subtree t) pc)))
16860 (set-buffer-modified-p bmp)))))
16861 (setq org-todo-keywords-for-agenda
16862 (org-uniquify org-todo-keywords-for-agenda))
16863 (setq org-todo-keyword-alist-for-agenda
16864 (org-uniquify org-todo-keyword-alist-for-agenda)
16865 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16867 ;;;; Embedded LaTeX
16869 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16870 "Keymap for the minor `org-cdlatex-mode'.")
16872 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16873 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16874 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16875 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16876 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16878 (defvar org-cdlatex-texmathp-advice-is-done nil
16879 "Flag remembering if we have applied the advice to texmathp already.")
16881 (define-minor-mode org-cdlatex-mode
16882 "Toggle the minor `org-cdlatex-mode'.
16883 This mode supports entering LaTeX environment and math in LaTeX fragments
16884 in Org-mode.
16885 \\{org-cdlatex-mode-map}"
16886 nil " OCDL" nil
16887 (when org-cdlatex-mode
16888 (require 'cdlatex)
16889 (run-hooks 'cdlatex-mode-hook)
16890 (cdlatex-compute-tables))
16891 (unless org-cdlatex-texmathp-advice-is-done
16892 (setq org-cdlatex-texmathp-advice-is-done t)
16893 (defadvice texmathp (around org-math-always-on activate)
16894 "Always return t in org-mode buffers.
16895 This is because we want to insert math symbols without dollars even outside
16896 the LaTeX math segments. If Orgmode thinks that point is actually inside
16897 an embedded LaTeX fragment, let texmathp do its job.
16898 \\[org-cdlatex-mode-map]"
16899 (interactive)
16900 (let (p)
16901 (cond
16902 ((not (derived-mode-p 'org-mode)) ad-do-it)
16903 ((eq this-command 'cdlatex-math-symbol)
16904 (setq ad-return-value t
16905 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16907 (let ((p (org-inside-LaTeX-fragment-p)))
16908 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16909 (setq ad-return-value t
16910 texmathp-why '("Org-mode embedded math" . 0))
16911 (if p ad-do-it)))))))))
16913 (defun turn-on-org-cdlatex ()
16914 "Unconditionally turn on `org-cdlatex-mode'."
16915 (org-cdlatex-mode 1))
16917 (defun org-inside-LaTeX-fragment-p ()
16918 "Test if point is inside a LaTeX fragment.
16919 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16920 sequence appearing also before point.
16921 Even though the matchers for math are configurable, this function assumes
16922 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16923 delimiters are skipped when they have been removed by customization.
16924 The return value is nil, or a cons cell with the delimiter and the
16925 position of this delimiter.
16927 This function does a reasonably good job, but can locally be fooled by
16928 for example currency specifications. For example it will assume being in
16929 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16930 fragments that are properly closed, but during editing, we have to live
16931 with the uncertainty caused by missing closing delimiters. This function
16932 looks only before point, not after."
16933 (catch 'exit
16934 (let ((pos (point))
16935 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16936 (lim (progn
16937 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16938 (point)))
16939 dd-on str (start 0) m re)
16940 (goto-char pos)
16941 (when dodollar
16942 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16943 re (nth 1 (assoc "$" org-latex-regexps)))
16944 (while (string-match re str start)
16945 (cond
16946 ((= (match-end 0) (length str))
16947 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16948 ((= (match-end 0) (- (length str) 5))
16949 (throw 'exit nil))
16950 (t (setq start (match-end 0))))))
16951 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16952 (goto-char pos)
16953 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16954 (and (match-beginning 2) (throw 'exit nil))
16955 ;; count $$
16956 (while (re-search-backward "\\$\\$" lim t)
16957 (setq dd-on (not dd-on)))
16958 (goto-char pos)
16959 (if dd-on (cons "$$" m))))))
16961 (defun org-inside-latex-macro-p ()
16962 "Is point inside a LaTeX macro or its arguments?"
16963 (save-match-data
16964 (org-in-regexp
16965 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16967 (defun org-try-cdlatex-tab ()
16968 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16969 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16970 - inside a LaTeX fragment, or
16971 - after the first word in a line, where an abbreviation expansion could
16972 insert a LaTeX environment."
16973 (when org-cdlatex-mode
16974 (cond
16975 ;; Before any word on the line: No expansion possible.
16976 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16977 ;; Just after first word on the line: Expand it. Make sure it
16978 ;; cannot happen on headlines, though.
16979 ((save-excursion
16980 (skip-chars-backward "a-zA-Z0-9*")
16981 (skip-chars-backward " \t")
16982 (and (bolp) (not (org-at-heading-p))))
16983 (cdlatex-tab) t)
16984 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16986 (defun org-cdlatex-underscore-caret (&optional arg)
16987 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16988 Revert to the normal definition outside of these fragments."
16989 (interactive "P")
16990 (if (org-inside-LaTeX-fragment-p)
16991 (call-interactively 'cdlatex-sub-superscript)
16992 (let (org-cdlatex-mode)
16993 (call-interactively (key-binding (vector last-input-event))))))
16995 (defun org-cdlatex-math-modify (&optional arg)
16996 "Execute `cdlatex-math-modify' in LaTeX fragments.
16997 Revert to the normal definition outside of these fragments."
16998 (interactive "P")
16999 (if (org-inside-LaTeX-fragment-p)
17000 (call-interactively 'cdlatex-math-modify)
17001 (let (org-cdlatex-mode)
17002 (call-interactively (key-binding (vector last-input-event))))))
17004 (defvar org-latex-fragment-image-overlays nil
17005 "List of overlays carrying the images of latex fragments.")
17006 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17008 (defun org-remove-latex-fragment-image-overlays ()
17009 "Remove all overlays with LaTeX fragment images in current buffer."
17010 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17011 (setq org-latex-fragment-image-overlays nil))
17013 (defun org-preview-latex-fragment (&optional subtree)
17014 "Preview the LaTeX fragment at point, or all locally or globally.
17015 If the cursor is in a LaTeX fragment, create the image and overlay
17016 it over the source code. If there is no fragment at point, display
17017 all fragments in the current text, from one headline to the next. With
17018 prefix SUBTREE, display all fragments in the current subtree. With a
17019 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17020 the cursor is before the first headline,
17021 display all fragments in the buffer.
17022 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17023 (interactive "P")
17024 (unless buffer-file-name
17025 (error "Can't preview LaTeX fragment in a non-file buffer"))
17026 (org-remove-latex-fragment-image-overlays)
17027 (save-excursion
17028 (save-restriction
17029 (let (beg end at msg)
17030 (cond
17031 ((or (equal subtree '(16))
17032 (not (save-excursion
17033 (re-search-backward org-outline-regexp-bol nil t))))
17034 (setq beg (point-min) end (point-max)
17035 msg "Creating images for buffer...%s"))
17036 ((equal subtree '(4))
17037 (org-back-to-heading)
17038 (setq beg (point) end (org-end-of-subtree t)
17039 msg "Creating images for subtree...%s"))
17041 (if (setq at (org-inside-LaTeX-fragment-p))
17042 (goto-char (max (point-min) (- (cdr at) 2)))
17043 (org-back-to-heading))
17044 (setq beg (point) end (progn (outline-next-heading) (point))
17045 msg (if at "Creating image...%s"
17046 "Creating images for entry...%s"))))
17047 (message msg "")
17048 (narrow-to-region beg end)
17049 (goto-char beg)
17050 (org-format-latex
17051 (concat "ltxpng/" (file-name-sans-extension
17052 (file-name-nondirectory
17053 buffer-file-name)))
17054 default-directory 'overlays msg at 'forbuffer
17055 org-latex-create-formula-image-program)
17056 (message msg "done. Use `C-c C-c' to remove images.")))))
17058 (defvar org-latex-regexps
17059 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17060 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17061 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17062 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17063 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17064 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17065 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17066 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17067 "Regular expressions for matching embedded LaTeX.")
17069 (defvar org-export-have-math nil) ;; dynamic scoping
17070 (defun org-format-latex (prefix &optional dir overlays msg at
17071 forbuffer processing-type)
17072 "Replace LaTeX fragments with links to an image, and produce images.
17073 Some of the options can be changed using the variable
17074 `org-format-latex-options'."
17075 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17076 (let* ((prefixnodir (file-name-nondirectory prefix))
17077 (absprefix (expand-file-name prefix dir))
17078 (todir (file-name-directory absprefix))
17079 (opt org-format-latex-options)
17080 (matchers (plist-get opt :matchers))
17081 (re-list org-latex-regexps)
17082 (org-format-latex-header-extra
17083 (plist-get (org-infile-export-plist) :latex-header-extra))
17084 (cnt 0) txt hash link beg end re e checkdir
17085 executables-checked string
17086 m n block-type block linkfile movefile ov)
17087 ;; Check the different regular expressions
17088 (while (setq e (pop re-list))
17089 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17090 block (if block-type "\n\n" ""))
17091 (when (member m matchers)
17092 (goto-char (point-min))
17093 (while (re-search-forward re nil t)
17094 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17095 (not (get-text-property (match-beginning n)
17096 'org-protected))
17097 (or (not overlays)
17098 (not (eq (get-char-property (match-beginning n)
17099 'org-overlay-type)
17100 'org-latex-overlay))))
17101 (setq org-export-have-math t)
17102 (cond
17103 ((eq processing-type 'verbatim)
17104 ;; Leave the text verbatim, just protect it
17105 (add-text-properties (match-beginning n) (match-end n)
17106 '(org-protected t)))
17107 ((eq processing-type 'mathjax)
17108 ;; Prepare for MathJax processing
17109 (setq string (match-string n))
17110 (if (member m '("$" "$1"))
17111 (save-excursion
17112 (delete-region (match-beginning n) (match-end n))
17113 (goto-char (match-beginning n))
17114 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17115 "\\)")
17116 '(org-protected t))))
17117 (add-text-properties (match-beginning n) (match-end n)
17118 '(org-protected t))))
17119 ((or (eq processing-type 'dvipng)
17120 (eq processing-type 'imagemagick))
17121 ;; Process to an image
17122 (setq txt (match-string n)
17123 beg (match-beginning n) end (match-end n)
17124 cnt (1+ cnt))
17125 (let (print-length print-level) ; make sure full list is printed
17126 (setq hash (sha1 (prin1-to-string
17127 (list org-format-latex-header
17128 org-format-latex-header-extra
17129 org-export-latex-default-packages-alist
17130 org-export-latex-packages-alist
17131 org-format-latex-options
17132 forbuffer txt)))
17133 linkfile (format "%s_%s.png" prefix hash)
17134 movefile (format "%s_%s.png" absprefix hash)))
17135 (setq link (concat block "[[file:" linkfile "]]" block))
17136 (if msg (message msg cnt))
17137 (goto-char beg)
17138 (unless checkdir ; make sure the directory exists
17139 (setq checkdir t)
17140 (or (file-directory-p todir) (make-directory todir t)))
17141 (cond
17142 ((eq processing-type 'dvipng)
17143 (unless executables-checked
17144 (org-check-external-command
17145 "latex" "needed to convert LaTeX fragments to images")
17146 (org-check-external-command
17147 "dvipng" "needed to convert LaTeX fragments to images")
17148 (setq executables-checked t))
17149 (unless (file-exists-p movefile)
17150 (org-create-formula-image-with-dvipng
17151 txt movefile opt forbuffer)))
17152 ((eq processing-type 'imagemagick)
17153 (unless executables-checked
17154 (org-check-external-command
17155 "convert" "you need to install imagemagick")
17156 (setq executables-checked t))
17157 (unless (file-exists-p movefile)
17158 (org-create-formula-image-with-imagemagick
17159 txt movefile opt forbuffer))))
17160 (if overlays
17161 (progn
17162 (mapc (lambda (o)
17163 (if (eq (overlay-get o 'org-overlay-type)
17164 'org-latex-overlay)
17165 (delete-overlay o)))
17166 (overlays-in beg end))
17167 (setq ov (make-overlay beg end))
17168 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17169 (if (featurep 'xemacs)
17170 (progn
17171 (overlay-put ov 'invisible t)
17172 (overlay-put
17173 ov 'end-glyph
17174 (make-glyph (vector 'png :file movefile))))
17175 (overlay-put
17176 ov 'display
17177 (list 'image :type 'png :file movefile :ascent 'center)))
17178 (push ov org-latex-fragment-image-overlays)
17179 (goto-char end))
17180 (delete-region beg end)
17181 (insert (org-add-props link
17182 (list 'org-latex-src
17183 (replace-regexp-in-string
17184 "\"" "" txt)
17185 'org-latex-src-embed-type
17186 (if block-type 'paragraph 'character))))))
17187 ((eq processing-type 'mathml)
17188 ;; Process to MathML
17189 (unless executables-checked
17190 (unless (save-match-data (org-format-latex-mathml-available-p))
17191 (error "LaTeX to MathML converter not configured"))
17192 (setq executables-checked t))
17193 (setq txt (match-string n)
17194 beg (match-beginning n) end (match-end n)
17195 cnt (1+ cnt))
17196 (if msg (message msg cnt))
17197 (goto-char beg)
17198 (delete-region beg end)
17199 (insert (org-format-latex-as-mathml
17200 txt block-type prefix dir)))
17202 (error "Unknown conversion type %s for latex fragments"
17203 processing-type)))))))))
17205 (defun org-create-math-formula (latex-frag &optional mathml-file)
17206 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17207 Use `org-latex-to-mathml-convert-command'. If the conversion is
17208 sucessful, return the portion between \"<math...> </math>\"
17209 elements otherwise return nil. When MATHML-FILE is specified,
17210 write the results in to that file. When invoked as an
17211 interactive command, prompt for LATEX-FRAG, with initial value
17212 set to the current active region and echo the results for user
17213 inspection."
17214 (interactive (list (let ((frag (when (region-active-p)
17215 (buffer-substring-no-properties
17216 (region-beginning) (region-end)))))
17217 (read-string "LaTeX Fragment: " frag nil frag))))
17218 (unless latex-frag (error "Invalid latex-frag"))
17219 (let* ((tmp-in-file (file-relative-name
17220 (make-temp-name (expand-file-name "ltxmathml-in"))))
17221 (ignore (write-region latex-frag nil tmp-in-file))
17222 (tmp-out-file (file-relative-name
17223 (make-temp-name (expand-file-name "ltxmathml-out"))))
17224 (cmd (format-spec
17225 org-latex-to-mathml-convert-command
17226 `((?j . ,(shell-quote-argument
17227 (expand-file-name org-latex-to-mathml-jar-file)))
17228 (?I . ,(shell-quote-argument tmp-in-file))
17229 (?o . ,(shell-quote-argument tmp-out-file)))))
17230 mathml shell-command-output)
17231 (when (org-called-interactively-p 'any)
17232 (unless (org-format-latex-mathml-available-p)
17233 (error "LaTeX to MathML converter not configured")))
17234 (message "Running %s" cmd)
17235 (setq shell-command-output (shell-command-to-string cmd))
17236 (setq mathml
17237 (when (file-readable-p tmp-out-file)
17238 (with-current-buffer (find-file-noselect tmp-out-file t)
17239 (goto-char (point-min))
17240 (when (re-search-forward
17241 (concat
17242 (regexp-quote
17243 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17244 "\\(.\\|\n\\)*"
17245 (regexp-quote "</math>")) nil t)
17246 (prog1 (match-string 0) (kill-buffer))))))
17247 (cond
17248 (mathml
17249 (setq mathml
17250 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17251 (when mathml-file
17252 (write-region mathml nil mathml-file))
17253 (when (org-called-interactively-p 'any)
17254 (message mathml)))
17255 ((message "LaTeX to MathML conversion failed")
17256 (message shell-command-output)))
17257 (delete-file tmp-in-file)
17258 (when (file-exists-p tmp-out-file)
17259 (delete-file tmp-out-file))
17260 mathml))
17262 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17263 prefix &optional dir)
17264 "Use `org-create-math-formula' but check local cache first."
17265 (let* ((absprefix (expand-file-name prefix dir))
17266 (print-length nil) (print-level nil)
17267 (formula-id (concat
17268 "formula-"
17269 (sha1
17270 (prin1-to-string
17271 (list latex-frag
17272 org-latex-to-mathml-convert-command)))))
17273 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17274 (formula-cache-dir (file-name-directory formula-cache)))
17276 (unless (file-directory-p formula-cache-dir)
17277 (make-directory formula-cache-dir t))
17279 (unless (file-exists-p formula-cache)
17280 (org-create-math-formula latex-frag formula-cache))
17282 (if (file-exists-p formula-cache)
17283 ;; Successful conversion. Return the link to MathML file.
17284 (org-add-props
17285 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17286 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17287 'org-latex-src-embed-type (if latex-frag-type
17288 'paragraph 'character)))
17289 ;; Failed conversion. Return the LaTeX fragment verbatim
17290 (add-text-properties
17291 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17292 latex-frag)))
17294 ;; This function borrows from Ganesh Swami's latex2png.el
17295 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17296 "This calls dvipng."
17297 (require 'org-latex)
17298 (let* ((tmpdir (if (featurep 'xemacs)
17299 (temp-directory)
17300 temporary-file-directory))
17301 (texfilebase (make-temp-name
17302 (expand-file-name "orgtex" tmpdir)))
17303 (texfile (concat texfilebase ".tex"))
17304 (dvifile (concat texfilebase ".dvi"))
17305 (pngfile (concat texfilebase ".png"))
17306 (fnh (if (featurep 'xemacs)
17307 (font-height (face-font 'default))
17308 (face-attribute 'default :height nil)))
17309 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17310 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17311 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17312 "Black"))
17313 (bg (or (plist-get options (if buffer :background :html-background))
17314 "Transparent")))
17315 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17316 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17317 (with-temp-file texfile
17318 (insert (org-splice-latex-header
17319 org-format-latex-header
17320 org-export-latex-default-packages-alist
17321 org-export-latex-packages-alist t
17322 org-format-latex-header-extra))
17323 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17324 (require 'org-latex)
17325 (org-export-latex-fix-inputenc))
17326 (let ((dir default-directory))
17327 (condition-case nil
17328 (progn
17329 (cd tmpdir)
17330 (call-process "latex" nil nil nil texfile))
17331 (error nil))
17332 (cd dir))
17333 (if (not (file-exists-p dvifile))
17334 (progn (message "Failed to create dvi file from %s" texfile) nil)
17335 (condition-case nil
17336 (if (featurep 'xemacs)
17337 (call-process "dvipng" nil nil nil
17338 "-fg" fg "-bg" bg
17339 "-T" "tight"
17340 "-o" pngfile
17341 dvifile)
17342 (call-process "dvipng" nil nil nil
17343 "-fg" fg "-bg" bg
17344 "-D" dpi
17345 ;;"-x" scale "-y" scale
17346 "-T" "tight"
17347 "-o" pngfile
17348 dvifile))
17349 (error nil))
17350 (if (not (file-exists-p pngfile))
17351 (if org-format-latex-signal-error
17352 (error "Failed to create png file from %s" texfile)
17353 (message "Failed to create png file from %s" texfile)
17354 nil)
17355 ;; Use the requested file name and clean up
17356 (copy-file pngfile tofile 'replace)
17357 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17358 (if (file-exists-p (concat texfilebase e))
17359 (delete-file (concat texfilebase e))))
17360 pngfile))))
17362 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17363 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17364 "This calls convert, which is included into imagemagick."
17365 (require 'org-latex)
17366 (let* ((tmpdir (if (featurep 'xemacs)
17367 (temp-directory)
17368 temporary-file-directory))
17369 (texfilebase (make-temp-name
17370 (expand-file-name "orgtex" tmpdir)))
17371 (texfile (concat texfilebase ".tex"))
17372 (pdffile (concat texfilebase ".pdf"))
17373 (pngfile (concat texfilebase ".png"))
17374 (fnh (if (featurep 'xemacs)
17375 (font-height (face-font 'default))
17376 (face-attribute 'default :height nil)))
17377 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17378 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17379 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17380 "black"))
17381 (bg (or (plist-get options (if buffer :background :html-background))
17382 "white")))
17383 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17384 (setq fg (org-latex-color-format fg)))
17385 (if (eq bg 'default) (setq bg (org-latex-color :background))
17386 (setq bg (org-latex-color-format
17387 (if (string= bg "Transparent")(setq bg "white")))))
17388 (with-temp-file texfile
17389 (insert (org-splice-latex-header
17390 org-format-latex-header
17391 org-export-latex-default-packages-alist
17392 org-export-latex-packages-alist t
17393 org-format-latex-header-extra))
17394 (insert "\n\\begin{document}\n"
17395 "\\definecolor{fg}{rgb}{" fg "}\n"
17396 "\\definecolor{bg}{rgb}{" bg "}\n"
17397 "\n\\pagecolor{bg}\n"
17398 "\n{\\color{fg}\n"
17399 string
17400 "\n}\n"
17401 "\n\\end{document}\n" )
17402 (require 'org-latex)
17403 (org-export-latex-fix-inputenc))
17404 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17405 (condition-case nil
17406 (progn
17407 (cd tmpdir)
17408 (setq cmds org-latex-to-pdf-process)
17409 (while cmds
17410 (setq latex-frags-cmds (pop cmds))
17411 (if (listp latex-frags-cmds)
17412 (setq cmds nil)
17413 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17414 (while latex-frags-cmds
17415 (setq cmd (pop latex-frags-cmds))
17416 (while (string-match "%b" cmd)
17417 (setq cmd (replace-match
17418 (save-match-data
17419 (shell-quote-argument texfile))
17420 t t cmd)))
17421 (while (string-match "%f" cmd)
17422 (setq cmd (replace-match
17423 (save-match-data
17424 (shell-quote-argument (file-name-nondirectory texfile)))
17425 t t cmd)))
17426 (while (string-match "%o" cmd)
17427 (setq cmd (replace-match
17428 (save-match-data
17429 (shell-quote-argument (file-name-directory texfile)))
17430 t t cmd)))
17431 (setq cmd (split-string cmd))
17432 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17433 (error nil))
17434 (cd dir))
17435 (if (not (file-exists-p pdffile))
17436 (progn (message "Failed to create pdf file from %s" texfile) nil)
17437 (condition-case nil
17438 (if (featurep 'xemacs)
17439 (call-process "convert" nil nil nil
17440 "-density" "96"
17441 "-trim"
17442 "-antialias"
17443 pdffile
17444 "-quality" "100"
17445 ;; "-sharpen" "0x1.0"
17446 pngfile)
17447 (call-process "convert" nil nil nil
17448 "-density" dpi
17449 "-trim"
17450 "-antialias"
17451 pdffile
17452 "-quality" "100"
17453 ; "-sharpen" "0x1.0"
17454 pngfile))
17455 (error nil))
17456 (if (not (file-exists-p pngfile))
17457 (if org-format-latex-signal-error
17458 (error "Failed to create png file from %s" texfile)
17459 (message "Failed to create png file from %s" texfile)
17460 nil)
17461 ;; Use the requested file name and clean up
17462 (copy-file pngfile tofile 'replace)
17463 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17464 (if (file-exists-p (concat texfilebase e))
17465 (delete-file (concat texfilebase e))))
17466 pngfile))))
17468 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17469 "Fill a LaTeX header template TPL.
17470 In the template, the following place holders will be recognized:
17472 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17473 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17474 [PACKAGES] \\usepackage statements for PKG
17475 [NO-PACKAGES] do not include PKG
17476 [EXTRA] the string EXTRA
17477 [NO-EXTRA] do not include EXTRA
17479 For backward compatibility, if both the positive and the negative place
17480 holder is missing, the positive one (without the \"NO-\") will be
17481 assumed to be present at the end of the template.
17482 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17483 EXTRA is a string.
17484 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17485 (let (rpl (end ""))
17486 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17487 (setq rpl (if (or (match-end 1) (not def-pkg))
17488 "" (org-latex-packages-to-string def-pkg snippets-p t))
17489 tpl (replace-match rpl t t tpl))
17490 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17492 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17493 (setq rpl (if (or (match-end 1) (not pkg))
17494 "" (org-latex-packages-to-string pkg snippets-p t))
17495 tpl (replace-match rpl t t tpl))
17496 (if pkg (setq end
17497 (concat end "\n"
17498 (org-latex-packages-to-string pkg snippets-p)))))
17500 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17501 (setq rpl (if (or (match-end 1) (not extra))
17502 "" (concat extra "\n"))
17503 tpl (replace-match rpl t t tpl))
17504 (if (and extra (string-match "\\S-" extra))
17505 (setq end (concat end "\n" extra))))
17507 (if (string-match "\\S-" end)
17508 (concat tpl "\n" end)
17509 tpl)))
17511 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17512 "Turn an alist of packages into a string with the \\usepackage macros."
17513 (setq pkg (mapconcat (lambda(p)
17514 (cond
17515 ((stringp p) p)
17516 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17517 (format "%% Package %s omitted" (cadr p)))
17518 ((equal "" (car p))
17519 (format "\\usepackage{%s}" (cadr p)))
17521 (format "\\usepackage[%s]{%s}"
17522 (car p) (cadr p)))))
17524 "\n"))
17525 (if newline (concat pkg "\n") pkg))
17527 (defun org-dvipng-color (attr)
17528 "Return a RGB color specification for dvipng."
17529 (apply 'format "rgb %s %s %s"
17530 (mapcar 'org-normalize-color
17531 (if (featurep 'xemacs)
17532 (color-rgb-components
17533 (face-property 'default
17534 (cond ((eq attr :foreground) 'foreground)
17535 ((eq attr :background) 'background))))
17536 (color-values (face-attribute 'default attr nil))))))
17538 (defun org-latex-color (attr)
17539 "Return a RGB color for the LaTeX color package."
17540 (apply 'format "%s,%s,%s"
17541 (mapcar 'org-normalize-color
17542 (if (featurep 'xemacs)
17543 (color-rgb-components
17544 (face-property 'default
17545 (cond ((eq attr :foreground) 'foreground)
17546 ((eq attr :background) 'background))))
17547 (color-values (face-attribute 'default attr nil))))))
17549 (defun org-latex-color-format (color-name)
17550 "Convert COLOR-NAME to a RGB color value."
17551 (apply 'format "%s,%s,%s"
17552 (mapcar 'org-normalize-color
17553 (color-values color-name))))
17555 (defun org-normalize-color (value)
17556 "Return string to be used as color value for an RGB component."
17557 (format "%g" (/ value 65535.0)))
17559 ;; Image display
17562 (defvar org-inline-image-overlays nil)
17563 (make-variable-buffer-local 'org-inline-image-overlays)
17565 (defun org-toggle-inline-images (&optional include-linked)
17566 "Toggle the display of inline images.
17567 INCLUDE-LINKED is passed to `org-display-inline-images'."
17568 (interactive "P")
17569 (if org-inline-image-overlays
17570 (progn
17571 (org-remove-inline-images)
17572 (message "Inline image display turned off"))
17573 (org-display-inline-images include-linked)
17574 (if org-inline-image-overlays
17575 (message "%d images displayed inline"
17576 (length org-inline-image-overlays))
17577 (message "No images to display inline"))))
17579 (defun org-display-inline-images (&optional include-linked refresh beg end)
17580 "Display inline images.
17581 Normally only links without a description part are inlined, because this
17582 is how it will work for export. When INCLUDE-LINKED is set, also links
17583 with a description part will be inlined. This can be nice for a quick
17584 look at those images, but it does not reflect what exported files will look
17585 like.
17586 When REFRESH is set, refresh existing images between BEG and END.
17587 This will create new image displays only if necessary.
17588 BEG and END default to the buffer boundaries."
17589 (interactive "P")
17590 (unless refresh
17591 (org-remove-inline-images)
17592 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17593 (save-excursion
17594 (save-restriction
17595 (widen)
17596 (setq beg (or beg (point-min)) end (or end (point-max)))
17597 (goto-char beg)
17598 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17599 (substring (org-image-file-name-regexp) 0 -2)
17600 "\\)\\]" (if include-linked "" "\\]")))
17601 old file ov img)
17602 (while (re-search-forward re end t)
17603 (setq old (get-char-property-and-overlay (match-beginning 1)
17604 'org-image-overlay))
17605 (setq file (expand-file-name
17606 (concat (or (match-string 3) "") (match-string 4))))
17607 (when (file-exists-p file)
17608 (if (and (car-safe old) refresh)
17609 (image-refresh (overlay-get (cdr old) 'display))
17610 (setq img (save-match-data (create-image file)))
17611 (when img
17612 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17613 (overlay-put ov 'display img)
17614 (overlay-put ov 'face 'default)
17615 (overlay-put ov 'org-image-overlay t)
17616 (overlay-put ov 'modification-hooks
17617 (list 'org-display-inline-modification-hook))
17618 (push ov org-inline-image-overlays)))))))))
17620 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17621 "Remove inline-display overlay if a corresponding region is modified."
17622 (let ((inhibit-modification-hooks t))
17623 (when (and ov after)
17624 (delete ov org-inline-image-overlays)
17625 (delete-overlay ov))))
17627 (defun org-remove-inline-images ()
17628 "Remove inline display of images."
17629 (interactive)
17630 (mapc 'delete-overlay org-inline-image-overlays)
17631 (setq org-inline-image-overlays nil))
17633 ;;;; Key bindings
17635 ;; Outline functions from `outline-mode-prefix-map'
17636 ;; that can be remapped in Org:
17637 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17638 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17639 (define-key org-mode-map [remap outline-forward-same-level]
17640 'org-forward-same-level)
17641 (define-key org-mode-map [remap outline-backward-same-level]
17642 'org-backward-same-level)
17643 (define-key org-mode-map [remap show-branches]
17644 'org-kill-note-or-show-branches)
17645 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17646 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17647 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17649 ;; Outline functions from `outline-mode-prefix-map' that can not
17650 ;; be remapped in Org:
17652 ;; - the column "key binding" shows whether the Outline function is still
17653 ;; available in Org mode on the same key that it has been bound to in
17654 ;; Outline mode:
17655 ;; - "overridden": key used for a different functionality in Org mode
17656 ;; - else: key still bound to the same Outline function in Org mode
17658 ;; | Outline function | key binding | Org replacement |
17659 ;; |------------------------------------+-------------+-----------------------|
17660 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17661 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17662 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17663 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17664 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17665 ;; | `show-entry' | overridden | no replacement |
17666 ;; | `show-children' | `C-c C-i' | visibility cycling |
17667 ;; | `show-branches' | `C-c C-k' | still same function |
17668 ;; | `show-subtree' | overridden | visibility cycling |
17669 ;; | `show-all' | overridden | no replacement |
17670 ;; | `hide-subtree' | overridden | visibility cycling |
17671 ;; | `hide-body' | overridden | no replacement |
17672 ;; | `hide-entry' | overridden | visibility cycling |
17673 ;; | `hide-leaves' | overridden | no replacement |
17674 ;; | `hide-sublevels' | overridden | no replacement |
17675 ;; | `hide-other' | overridden | no replacement |
17677 ;; Make `C-c C-x' a prefix key
17678 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17680 ;; TAB key with modifiers
17681 (org-defkey org-mode-map "\C-i" 'org-cycle)
17682 (org-defkey org-mode-map [(tab)] 'org-cycle)
17683 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17684 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17685 ;; The following line is necessary under Suse GNU/Linux
17686 (unless (featurep 'xemacs)
17687 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17688 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17689 (define-key org-mode-map [backtab] 'org-shifttab)
17691 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17692 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17693 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17695 ;; Cursor keys with modifiers
17696 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17697 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17698 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17699 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17701 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17702 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17703 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17704 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17706 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17707 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17708 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17709 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17711 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17712 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17713 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17714 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17716 ;; Babel keys
17717 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17718 (mapc (lambda (pair)
17719 (define-key org-babel-map (car pair) (cdr pair)))
17720 org-babel-key-bindings)
17722 ;;; Extra keys for tty access.
17723 ;; We only set them when really needed because otherwise the
17724 ;; menus don't show the simple keys
17726 (when (or org-use-extra-keys
17727 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17728 (not window-system))
17729 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17730 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17731 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17732 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17733 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17734 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17735 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17736 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17737 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17738 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17739 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17740 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17741 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17742 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17743 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17744 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17745 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17746 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17747 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17748 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17749 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17750 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17751 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17752 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17753 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17754 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17755 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17756 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17758 ;; All the other keys
17760 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17761 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17762 (if (boundp 'narrow-map)
17763 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17764 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17765 (if (boundp 'narrow-map)
17766 (org-defkey narrow-map "b" 'org-narrow-to-block)
17767 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17768 (if (boundp 'narrow-map)
17769 (org-defkey narrow-map "e" 'org-narrow-to-element)
17770 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17771 (org-defkey org-mode-map "\C-\M-t" 'org-element-transpose)
17772 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17773 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17774 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17775 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17776 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17777 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17778 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17779 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17780 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17781 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17782 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17783 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17784 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17785 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17786 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17787 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17788 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17789 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17790 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17791 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17792 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17793 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17794 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17795 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17796 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17797 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17798 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17799 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17800 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17801 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17802 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17803 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17804 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17805 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17806 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17807 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17808 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17809 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17810 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17811 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17812 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17813 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17814 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17815 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17816 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17817 (org-defkey org-mode-map "\C-c^" 'org-sort)
17818 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17819 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17820 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17821 (org-defkey org-mode-map "\C-m" 'org-return)
17822 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17823 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17824 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17825 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17826 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17827 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17828 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17829 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17830 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17831 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17832 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17833 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17834 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17835 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17836 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17837 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17838 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17839 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17840 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17841 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17842 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17843 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17844 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17846 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17847 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17848 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17849 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17851 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17852 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17853 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17854 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
17855 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17856 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17857 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17858 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17859 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17860 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17861 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17862 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17863 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17864 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17865 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17866 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17867 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
17868 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17869 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17870 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17871 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17873 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17874 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17875 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17876 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17877 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17879 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17881 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17883 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17884 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17886 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17889 (when (featurep 'xemacs)
17890 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17893 (defconst org-speed-commands-default
17895 ("Outline Navigation")
17896 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17897 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17898 ("f" . (org-speed-move-safe 'org-forward-same-level))
17899 ("b" . (org-speed-move-safe 'org-backward-same-level))
17900 ("u" . (org-speed-move-safe 'outline-up-heading))
17901 ("j" . org-goto)
17902 ("g" . (org-refile t))
17903 ("Outline Visibility")
17904 ("c" . org-cycle)
17905 ("C" . org-shifttab)
17906 (" " . org-display-outline-path)
17907 (":" . org-columns)
17908 ("Outline Structure Editing")
17909 ("U" . org-shiftmetaup)
17910 ("D" . org-shiftmetadown)
17911 ("r" . org-metaright)
17912 ("l" . org-metaleft)
17913 ("R" . org-shiftmetaright)
17914 ("L" . org-shiftmetaleft)
17915 ("i" . (progn (forward-char 1) (call-interactively
17916 'org-insert-heading-respect-content)))
17917 ("^" . org-sort)
17918 ("w" . org-refile)
17919 ("a" . org-archive-subtree-default-with-confirmation)
17920 ("." . org-mark-subtree)
17921 ("#" . org-toggle-comment)
17922 ("Clock Commands")
17923 ("I" . org-clock-in)
17924 ("O" . org-clock-out)
17925 ("Meta Data Editing")
17926 ("t" . org-todo)
17927 ("0" . (org-priority ?\ ))
17928 ("1" . (org-priority ?A))
17929 ("2" . (org-priority ?B))
17930 ("3" . (org-priority ?C))
17931 (";" . org-set-tags-command)
17932 ("e" . org-set-effort)
17933 ("E" . org-inc-effort)
17934 ("Agenda Views etc")
17935 ("v" . org-agenda)
17936 ("/" . org-sparse-tree)
17937 ("Misc")
17938 ("o" . org-open-at-point)
17939 ("?" . org-speed-command-help)
17940 ("<" . (org-agenda-set-restriction-lock 'subtree))
17941 (">" . (org-agenda-remove-restriction-lock))
17943 "The default speed commands.")
17945 (defun org-print-speed-command (e)
17946 (if (> (length (car e)) 1)
17947 (progn
17948 (princ "\n")
17949 (princ (car e))
17950 (princ "\n")
17951 (princ (make-string (length (car e)) ?-))
17952 (princ "\n"))
17953 (princ (car e))
17954 (princ " ")
17955 (if (symbolp (cdr e))
17956 (princ (symbol-name (cdr e)))
17957 (prin1 (cdr e)))
17958 (princ "\n")))
17960 (defun org-speed-command-help ()
17961 "Show the available speed commands."
17962 (interactive)
17963 (if (not org-use-speed-commands)
17964 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17965 (with-output-to-temp-buffer "*Help*"
17966 (princ "User-defined Speed commands\n===========================\n")
17967 (mapc 'org-print-speed-command org-speed-commands-user)
17968 (princ "\n")
17969 (princ "Built-in Speed commands\n=======================\n")
17970 (mapc 'org-print-speed-command org-speed-commands-default))
17971 (with-current-buffer "*Help*"
17972 (setq truncate-lines t))))
17974 (defun org-speed-move-safe (cmd)
17975 "Execute CMD, but make sure that the cursor always ends up in a headline.
17976 If not, return to the original position and throw an error."
17977 (interactive)
17978 (let ((pos (point)))
17979 (call-interactively cmd)
17980 (unless (and (bolp) (org-at-heading-p))
17981 (goto-char pos)
17982 (error "Boundary reached while executing %s" cmd))))
17984 (defvar org-self-insert-command-undo-counter 0)
17986 (defvar org-table-auto-blank-field) ; defined in org-table.el
17987 (defvar org-speed-command nil)
17989 (defun org-speed-command-default-hook (keys)
17990 "Hook for activating single-letter speed commands.
17991 `org-speed-commands-default' specifies a minimal command set.
17992 Use `org-speed-commands-user' for further customization."
17993 (when (or (and (bolp) (looking-at org-outline-regexp))
17994 (and (functionp org-use-speed-commands)
17995 (funcall org-use-speed-commands)))
17996 (cdr (assoc keys (append org-speed-commands-user
17997 org-speed-commands-default)))))
17999 (defun org-babel-speed-command-hook (keys)
18000 "Hook for activating single-letter code block commands."
18001 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18002 (cdr (assoc keys org-babel-key-bindings))))
18004 (defcustom org-speed-command-hook
18005 '(org-speed-command-default-hook org-babel-speed-command-hook)
18006 "Hook for activating speed commands at strategic locations.
18007 Hook functions are called in sequence until a valid handler is
18008 found.
18010 Each hook takes a single argument, a user-pressed command key
18011 which is also a `self-insert-command' from the global map.
18013 Within the hook, examine the cursor position and the command key
18014 and return nil or a valid handler as appropriate. Handler could
18015 be one of an interactive command, a function, or a form.
18017 Set `org-use-speed-commands' to non-nil value to enable this
18018 hook. The default setting is `org-speed-command-default-hook'."
18019 :group 'org-structure
18020 :version "24.1"
18021 :type 'hook)
18023 (defun org-self-insert-command (N)
18024 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18025 If the cursor is in a table looking at whitespace, the whitespace is
18026 overwritten, and the table is not marked as requiring realignment."
18027 (interactive "p")
18028 (org-check-before-invisible-edit 'insert)
18029 (cond
18030 ((and org-use-speed-commands
18031 (setq org-speed-command
18032 (run-hook-with-args-until-success
18033 'org-speed-command-hook (this-command-keys))))
18034 (cond
18035 ((commandp org-speed-command)
18036 (setq this-command org-speed-command)
18037 (call-interactively org-speed-command))
18038 ((functionp org-speed-command)
18039 (funcall org-speed-command))
18040 ((and org-speed-command (listp org-speed-command))
18041 (eval org-speed-command))
18042 (t (let (org-use-speed-commands)
18043 (call-interactively 'org-self-insert-command)))))
18044 ((and
18045 (org-table-p)
18046 (progn
18047 ;; check if we blank the field, and if that triggers align
18048 (and (featurep 'org-table) org-table-auto-blank-field
18049 (member last-command
18050 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18051 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18052 ;; got extra space, this field does not determine column width
18053 (let (org-table-may-need-update) (org-table-blank-field))
18054 ;; no extra space, this field may determine column width
18055 (org-table-blank-field)))
18057 (eq N 1)
18058 (looking-at "[^|\n]* |"))
18059 (let (org-table-may-need-update)
18060 (goto-char (1- (match-end 0)))
18061 (backward-delete-char 1)
18062 (goto-char (match-beginning 0))
18063 (self-insert-command N)))
18065 (setq org-table-may-need-update t)
18066 (self-insert-command N)
18067 (org-fix-tags-on-the-fly)
18068 (if org-self-insert-cluster-for-undo
18069 (if (not (eq last-command 'org-self-insert-command))
18070 (setq org-self-insert-command-undo-counter 1)
18071 (if (>= org-self-insert-command-undo-counter 20)
18072 (setq org-self-insert-command-undo-counter 1)
18073 (and (> org-self-insert-command-undo-counter 0)
18074 buffer-undo-list (listp buffer-undo-list)
18075 (not (cadr buffer-undo-list)) ; remove nil entry
18076 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18077 (setq org-self-insert-command-undo-counter
18078 (1+ org-self-insert-command-undo-counter))))))))
18080 (defun org-check-before-invisible-edit (kind)
18081 "Check is editing if kind KIND would be dangerous with invisible text around.
18082 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18083 ;; First, try to get out of here as quickly as possible, to reduce overhead
18084 (if (and org-catch-invisible-edits
18085 (or (not (boundp 'visible-mode)) (not visible-mode))
18086 (or (get-char-property (point) 'invisible)
18087 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18088 ;; OK, we need to take a closer look
18089 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18090 (invisible-before-point (if (bobp) nil (get-char-property
18091 (1- (point)) 'invisible)))
18092 (border-and-ok-direction
18094 ;; Check if we are acting predictably before invisible text
18095 (and invisible-at-point (not invisible-before-point)
18096 (memq kind '(insert delete-backward)))
18097 ;; Check if we are acting predictably after invisible text
18098 ;; This works not well, and I have turned it off. It seems
18099 ;; better to always show and stop after invisible text.
18100 ;; (and (not invisible-at-point) invisible-before-point
18101 ;; (memq kind '(insert delete)))
18104 (when (or (memq invisible-at-point '(outline org-hide-block))
18105 (memq invisible-before-point '(outline org-hide-block)))
18106 (if (eq org-catch-invisible-edits 'error)
18107 (error "Editing in invisible areas is prohibited - make visible first"))
18108 ;; Make the area visible
18109 (save-excursion
18110 (if invisible-before-point
18111 (goto-char (previous-single-char-property-change
18112 (point) 'invisible)))
18113 (org-cycle))
18114 (cond
18115 ((eq org-catch-invisible-edits 'show)
18116 ;; That's it, we do the edit after showing
18117 (message
18118 "Unfolding invisible region around point before editing")
18119 (sit-for 1))
18120 ((and (eq org-catch-invisible-edits 'smart)
18121 border-and-ok-direction)
18122 (message "Unfolding invisible region around point before editing"))
18124 ;; Don't do the edit, make the user repeat it in full visibility
18125 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18127 (defun org-fix-tags-on-the-fly ()
18128 (when (and (equal (char-after (point-at-bol)) ?*)
18129 (org-at-heading-p))
18130 (org-align-tags-here org-tags-column)))
18132 (defun org-delete-backward-char (N)
18133 "Like `delete-backward-char', insert whitespace at field end in tables.
18134 When deleting backwards, in tables this function will insert whitespace in
18135 front of the next \"|\" separator, to keep the table aligned. The table will
18136 still be marked for re-alignment if the field did fill the entire column,
18137 because, in this case the deletion might narrow the column."
18138 (interactive "p")
18139 (org-check-before-invisible-edit 'delete-backward)
18140 (if (and (org-table-p)
18141 (eq N 1)
18142 (string-match "|" (buffer-substring (point-at-bol) (point)))
18143 (looking-at ".*?|"))
18144 (let ((pos (point))
18145 (noalign (looking-at "[^|\n\r]* |"))
18146 (c org-table-may-need-update))
18147 (backward-delete-char N)
18148 (if (not overwrite-mode)
18149 (progn
18150 (skip-chars-forward "^|")
18151 (insert " ")
18152 (goto-char (1- pos))))
18153 ;; noalign: if there were two spaces at the end, this field
18154 ;; does not determine the width of the column.
18155 (if noalign (setq org-table-may-need-update c)))
18156 (backward-delete-char N)
18157 (org-fix-tags-on-the-fly)))
18159 (defun org-delete-char (N)
18160 "Like `delete-char', but insert whitespace at field end in tables.
18161 When deleting characters, in tables this function will insert whitespace in
18162 front of the next \"|\" separator, to keep the table aligned. The table will
18163 still be marked for re-alignment if the field did fill the entire column,
18164 because, in this case the deletion might narrow the column."
18165 (interactive "p")
18166 (org-check-before-invisible-edit 'delete)
18167 (if (and (org-table-p)
18168 (not (bolp))
18169 (not (= (char-after) ?|))
18170 (eq N 1))
18171 (if (looking-at ".*?|")
18172 (let ((pos (point))
18173 (noalign (looking-at "[^|\n\r]* |"))
18174 (c org-table-may-need-update))
18175 (replace-match (concat
18176 (substring (match-string 0) 1 -1)
18177 " |"))
18178 (goto-char pos)
18179 ;; noalign: if there were two spaces at the end, this field
18180 ;; does not determine the width of the column.
18181 (if noalign (setq org-table-may-need-update c)))
18182 (delete-char N))
18183 (delete-char N)
18184 (org-fix-tags-on-the-fly)))
18186 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18187 (put 'org-self-insert-command 'delete-selection t)
18188 (put 'orgtbl-self-insert-command 'delete-selection t)
18189 (put 'org-delete-char 'delete-selection 'supersede)
18190 (put 'org-delete-backward-char 'delete-selection 'supersede)
18191 (put 'org-yank 'delete-selection 'yank)
18193 ;; Make `flyspell-mode' delay after some commands
18194 (put 'org-self-insert-command 'flyspell-delayed t)
18195 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18196 (put 'org-delete-char 'flyspell-delayed t)
18197 (put 'org-delete-backward-char 'flyspell-delayed t)
18199 ;; Make pabbrev-mode expand after org-mode commands
18200 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18201 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18203 ;; How to do this: Measure non-white length of current string
18204 ;; If equal to column width, we should realign.
18206 (defun org-remap (map &rest commands)
18207 "In MAP, remap the functions given in COMMANDS.
18208 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18209 (let (new old)
18210 (while commands
18211 (setq old (pop commands) new (pop commands))
18212 (if (fboundp 'command-remapping)
18213 (org-defkey map (vector 'remap old) new)
18214 (substitute-key-definition old new map global-map)))))
18216 (when (eq org-enable-table-editor 'optimized)
18217 ;; If the user wants maximum table support, we need to hijack
18218 ;; some standard editing functions
18219 (org-remap org-mode-map
18220 'self-insert-command 'org-self-insert-command
18221 'delete-char 'org-delete-char
18222 'delete-backward-char 'org-delete-backward-char)
18223 (org-defkey org-mode-map "|" 'org-force-self-insert))
18225 (defvar org-ctrl-c-ctrl-c-hook nil
18226 "Hook for functions attaching themselves to `C-c C-c'.
18228 This can be used to add additional functionality to the C-c C-c
18229 key which executes context-dependent commands. This hook is run
18230 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18231 run after the last test.
18233 Each function will be called with no arguments. The function
18234 must check if the context is appropriate for it to act. If yes,
18235 it should do its thing and then return a non-nil value. If the
18236 context is wrong, just do nothing and return nil.")
18238 (defvar org-ctrl-c-ctrl-c-final-hook nil
18239 "Hook for functions attaching themselves to `C-c C-c'.
18241 This can be used to add additional functionality to the C-c C-c
18242 key which executes context-dependent commands. This hook is run
18243 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18244 before the first test.
18246 Each function will be called with no arguments. The function
18247 must check if the context is appropriate for it to act. If yes,
18248 it should do its thing and then return a non-nil value. If the
18249 context is wrong, just do nothing and return nil.")
18251 (defvar org-tab-first-hook nil
18252 "Hook for functions to attach themselves to TAB.
18253 See `org-ctrl-c-ctrl-c-hook' for more information.
18254 This hook runs as the first action when TAB is pressed, even before
18255 `org-cycle' messes around with the `outline-regexp' to cater for
18256 inline tasks and plain list item folding.
18257 If any function in this hook returns t, any other actions that
18258 would have been caused by TAB (such as table field motion or visibility
18259 cycling) will not occur.")
18261 (defvar org-tab-after-check-for-table-hook nil
18262 "Hook for functions to attach themselves to TAB.
18263 See `org-ctrl-c-ctrl-c-hook' for more information.
18264 This hook runs after it has been established that the cursor is not in a
18265 table, but before checking if the cursor is in a headline or if global cycling
18266 should be done.
18267 If any function in this hook returns t, not other actions like visibility
18268 cycling will be done.")
18270 (defvar org-tab-after-check-for-cycling-hook nil
18271 "Hook for functions to attach themselves to TAB.
18272 See `org-ctrl-c-ctrl-c-hook' for more information.
18273 This hook runs after it has been established that not table field motion and
18274 not visibility should be done because of current context. This is probably
18275 the place where a package like yasnippets can hook in.")
18277 (defvar org-tab-before-tab-emulation-hook nil
18278 "Hook for functions to attach themselves to TAB.
18279 See `org-ctrl-c-ctrl-c-hook' for more information.
18280 This hook runs after every other options for TAB have been exhausted, but
18281 before indentation and \t insertion takes place.")
18283 (defvar org-metaleft-hook nil
18284 "Hook for functions attaching themselves to `M-left'.
18285 See `org-ctrl-c-ctrl-c-hook' for more information.")
18286 (defvar org-metaright-hook nil
18287 "Hook for functions attaching themselves to `M-right'.
18288 See `org-ctrl-c-ctrl-c-hook' for more information.")
18289 (defvar org-metaup-hook nil
18290 "Hook for functions attaching themselves to `M-up'.
18291 See `org-ctrl-c-ctrl-c-hook' for more information.")
18292 (defvar org-metadown-hook nil
18293 "Hook for functions attaching themselves to `M-down'.
18294 See `org-ctrl-c-ctrl-c-hook' for more information.")
18295 (defvar org-shiftmetaleft-hook nil
18296 "Hook for functions attaching themselves to `M-S-left'.
18297 See `org-ctrl-c-ctrl-c-hook' for more information.")
18298 (defvar org-shiftmetaright-hook nil
18299 "Hook for functions attaching themselves to `M-S-right'.
18300 See `org-ctrl-c-ctrl-c-hook' for more information.")
18301 (defvar org-shiftmetaup-hook nil
18302 "Hook for functions attaching themselves to `M-S-up'.
18303 See `org-ctrl-c-ctrl-c-hook' for more information.")
18304 (defvar org-shiftmetadown-hook nil
18305 "Hook for functions attaching themselves to `M-S-down'.
18306 See `org-ctrl-c-ctrl-c-hook' for more information.")
18307 (defvar org-metareturn-hook nil
18308 "Hook for functions attaching themselves to `M-RET'.
18309 See `org-ctrl-c-ctrl-c-hook' for more information.")
18310 (defvar org-shiftup-hook nil
18311 "Hook for functions attaching themselves to `S-up'.
18312 See `org-ctrl-c-ctrl-c-hook' for more information.")
18313 (defvar org-shiftup-final-hook nil
18314 "Hook for functions attaching themselves to `S-up'.
18315 This one runs after all other options except shift-select have been excluded.
18316 See `org-ctrl-c-ctrl-c-hook' for more information.")
18317 (defvar org-shiftdown-hook nil
18318 "Hook for functions attaching themselves to `S-down'.
18319 See `org-ctrl-c-ctrl-c-hook' for more information.")
18320 (defvar org-shiftdown-final-hook nil
18321 "Hook for functions attaching themselves to `S-down'.
18322 This one runs after all other options except shift-select have been excluded.
18323 See `org-ctrl-c-ctrl-c-hook' for more information.")
18324 (defvar org-shiftleft-hook nil
18325 "Hook for functions attaching themselves to `S-left'.
18326 See `org-ctrl-c-ctrl-c-hook' for more information.")
18327 (defvar org-shiftleft-final-hook nil
18328 "Hook for functions attaching themselves to `S-left'.
18329 This one runs after all other options except shift-select have been excluded.
18330 See `org-ctrl-c-ctrl-c-hook' for more information.")
18331 (defvar org-shiftright-hook nil
18332 "Hook for functions attaching themselves to `S-right'.
18333 See `org-ctrl-c-ctrl-c-hook' for more information.")
18334 (defvar org-shiftright-final-hook nil
18335 "Hook for functions attaching themselves to `S-right'.
18336 This one runs after all other options except shift-select have been excluded.
18337 See `org-ctrl-c-ctrl-c-hook' for more information.")
18339 (defun org-modifier-cursor-error ()
18340 "Throw an error, a modified cursor command was applied in wrong context."
18341 (error "This command is active in special context like tables, headlines or items"))
18343 (defun org-shiftselect-error ()
18344 "Throw an error because Shift-Cursor command was applied in wrong context."
18345 (if (and (boundp 'shift-select-mode) shift-select-mode)
18346 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18347 (error "This command works only in special context like headlines or timestamps")))
18349 (defun org-call-for-shift-select (cmd)
18350 (let ((this-command-keys-shift-translated t))
18351 (call-interactively cmd)))
18353 (defun org-shifttab (&optional arg)
18354 "Global visibility cycling or move to previous table field.
18355 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18356 on context.
18357 See the individual commands for more information."
18358 (interactive "P")
18359 (cond
18360 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18361 ((integerp arg)
18362 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18363 (message "Content view to level: %d" arg)
18364 (org-content (prefix-numeric-value arg2))
18365 (setq org-cycle-global-status 'overview)))
18366 (t (call-interactively 'org-global-cycle))))
18368 (defun org-shiftmetaleft ()
18369 "Promote subtree or delete table column.
18370 Calls `org-promote-subtree', `org-outdent-item-tree', or
18371 `org-table-delete-column', depending on context. See the
18372 individual commands for more information."
18373 (interactive)
18374 (cond
18375 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18376 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18377 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18378 ((if (not (org-region-active-p)) (org-at-item-p)
18379 (save-excursion (goto-char (region-beginning))
18380 (org-at-item-p)))
18381 (call-interactively 'org-outdent-item-tree))
18382 (t (org-modifier-cursor-error))))
18384 (defun org-shiftmetaright ()
18385 "Demote subtree or insert table column.
18386 Calls `org-demote-subtree', `org-indent-item-tree', or
18387 `org-table-insert-column', depending on context. See the
18388 individual commands for more information."
18389 (interactive)
18390 (cond
18391 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18392 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18393 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18394 ((if (not (org-region-active-p)) (org-at-item-p)
18395 (save-excursion (goto-char (region-beginning))
18396 (org-at-item-p)))
18397 (call-interactively 'org-indent-item-tree))
18398 (t (org-modifier-cursor-error))))
18400 (defun org-shiftmetaup (&optional arg)
18401 "Move subtree up or kill table row.
18402 Calls `org-move-subtree-up' or `org-table-kill-row' or
18403 `org-move-item-up' or `org-timestamp-up', depending on context.
18404 See the individual commands for more information."
18405 (interactive "P")
18406 (cond
18407 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18408 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18409 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18410 ((org-at-item-p) (call-interactively 'org-move-item-up))
18411 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18412 (call-interactively 'org-timestamp-up)))
18413 (t (org-modifier-cursor-error))))
18415 (defun org-shiftmetadown (&optional arg)
18416 "Move subtree down or insert table row.
18417 Calls `org-move-subtree-down' or `org-table-insert-row' or
18418 `org-move-item-down' or `org-timestamp-up', depending on context.
18419 See the individual commands for more information."
18420 (interactive "P")
18421 (cond
18422 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18423 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18424 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18425 ((org-at-item-p) (call-interactively 'org-move-item-down))
18426 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18427 (call-interactively 'org-timestamp-down)))
18428 (t (org-modifier-cursor-error))))
18430 (defsubst org-hidden-tree-error ()
18431 (error
18432 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18434 (defun org-metaleft (&optional arg)
18435 "Promote heading or move table column to left.
18436 Calls `org-do-promote' or `org-table-move-column', depending on context.
18437 With no specific context, calls the Emacs default `backward-word'.
18438 See the individual commands for more information."
18439 (interactive "P")
18440 (cond
18441 ((run-hook-with-args-until-success 'org-metaleft-hook))
18442 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18443 ((org-with-limited-levels
18444 (or (org-at-heading-p)
18445 (and (org-region-active-p)
18446 (save-excursion
18447 (goto-char (region-beginning))
18448 (org-at-heading-p)))))
18449 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18450 (call-interactively 'org-do-promote))
18451 ;; At an inline task.
18452 ((org-at-heading-p)
18453 (call-interactively 'org-inlinetask-promote))
18454 ((or (org-at-item-p)
18455 (and (org-region-active-p)
18456 (save-excursion
18457 (goto-char (region-beginning))
18458 (org-at-item-p))))
18459 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18460 (call-interactively 'org-outdent-item))
18461 (t (call-interactively 'backward-word))))
18463 (defun org-metaright (&optional arg)
18464 "Demote a subtree, a list item or move table column to right.
18465 In front of a drawer or a block keyword, indent it correctly.
18466 With no specific context, calls the Emacs default `forward-word'.
18467 See the individual commands for more information."
18468 (interactive "P")
18469 (cond
18470 ((run-hook-with-args-until-success 'org-metaright-hook))
18471 ((org-at-table-p) (call-interactively 'org-table-move-column))
18472 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18473 ((org-at-block-p) (call-interactively 'org-indent-block))
18474 ((org-with-limited-levels
18475 (or (org-at-heading-p)
18476 (and (org-region-active-p)
18477 (save-excursion
18478 (goto-char (region-beginning))
18479 (org-at-heading-p)))))
18480 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18481 (call-interactively 'org-do-demote))
18482 ;; At an inline task.
18483 ((org-at-heading-p)
18484 (call-interactively 'org-inlinetask-demote))
18485 ((or (org-at-item-p)
18486 (and (org-region-active-p)
18487 (save-excursion
18488 (goto-char (region-beginning))
18489 (org-at-item-p))))
18490 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18491 (call-interactively 'org-indent-item))
18492 (t (call-interactively 'forward-word))))
18494 (defun org-check-for-hidden (what)
18495 "Check if there are hidden headlines/items in the current visual line.
18496 WHAT can be either `headlines' or `items'. If the current line is
18497 an outline or item heading and it has a folded subtree below it,
18498 this function returns t, nil otherwise."
18499 (let ((re (cond
18500 ((eq what 'headlines) org-outline-regexp-bol)
18501 ((eq what 'items) (org-item-beginning-re))
18502 (t (error "This should not happen"))))
18503 beg end)
18504 (save-excursion
18505 (catch 'exit
18506 (unless (org-region-active-p)
18507 (setq beg (point-at-bol))
18508 (beginning-of-line 2)
18509 (while (and (not (eobp)) ;; this is like `next-line'
18510 (get-char-property (1- (point)) 'invisible))
18511 (beginning-of-line 2))
18512 (setq end (point))
18513 (goto-char beg)
18514 (goto-char (point-at-eol))
18515 (setq end (max end (point)))
18516 (while (re-search-forward re end t)
18517 (if (get-char-property (match-beginning 0) 'invisible)
18518 (throw 'exit t))))
18519 nil))))
18521 (defun org-metaup (&optional arg)
18522 "Move subtree up or move table row up.
18523 Calls `org-move-subtree-up' or `org-table-move-row' or
18524 `org-move-item-up', depending on context. See the individual commands
18525 for more information."
18526 (interactive "P")
18527 (cond
18528 ((run-hook-with-args-until-success 'org-metaup-hook))
18529 ((org-region-active-p)
18530 (let* ((a (min (region-beginning) (region-end)))
18531 (b (1- (max (region-beginning) (region-end))))
18532 (c (save-excursion (goto-char a)
18533 (move-beginning-of-line 0)))
18534 (d (save-excursion (goto-char a)
18535 (move-end-of-line 0) (point))))
18536 (transpose-regions a b c d)
18537 (goto-char c)))
18538 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18539 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18540 ((org-at-item-p) (call-interactively 'org-move-item-up))
18541 (t (org-element-drag-backward))))
18543 (defun org-metadown (&optional arg)
18544 "Move subtree down or move table row down.
18545 Calls `org-move-subtree-down' or `org-table-move-row' or
18546 `org-move-item-down', depending on context. See the individual
18547 commands for more information."
18548 (interactive "P")
18549 (cond
18550 ((run-hook-with-args-until-success 'org-metadown-hook))
18551 ((org-region-active-p)
18552 (let* ((a (min (region-beginning) (region-end)))
18553 (b (max (region-beginning) (region-end)))
18554 (c (save-excursion (goto-char b)
18555 (move-beginning-of-line 1)))
18556 (d (save-excursion (goto-char b)
18557 (move-end-of-line 1) (1+ (point)))))
18558 (transpose-regions a b c d)
18559 (goto-char d)))
18560 ((org-at-table-p) (call-interactively 'org-table-move-row))
18561 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18562 ((org-at-item-p) (call-interactively 'org-move-item-down))
18563 (t (org-element-drag-forward))))
18565 (defun org-shiftup (&optional arg)
18566 "Increase item in timestamp or increase priority of current headline.
18567 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18568 depending on context. See the individual commands for more information."
18569 (interactive "P")
18570 (cond
18571 ((run-hook-with-args-until-success 'org-shiftup-hook))
18572 ((and org-support-shift-select (org-region-active-p))
18573 (org-call-for-shift-select 'previous-line))
18574 ((org-at-timestamp-p t)
18575 (call-interactively (if org-edit-timestamp-down-means-later
18576 'org-timestamp-down 'org-timestamp-up)))
18577 ((and (not (eq org-support-shift-select 'always))
18578 org-enable-priority-commands
18579 (org-at-heading-p))
18580 (call-interactively 'org-priority-up))
18581 ((and (not org-support-shift-select) (org-at-item-p))
18582 (call-interactively 'org-previous-item))
18583 ((org-clocktable-try-shift 'up arg))
18584 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18585 (org-support-shift-select
18586 (org-call-for-shift-select 'previous-line))
18587 (t (org-shiftselect-error))))
18589 (defun org-shiftdown (&optional arg)
18590 "Decrease item in timestamp or decrease priority of current headline.
18591 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18592 depending on context. See the individual commands for more information."
18593 (interactive "P")
18594 (cond
18595 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18596 ((and org-support-shift-select (org-region-active-p))
18597 (org-call-for-shift-select 'next-line))
18598 ((org-at-timestamp-p t)
18599 (call-interactively (if org-edit-timestamp-down-means-later
18600 'org-timestamp-up 'org-timestamp-down)))
18601 ((and (not (eq org-support-shift-select 'always))
18602 org-enable-priority-commands
18603 (org-at-heading-p))
18604 (call-interactively 'org-priority-down))
18605 ((and (not org-support-shift-select) (org-at-item-p))
18606 (call-interactively 'org-next-item))
18607 ((org-clocktable-try-shift 'down arg))
18608 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18609 (org-support-shift-select
18610 (org-call-for-shift-select 'next-line))
18611 (t (org-shiftselect-error))))
18613 (defun org-shiftright (&optional arg)
18614 "Cycle the thing at point or in the current line, depending on context.
18615 Depending on context, this does one of the following:
18617 - switch a timestamp at point one day into the future
18618 - on a headline, switch to the next TODO keyword.
18619 - on an item, switch entire list to the next bullet type
18620 - on a property line, switch to the next allowed value
18621 - on a clocktable definition line, move time block into the future"
18622 (interactive "P")
18623 (cond
18624 ((run-hook-with-args-until-success 'org-shiftright-hook))
18625 ((and org-support-shift-select (org-region-active-p))
18626 (org-call-for-shift-select 'forward-char))
18627 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18628 ((and (not (eq org-support-shift-select 'always))
18629 (org-at-heading-p))
18630 (let ((org-inhibit-logging
18631 (not org-treat-S-cursor-todo-selection-as-state-change))
18632 (org-inhibit-blocking
18633 (not org-treat-S-cursor-todo-selection-as-state-change)))
18634 (org-call-with-arg 'org-todo 'right)))
18635 ((or (and org-support-shift-select
18636 (not (eq org-support-shift-select 'always))
18637 (org-at-item-bullet-p))
18638 (and (not org-support-shift-select) (org-at-item-p)))
18639 (org-call-with-arg 'org-cycle-list-bullet nil))
18640 ((and (not (eq org-support-shift-select 'always))
18641 (org-at-property-p))
18642 (call-interactively 'org-property-next-allowed-value))
18643 ((org-clocktable-try-shift 'right arg))
18644 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18645 (org-support-shift-select
18646 (org-call-for-shift-select 'forward-char))
18647 (t (org-shiftselect-error))))
18649 (defun org-shiftleft (&optional arg)
18650 "Cycle the thing at point or in the current line, depending on context.
18651 Depending on context, this does one of the following:
18653 - switch a timestamp at point one day into the past
18654 - on a headline, switch to the previous TODO keyword.
18655 - on an item, switch entire list to the previous bullet type
18656 - on a property line, switch to the previous allowed value
18657 - on a clocktable definition line, move time block into the past"
18658 (interactive "P")
18659 (cond
18660 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18661 ((and org-support-shift-select (org-region-active-p))
18662 (org-call-for-shift-select 'backward-char))
18663 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18664 ((and (not (eq org-support-shift-select 'always))
18665 (org-at-heading-p))
18666 (let ((org-inhibit-logging
18667 (not org-treat-S-cursor-todo-selection-as-state-change))
18668 (org-inhibit-blocking
18669 (not org-treat-S-cursor-todo-selection-as-state-change)))
18670 (org-call-with-arg 'org-todo 'left)))
18671 ((or (and org-support-shift-select
18672 (not (eq org-support-shift-select 'always))
18673 (org-at-item-bullet-p))
18674 (and (not org-support-shift-select) (org-at-item-p)))
18675 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18676 ((and (not (eq org-support-shift-select 'always))
18677 (org-at-property-p))
18678 (call-interactively 'org-property-previous-allowed-value))
18679 ((org-clocktable-try-shift 'left arg))
18680 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18681 (org-support-shift-select
18682 (org-call-for-shift-select 'backward-char))
18683 (t (org-shiftselect-error))))
18685 (defun org-shiftcontrolright ()
18686 "Switch to next TODO set."
18687 (interactive)
18688 (cond
18689 ((and org-support-shift-select (org-region-active-p))
18690 (org-call-for-shift-select 'forward-word))
18691 ((and (not (eq org-support-shift-select 'always))
18692 (org-at-heading-p))
18693 (org-call-with-arg 'org-todo 'nextset))
18694 (org-support-shift-select
18695 (org-call-for-shift-select 'forward-word))
18696 (t (org-shiftselect-error))))
18698 (defun org-shiftcontrolleft ()
18699 "Switch to previous TODO set."
18700 (interactive)
18701 (cond
18702 ((and org-support-shift-select (org-region-active-p))
18703 (org-call-for-shift-select 'backward-word))
18704 ((and (not (eq org-support-shift-select 'always))
18705 (org-at-heading-p))
18706 (org-call-with-arg 'org-todo 'previousset))
18707 (org-support-shift-select
18708 (org-call-for-shift-select 'backward-word))
18709 (t (org-shiftselect-error))))
18711 (defun org-shiftcontrolup ()
18712 "Change timestamps synchronously up in CLOCK log lines."
18713 (interactive)
18714 (cond ((and (not org-support-shift-select)
18715 (org-at-clock-log-p)
18716 (org-at-timestamp-p t))
18717 (org-clock-timestamps-up))
18718 (t (org-shiftselect-error))))
18720 (defun org-shiftcontroldown ()
18721 "Change timestamps synchronously down in CLOCK log lines."
18722 (interactive)
18723 (cond ((and (not org-support-shift-select)
18724 (org-at-clock-log-p)
18725 (org-at-timestamp-p t))
18726 (org-clock-timestamps-down))
18727 (t (org-shiftselect-error))))
18729 (defun org-ctrl-c-ret ()
18730 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18731 (interactive)
18732 (cond
18733 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18734 (t (call-interactively 'org-insert-heading))))
18736 (defun org-find-visible ()
18737 (let ((s (point)))
18738 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18739 (get-char-property s 'invisible)))
18741 (defun org-find-invisible ()
18742 (let ((s (point)))
18743 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18744 (not (get-char-property s 'invisible))))
18747 (defun org-copy-visible (beg end)
18748 "Copy the visible parts of the region."
18749 (interactive "r")
18750 (let (snippets s)
18751 (save-excursion
18752 (save-restriction
18753 (narrow-to-region beg end)
18754 (setq s (goto-char (point-min)))
18755 (while (not (= (point) (point-max)))
18756 (goto-char (org-find-invisible))
18757 (push (buffer-substring s (point)) snippets)
18758 (setq s (goto-char (org-find-visible))))))
18759 (kill-new (apply 'concat (nreverse snippets)))))
18761 (defun org-copy-special ()
18762 "Copy region in table or copy current subtree.
18763 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18764 See the individual commands for more information."
18765 (interactive)
18766 (call-interactively
18767 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18769 (defun org-cut-special ()
18770 "Cut region in table or cut current subtree.
18771 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18772 See the individual commands for more information."
18773 (interactive)
18774 (call-interactively
18775 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18777 (defun org-paste-special (arg)
18778 "Paste rectangular region into table, or past subtree relative to level.
18779 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18780 See the individual commands for more information."
18781 (interactive "P")
18782 (if (org-at-table-p)
18783 (org-table-paste-rectangle)
18784 (org-paste-subtree arg)))
18786 (defun org-edit-special (&optional arg)
18787 "Call a special editor for the stuff at point.
18788 When at a table, call the formula editor with `org-table-edit-formulas'.
18789 When at the first line of an src example, call `org-edit-src-code'.
18790 When in an #+include line, visit the include file. Otherwise call
18791 `ffap' to visit the file at point."
18792 (interactive)
18793 ;; possibly prep session before editing source
18794 (when arg
18795 (let* ((info (org-babel-get-src-block-info))
18796 (lang (nth 0 info))
18797 (params (nth 2 info))
18798 (session (cdr (assoc :session params))))
18799 (when (and info session) ;; we are in a source-code block with a session
18800 (funcall
18801 (intern (concat "org-babel-prep-session:" lang)) session params))))
18802 (cond ;; proceed with `org-edit-special'
18803 ((save-excursion
18804 (beginning-of-line 1)
18805 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18806 (find-file (org-trim (match-string 1))))
18807 ((org-edit-src-code))
18808 ((org-edit-fixed-width-region))
18809 ((org-at-table.el-p)
18810 (org-edit-src-code))
18811 ((or (org-at-table-p)
18812 (save-excursion
18813 (beginning-of-line 1)
18814 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18815 (call-interactively 'org-table-edit-formulas))
18816 (t (call-interactively 'ffap))))
18818 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18819 (defun org-ctrl-c-ctrl-c (&optional arg)
18820 "Set tags in headline, or update according to changed information at point.
18822 This command does many different things, depending on context:
18824 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18825 this is what we do.
18827 - If the cursor is on a statistics cookie, update it.
18829 - If the cursor is in a headline, prompt for tags and insert them
18830 into the current line, aligned to `org-tags-column'. When called
18831 with prefix arg, realign all tags in the current buffer.
18833 - If the cursor is in one of the special #+KEYWORD lines, this
18834 triggers scanning the buffer for these lines and updating the
18835 information.
18837 - If the cursor is inside a table, realign the table. This command
18838 works even if the automatic table editor has been turned off.
18840 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18841 the entire table.
18843 - If the cursor is at a footnote reference or definition, jump to
18844 the corresponding definition or references, respectively.
18846 - If the cursor is a the beginning of a dynamic block, update it.
18848 - If the current buffer is a capture buffer, close note and file it.
18850 - If the cursor is on a <<<target>>>, update radio targets and
18851 corresponding links in this buffer.
18853 - If the cursor is on a numbered item in a plain list, renumber the
18854 ordered list.
18856 - If the cursor is on a checkbox, toggle it.
18858 - If the cursor is on a code block, evaluate it. The variable
18859 `org-confirm-babel-evaluate' can be used to control prompting
18860 before code block evaluation, by default every code block
18861 evaluation requires confirmation. Code block evaluation can be
18862 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18863 (interactive "P")
18864 (let ((org-enable-table-editor t))
18865 (cond
18866 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18867 org-occur-highlights
18868 org-latex-fragment-image-overlays)
18869 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18870 (org-remove-occur-highlights)
18871 (org-remove-latex-fragment-image-overlays)
18872 (message "Temporary highlights/overlays removed from current buffer"))
18873 ((and (local-variable-p 'org-finish-function (current-buffer))
18874 (fboundp org-finish-function))
18875 (funcall org-finish-function))
18876 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18877 ((org-in-regexp org-ts-regexp-both)
18878 (org-timestamp-change 0 'day))
18879 ((or (looking-at org-property-start-re)
18880 (org-at-property-p))
18881 (call-interactively 'org-property-action))
18882 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18883 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18884 (or (org-at-heading-p) (org-at-item-p)))
18885 (call-interactively 'org-update-statistics-cookies))
18886 ((org-at-heading-p) (call-interactively 'org-set-tags))
18887 ((org-at-table.el-p)
18888 (message "Use C-c ' to edit table.el tables"))
18889 ((org-at-table-p)
18890 (org-table-maybe-eval-formula)
18891 (if arg
18892 (call-interactively 'org-table-recalculate)
18893 (org-table-maybe-recalculate-line))
18894 (call-interactively 'org-table-align)
18895 (orgtbl-send-table 'maybe))
18896 ((or (org-footnote-at-reference-p)
18897 (org-footnote-at-definition-p))
18898 (call-interactively 'org-footnote-action))
18899 ((org-at-item-checkbox-p)
18900 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18901 ;; list only if at top item.
18902 (let* ((cbox (match-string 1))
18903 (struct (org-list-struct))
18904 (old-struct (copy-tree struct))
18905 (parents (org-list-parents-alist struct))
18906 (orderedp (org-entry-get nil "ORDERED"))
18907 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18908 block-item)
18909 ;; Use a light version of `org-toggle-checkbox' to avoid
18910 ;; computing list structure twice.
18911 (let ((new-box (cond
18912 ((equal arg '(16)) "[-]")
18913 ((equal arg '(4)) nil)
18914 ((equal "[X]" cbox) "[ ]")
18915 (t "[X]"))))
18916 (if (and firstp arg)
18917 ;; If at first item of sub-list, remove check-box from
18918 ;; every item at the same level.
18919 (mapc
18920 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18921 (org-list-get-all-items
18922 (point-at-bol) struct (org-list-prevs-alist struct)))
18923 (org-list-set-checkbox (point-at-bol) struct new-box)))
18924 ;; Replicate `org-list-write-struct', while grabbing a return
18925 ;; value from `org-list-struct-fix-box'.
18926 (org-list-struct-fix-ind struct parents 2)
18927 (org-list-struct-fix-item-end struct)
18928 (let ((prevs (org-list-prevs-alist struct)))
18929 (org-list-struct-fix-bul struct prevs)
18930 (org-list-struct-fix-ind struct parents)
18931 (setq block-item
18932 (org-list-struct-fix-box struct parents prevs orderedp)))
18933 (org-list-struct-apply-struct struct old-struct)
18934 (org-update-checkbox-count-maybe)
18935 (when block-item
18936 (message
18937 "Checkboxes were removed due to unchecked box at line %d"
18938 (org-current-line block-item)))
18939 (when firstp (org-list-send-list 'maybe))))
18940 ((org-at-item-p)
18941 ;; Cursor at an item: repair list. Do checkbox related actions
18942 ;; only if function was called with an argument. Send list only
18943 ;; if at top item.
18944 (let* ((struct (org-list-struct))
18945 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18946 old-struct)
18947 (when arg
18948 (setq old-struct (copy-tree struct))
18949 (if firstp
18950 ;; If at first item of sub-list, add check-box to every
18951 ;; item at the same level.
18952 (mapc
18953 (lambda (pos)
18954 (unless (org-list-get-checkbox pos struct)
18955 (org-list-set-checkbox pos struct "[ ]")))
18956 (org-list-get-all-items
18957 (point-at-bol) struct (org-list-prevs-alist struct)))
18958 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18959 (org-list-write-struct
18960 struct (org-list-parents-alist struct) old-struct)
18961 (when arg (org-update-checkbox-count-maybe))
18962 (when firstp (org-list-send-list 'maybe))))
18963 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18964 ;; Dynamic block
18965 (beginning-of-line 1)
18966 (save-excursion (org-update-dblock)))
18967 ((save-excursion
18968 (let ((case-fold-search t))
18969 (beginning-of-line 1)
18970 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18971 (cond
18972 ((or (equal (match-string 1) "TBLFM")
18973 (equal (match-string 1) "tblfm"))
18974 ;; Recalculate the table before this line
18975 (save-excursion
18976 (beginning-of-line 1)
18977 (skip-chars-backward " \r\n\t")
18978 (if (org-at-table-p)
18979 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18981 (let ((org-inhibit-startup-visibility-stuff t)
18982 (org-startup-align-all-tables nil))
18983 (when (boundp 'org-table-coordinate-overlays)
18984 (mapc 'delete-overlay org-table-coordinate-overlays)
18985 (setq org-table-coordinate-overlays nil))
18986 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18987 (message "Local setup has been refreshed"))))
18988 ((org-clock-update-time-maybe))
18990 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18991 (error "C-c C-c can do nothing useful at this location"))))))
18993 (defun org-mode-restart ()
18994 "Restart Org-mode, to scan again for special lines.
18995 Also updates the keyword regular expressions."
18996 (interactive)
18997 (org-mode)
18998 (message "Org-mode restarted"))
19000 (defun org-kill-note-or-show-branches ()
19001 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19002 (interactive)
19003 (if (not org-finish-function)
19004 (progn
19005 (hide-subtree)
19006 (call-interactively 'show-branches))
19007 (let ((org-note-abort t))
19008 (funcall org-finish-function))))
19010 (defun org-return (&optional indent)
19011 "Goto next table row or insert a newline.
19012 Calls `org-table-next-row' or `newline', depending on context.
19013 See the individual commands for more information."
19014 (interactive)
19015 (let (org-ts-what)
19016 (cond
19017 ((or (bobp) (org-in-src-block-p))
19018 (if indent (newline-and-indent) (newline)))
19019 ((org-at-table-p)
19020 (org-table-justify-field-maybe)
19021 (call-interactively 'org-table-next-row))
19022 ;; when `newline-and-indent' is called within a list, make sure
19023 ;; text moved stays inside the item.
19024 ((and (org-in-item-p) indent)
19025 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19026 (progn
19027 (save-match-data (newline))
19028 (org-indent-line-to (length (match-string 0))))
19029 (let ((ind (org-get-indentation)))
19030 (newline)
19031 (if (org-looking-back org-list-end-re)
19032 (org-indent-line)
19033 (org-indent-line-to ind)))))
19034 ((and org-return-follows-link
19035 (org-at-timestamp-p t)
19036 (not (eq org-ts-what 'after)))
19037 (org-follow-timestamp-link))
19038 ((and org-return-follows-link
19039 (let ((tprop (get-text-property (point) 'face)))
19040 (or (eq tprop 'org-link)
19041 (and (listp tprop) (memq 'org-link tprop)))))
19042 (call-interactively 'org-open-at-point))
19043 ((and (org-at-heading-p)
19044 (looking-at
19045 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19046 (org-show-entry)
19047 (end-of-line 1)
19048 (newline))
19049 (t (if indent (newline-and-indent) (newline))))))
19051 (defun org-return-indent ()
19052 "Goto next table row or insert a newline and indent.
19053 Calls `org-table-next-row' or `newline-and-indent', depending on
19054 context. See the individual commands for more information."
19055 (interactive)
19056 (org-return t))
19058 (defun org-ctrl-c-star ()
19059 "Compute table, or change heading status of lines.
19060 Calls `org-table-recalculate' or `org-toggle-heading',
19061 depending on context."
19062 (interactive)
19063 (cond
19064 ((org-at-table-p)
19065 (call-interactively 'org-table-recalculate))
19067 ;; Convert all lines in region to list items
19068 (call-interactively 'org-toggle-heading))))
19070 (defun org-ctrl-c-minus ()
19071 "Insert separator line in table or modify bullet status of line.
19072 Also turns a plain line or a region of lines into list items.
19073 Calls `org-table-insert-hline', `org-toggle-item', or
19074 `org-cycle-list-bullet', depending on context."
19075 (interactive)
19076 (cond
19077 ((org-at-table-p)
19078 (call-interactively 'org-table-insert-hline))
19079 ((org-region-active-p)
19080 (call-interactively 'org-toggle-item))
19081 ((org-in-item-p)
19082 (call-interactively 'org-cycle-list-bullet))
19084 (call-interactively 'org-toggle-item))))
19086 (defun org-toggle-item (arg)
19087 "Convert headings or normal lines to items, items to normal lines.
19088 If there is no active region, only the current line is considered.
19090 If the first non blank line in the region is an headline, convert
19091 all headlines to items, shifting text accordingly.
19093 If it is an item, convert all items to normal lines.
19095 If it is normal text, change region into an item. With a prefix
19096 argument ARG, change each line in region into an item."
19097 (interactive "P")
19098 (let ((shift-text
19099 (function
19100 ;; Shift text in current section to IND, from point to END.
19101 ;; The function leaves point to END line.
19102 (lambda (ind end)
19103 (let ((min-i 1000) (end (copy-marker end)))
19104 ;; First determine the minimum indentation (MIN-I) of
19105 ;; the text.
19106 (save-excursion
19107 (catch 'exit
19108 (while (< (point) end)
19109 (let ((i (org-get-indentation)))
19110 (cond
19111 ;; Skip blank lines and inline tasks.
19112 ((looking-at "^[ \t]*$"))
19113 ((looking-at org-outline-regexp-bol))
19114 ;; We can't find less than 0 indentation.
19115 ((zerop i) (throw 'exit (setq min-i 0)))
19116 ((< i min-i) (setq min-i i))))
19117 (forward-line))))
19118 ;; Then indent each line so that a line indented to
19119 ;; MIN-I becomes indented to IND. Ignore blank lines
19120 ;; and inline tasks in the process.
19121 (let ((delta (- ind min-i)))
19122 (while (< (point) end)
19123 (unless (or (looking-at "^[ \t]*$")
19124 (looking-at org-outline-regexp-bol))
19125 (org-indent-line-to (+ (org-get-indentation) delta)))
19126 (forward-line)))))))
19127 (skip-blanks
19128 (function
19129 ;; Return beginning of first non-blank line, starting from
19130 ;; line at POS.
19131 (lambda (pos)
19132 (save-excursion
19133 (goto-char pos)
19134 (skip-chars-forward " \r\t\n")
19135 (point-at-bol)))))
19136 beg end)
19137 ;; Determine boundaries of changes.
19138 (if (org-region-active-p)
19139 (setq beg (funcall skip-blanks (region-beginning))
19140 end (copy-marker (region-end)))
19141 (setq beg (funcall skip-blanks (point-at-bol))
19142 end (copy-marker (point-at-eol))))
19143 ;; Depending on the starting line, choose an action on the text
19144 ;; between BEG and END.
19145 (org-with-limited-levels
19146 (save-excursion
19147 (goto-char beg)
19148 (cond
19149 ;; Case 1. Start at an item: de-itemize. Note that it only
19150 ;; happens when a region is active: `org-ctrl-c-minus'
19151 ;; would call `org-cycle-list-bullet' otherwise.
19152 ((org-at-item-p)
19153 (while (< (point) end)
19154 (when (org-at-item-p)
19155 (skip-chars-forward " \t")
19156 (delete-region (point) (match-end 0)))
19157 (forward-line)))
19158 ;; Case 2. Start at an heading: convert to items.
19159 ((org-at-heading-p)
19160 (let* ((bul (org-list-bullet-string "-"))
19161 (bul-len (length bul))
19162 ;; Indentation of the first heading. It should be
19163 ;; relative to the indentation of its parent, if any.
19164 (start-ind (save-excursion
19165 (cond
19166 ((not org-adapt-indentation) 0)
19167 ((not (outline-previous-heading)) 0)
19168 (t (length (match-string 0))))))
19169 ;; Level of first heading. Further headings will be
19170 ;; compared to it to determine hierarchy in the list.
19171 (ref-level (org-reduced-level (org-outline-level))))
19172 (while (< (point) end)
19173 (let* ((level (org-reduced-level (org-outline-level)))
19174 (delta (max 0 (- level ref-level))))
19175 ;; If current headline is less indented than the first
19176 ;; one, set it as reference, in order to preserve
19177 ;; subtrees.
19178 (when (< level ref-level) (setq ref-level level))
19179 (replace-match bul t t)
19180 (org-indent-line-to (+ start-ind (* delta bul-len)))
19181 ;; Ensure all text down to END (or SECTION-END) belongs
19182 ;; to the newly created item.
19183 (let ((section-end (save-excursion
19184 (or (outline-next-heading) (point)))))
19185 (forward-line)
19186 (funcall shift-text
19187 (+ start-ind (* (1+ delta) bul-len))
19188 (min end section-end)))))))
19189 ;; Case 3. Normal line with ARG: turn each non-item line into
19190 ;; an item.
19191 (arg
19192 (while (< (point) end)
19193 (unless (or (org-at-heading-p) (org-at-item-p))
19194 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19195 (replace-match
19196 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19197 (forward-line)))
19198 ;; Case 4. Normal line without ARG: make the first line of
19199 ;; region an item, and shift indentation of others
19200 ;; lines to set them as item's body.
19201 (t (let* ((bul (org-list-bullet-string "-"))
19202 (bul-len (length bul))
19203 (ref-ind (org-get-indentation)))
19204 (skip-chars-forward " \t")
19205 (insert bul)
19206 (forward-line)
19207 (while (< (point) end)
19208 ;; Ensure that lines less indented than first one
19209 ;; still get included in item body.
19210 (funcall shift-text
19211 (+ ref-ind bul-len)
19212 (min end (save-excursion (or (outline-next-heading)
19213 (point)))))
19214 (forward-line)))))))))
19216 (defun org-toggle-heading (&optional nstars)
19217 "Convert headings to normal text, or items or text to headings.
19218 If there is no active region, only the current line is considered.
19220 With a \\[universal-argument] prefix, convert the whole list at
19221 point into heading.
19223 In a region:
19225 - If the first non blank line is an headline, remove the stars
19226 from all headlines in the region.
19228 - If it is a normal line turn each and every normal line (i.e. not an
19229 heading or an item) in the region into a heading.
19231 - If it is a plain list item, turn all plain list items into headings.
19233 When converting a line into a heading, the number of stars is chosen
19234 such that the lines become children of the current entry. However,
19235 when a prefix argument is given, its value determines the number of
19236 stars to add."
19237 (interactive "P")
19238 (let ((skip-blanks
19239 (function
19240 ;; Return beginning of first non-blank line, starting from
19241 ;; line at POS.
19242 (lambda (pos)
19243 (save-excursion
19244 (goto-char pos)
19245 (while (org-at-comment-p) (forward-line))
19246 (skip-chars-forward " \r\t\n")
19247 (point-at-bol)))))
19248 beg end toggled)
19249 ;; Determine boundaries of changes. If a universal prefix has
19250 ;; been given, put the list in a region. If region ends at a bol,
19251 ;; do not consider the last line to be in the region.
19253 (when (and current-prefix-arg (org-at-item-p))
19254 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19255 (org-mark-list))
19257 (if (org-region-active-p)
19258 (setq beg (funcall skip-blanks (region-beginning))
19259 end (copy-marker (save-excursion
19260 (goto-char (region-end))
19261 (if (bolp) (point) (point-at-eol)))))
19262 (setq beg (funcall skip-blanks (point-at-bol))
19263 end (copy-marker (point-at-eol))))
19264 ;; Ensure inline tasks don't count as headings.
19265 (org-with-limited-levels
19266 (save-excursion
19267 (goto-char beg)
19268 (cond
19269 ;; Case 1. Started at an heading: de-star headings.
19270 ((org-at-heading-p)
19271 (while (< (point) end)
19272 (when (org-at-heading-p t)
19273 (looking-at org-outline-regexp) (replace-match "")
19274 (setq toggled t))
19275 (forward-line)))
19276 ;; Case 2. Started at an item: change items into headlines.
19277 ;; One star will be added by `org-list-to-subtree'.
19278 ((org-at-item-p)
19279 (let* ((stars (make-string
19280 (if nstars
19281 ;; subtract the star that will be added again by
19282 ;; `org-list-to-subtree'
19283 (1- (prefix-numeric-value current-prefix-arg))
19284 (or (org-current-level) 0))
19285 ?*))
19286 (add-stars
19287 (cond (nstars "") ; stars from prefix only
19288 ((equal stars "") "") ; before first heading
19289 (org-odd-levels-only "*") ; inside heading, odd
19290 (t "")))) ; inside heading, oddeven
19291 (while (< (point) end)
19292 (when (org-at-item-p)
19293 ;; Pay attention to cases when region ends before list.
19294 (let* ((struct (org-list-struct))
19295 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19296 (save-restriction
19297 (narrow-to-region (point) list-end)
19298 (insert
19299 (org-list-to-subtree
19300 (org-list-parse-list t)
19301 '(:istart (concat stars add-stars (funcall get-stars depth))
19302 :icount (concat stars add-stars (funcall get-stars depth)))))))
19303 (setq toggled t))
19304 (forward-line))))
19305 ;; Case 3. Started at normal text: make every line an heading,
19306 ;; skipping headlines and items.
19307 (t (let* ((stars (make-string
19308 (if nstars
19309 (prefix-numeric-value current-prefix-arg)
19310 (or (org-current-level) 0))
19311 ?*))
19312 (add-stars
19313 (cond (nstars "") ; stars from prefix only
19314 ((equal stars "") "*") ; before first heading
19315 (org-odd-levels-only "**") ; inside heading, odd
19316 (t "*"))) ; inside heading, oddeven
19317 (rpl (concat stars add-stars " ")))
19318 (while (< (point) end)
19319 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19320 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19321 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19322 (forward-line)))))))
19323 (unless toggled (message "Cannot toggle heading from here"))))
19325 (defun org-meta-return (&optional arg)
19326 "Insert a new heading or wrap a region in a table.
19327 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19328 See the individual commands for more information."
19329 (interactive "P")
19330 (cond
19331 ((run-hook-with-args-until-success 'org-metareturn-hook))
19332 ((or (org-at-drawer-p) (org-at-property-p))
19333 (newline-and-indent))
19334 ((org-at-table-p)
19335 (call-interactively 'org-table-wrap-region))
19336 (t (call-interactively 'org-insert-heading))))
19338 ;;; Menu entries
19340 ;; Define the Org-mode menus
19341 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19342 '("Tbl"
19343 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19344 ["Next Field" org-cycle (org-at-table-p)]
19345 ["Previous Field" org-shifttab (org-at-table-p)]
19346 ["Next Row" org-return (org-at-table-p)]
19347 "--"
19348 ["Blank Field" org-table-blank-field (org-at-table-p)]
19349 ["Edit Field" org-table-edit-field (org-at-table-p)]
19350 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19351 "--"
19352 ("Column"
19353 ["Move Column Left" org-metaleft (org-at-table-p)]
19354 ["Move Column Right" org-metaright (org-at-table-p)]
19355 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19356 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19357 ("Row"
19358 ["Move Row Up" org-metaup (org-at-table-p)]
19359 ["Move Row Down" org-metadown (org-at-table-p)]
19360 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19361 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19362 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19363 "--"
19364 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19365 ("Rectangle"
19366 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19367 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19368 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19369 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19370 "--"
19371 ("Calculate"
19372 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19373 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19374 ["Edit Formulas" org-edit-special (org-at-table-p)]
19375 "--"
19376 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19377 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19378 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19379 "--"
19380 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19381 "--"
19382 ["Sum Column/Rectangle" org-table-sum
19383 (or (org-at-table-p) (org-region-active-p))]
19384 ["Which Column?" org-table-current-column (org-at-table-p)])
19385 ["Debug Formulas"
19386 org-table-toggle-formula-debugger
19387 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19388 ["Show Col/Row Numbers"
19389 org-table-toggle-coordinate-overlays
19390 :style toggle
19391 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19392 "--"
19393 ["Create" org-table-create (and (not (org-at-table-p))
19394 org-enable-table-editor)]
19395 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19396 ["Import from File" org-table-import (not (org-at-table-p))]
19397 ["Export to File" org-table-export (org-at-table-p)]
19398 "--"
19399 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19401 (easy-menu-define org-org-menu org-mode-map "Org menu"
19402 '("Org"
19403 ("Show/Hide"
19404 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19405 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19406 ["Sparse Tree..." org-sparse-tree t]
19407 ["Reveal Context" org-reveal t]
19408 ["Show All" show-all t]
19409 "--"
19410 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19411 "--"
19412 ["New Heading" org-insert-heading t]
19413 ("Navigate Headings"
19414 ["Up" outline-up-heading t]
19415 ["Next" outline-next-visible-heading t]
19416 ["Previous" outline-previous-visible-heading t]
19417 ["Next Same Level" outline-forward-same-level t]
19418 ["Previous Same Level" outline-backward-same-level t]
19419 "--"
19420 ["Jump" org-goto t])
19421 ("Edit Structure"
19422 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19423 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19424 "--"
19425 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19426 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19427 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19428 "--"
19429 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19430 "--"
19431 ["Copy visible text" org-copy-visible t]
19432 "--"
19433 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19434 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19435 ["Demote Heading" org-metaright (not (org-at-table-p))]
19436 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19437 "--"
19438 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19439 "--"
19440 ["Convert to odd levels" org-convert-to-odd-levels t]
19441 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19442 ("Editing"
19443 ["Emphasis..." org-emphasize t]
19444 ["Edit Source Example" org-edit-special t]
19445 "--"
19446 ["Footnote new/jump" org-footnote-action t]
19447 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19448 ("Archive"
19449 ["Archive (default method)" org-archive-subtree-default t]
19450 "--"
19451 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19452 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19453 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19455 "--"
19456 ("Hyperlinks"
19457 ["Store Link (Global)" org-store-link t]
19458 ["Find existing link to here" org-occur-link-in-agenda-files t]
19459 ["Insert Link" org-insert-link t]
19460 ["Follow Link" org-open-at-point t]
19461 "--"
19462 ["Next link" org-next-link t]
19463 ["Previous link" org-previous-link t]
19464 "--"
19465 ["Descriptive Links"
19466 org-toggle-link-display
19467 :style radio
19468 :selected org-descriptive-links
19470 ["Literal Links"
19471 org-toggle-link-display
19472 :style radio
19473 :selected (not org-descriptive-links)])
19474 "--"
19475 ("TODO Lists"
19476 ["TODO/DONE/-" org-todo t]
19477 ("Select keyword"
19478 ["Next keyword" org-shiftright (org-at-heading-p)]
19479 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19480 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19481 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19482 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19483 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19484 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19485 "--"
19486 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19487 :selected org-enforce-todo-dependencies :style toggle :active t]
19488 "Settings for tree at point"
19489 ["Do Children sequentially" org-toggle-ordered-property :style radio
19490 :selected (org-entry-get nil "ORDERED")
19491 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19492 ["Do Children parallel" org-toggle-ordered-property :style radio
19493 :selected (not (org-entry-get nil "ORDERED"))
19494 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19495 "--"
19496 ["Set Priority" org-priority t]
19497 ["Priority Up" org-shiftup t]
19498 ["Priority Down" org-shiftdown t]
19499 "--"
19500 ["Get news from all feeds" org-feed-update-all t]
19501 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19502 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19503 ("TAGS and Properties"
19504 ["Set Tags" org-set-tags-command t]
19505 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19506 "--"
19507 ["Set property" org-set-property t]
19508 ["Column view of properties" org-columns t]
19509 ["Insert Column View DBlock" org-insert-columns-dblock t])
19510 ("Dates and Scheduling"
19511 ["Timestamp" org-time-stamp t]
19512 ["Timestamp (inactive)" org-time-stamp-inactive t]
19513 ("Change Date"
19514 ["1 Day Later" org-shiftright t]
19515 ["1 Day Earlier" org-shiftleft t]
19516 ["1 ... Later" org-shiftup t]
19517 ["1 ... Earlier" org-shiftdown t])
19518 ["Compute Time Range" org-evaluate-time-range t]
19519 ["Schedule Item" org-schedule t]
19520 ["Deadline" org-deadline t]
19521 "--"
19522 ["Custom time format" org-toggle-time-stamp-overlays
19523 :style radio :selected org-display-custom-times]
19524 "--"
19525 ["Goto Calendar" org-goto-calendar t]
19526 ["Date from Calendar" org-date-from-calendar t]
19527 "--"
19528 ["Start/Restart Timer" org-timer-start t]
19529 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19530 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19531 ["Insert Timer String" org-timer t]
19532 ["Insert Timer Item" org-timer-item t])
19533 ("Logging work"
19534 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19535 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19536 ["Clock out" org-clock-out t]
19537 ["Clock cancel" org-clock-cancel t]
19538 "--"
19539 ["Mark as default task" org-clock-mark-default-task t]
19540 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19541 ["Goto running clock" org-clock-goto t]
19542 "--"
19543 ["Display times" org-clock-display t]
19544 ["Create clock table" org-clock-report t]
19545 "--"
19546 ["Record DONE time"
19547 (progn (setq org-log-done (not org-log-done))
19548 (message "Switching to %s will %s record a timestamp"
19549 (car org-done-keywords)
19550 (if org-log-done "automatically" "not")))
19551 :style toggle :selected org-log-done])
19552 "--"
19553 ["Agenda Command..." org-agenda t]
19554 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19555 ("File List for Agenda")
19556 ("Special views current file"
19557 ["TODO Tree" org-show-todo-tree t]
19558 ["Check Deadlines" org-check-deadlines t]
19559 ["Timeline" org-timeline t]
19560 ["Tags/Property tree" org-match-sparse-tree t])
19561 "--"
19562 ["Export/Publish..." org-export t]
19563 ("LaTeX"
19564 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19565 :selected org-cdlatex-mode]
19566 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19567 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19568 ["Modify math symbol" org-cdlatex-math-modify
19569 (org-inside-LaTeX-fragment-p)]
19570 ["Insert citation" org-reftex-citation t]
19571 "--"
19572 ["Template for BEAMER" (progn (require 'org-beamer)
19573 (org-insert-beamer-options-template)) t])
19574 "--"
19575 ("MobileOrg"
19576 ["Push Files and Views" org-mobile-push t]
19577 ["Get Captured and Flagged" org-mobile-pull t]
19578 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19579 "--"
19580 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19581 "--"
19582 ("Documentation"
19583 ["Show Version" org-version t]
19584 ["Info Documentation" org-info t])
19585 ("Customize"
19586 ["Browse Org Group" org-customize t]
19587 "--"
19588 ["Expand This Menu" org-create-customize-menu
19589 (fboundp 'customize-menu-create)])
19590 ["Send bug report" org-submit-bug-report t]
19591 "--"
19592 ("Refresh/Reload"
19593 ["Refresh setup current buffer" org-mode-restart t]
19594 ["Reload Org (after update)" org-reload t]
19595 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19598 (defun org-info (&optional node)
19599 "Read documentation for Org-mode in the info system.
19600 With optional NODE, go directly to that node."
19601 (interactive)
19602 (info (format "(org)%s" (or node ""))))
19604 ;;;###autoload
19605 (defun org-submit-bug-report ()
19606 "Submit a bug report on Org-mode via mail.
19608 Don't hesitate to report any problems or inaccurate documentation.
19610 If you don't have setup sending mail from (X)Emacs, please copy the
19611 output buffer into your mail program, as it gives us important
19612 information about your Org-mode version and configuration."
19613 (interactive)
19614 (require 'reporter)
19615 (org-load-modules-maybe)
19616 (org-require-autoloaded-modules)
19617 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19618 (reporter-submit-bug-report
19619 "emacs-orgmode@gnu.org"
19620 (org-version nil 'full)
19621 (let (list)
19622 (save-window-excursion
19623 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19624 (delete-other-windows)
19625 (erase-buffer)
19626 (insert "You are about to submit a bug report to the Org-mode mailing list.
19628 We would like to add your full Org-mode and Outline configuration to the
19629 bug report. This greatly simplifies the work of the maintainer and
19630 other experts on the mailing list.
19632 HOWEVER, some variables you have customized may contain private
19633 information. The names of customers, colleagues, or friends, might
19634 appear in the form of file names, tags, todo states, or search strings.
19635 If you answer yes to the prompt, you might want to check and remove
19636 such private information before sending the email.")
19637 (add-text-properties (point-min) (point-max) '(face org-warning))
19638 (when (yes-or-no-p "Include your Org-mode configuration ")
19639 (mapatoms
19640 (lambda (v)
19641 (and (boundp v)
19642 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19643 (or (and (symbol-value v)
19644 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19645 (and
19646 (get v 'custom-type) (get v 'standard-value)
19647 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19648 (push v list)))))
19649 (kill-buffer (get-buffer "*Warn about privacy*"))
19650 list))
19651 nil nil
19652 "Remember to cover the basics, that is, what you expected to happen and
19653 what in fact did happen. You don't know how to make a good report? See
19655 http://orgmode.org/manual/Feedback.html#Feedback
19657 Your bug report will be posted to the Org-mode mailing list.
19658 ------------------------------------------------------------------------")
19659 (save-excursion
19660 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19661 (replace-match "\\1Bug: \\3 [\\2]")))))
19664 (defun org-install-agenda-files-menu ()
19665 (let ((bl (buffer-list)))
19666 (save-excursion
19667 (while bl
19668 (set-buffer (pop bl))
19669 (if (derived-mode-p 'org-mode) (setq bl nil)))
19670 (when (derived-mode-p 'org-mode)
19671 (easy-menu-change
19672 '("Org") "File List for Agenda"
19673 (append
19674 (list
19675 ["Edit File List" (org-edit-agenda-file-list) t]
19676 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19677 ["Remove Current File from List" org-remove-file t]
19678 ["Cycle through agenda files" org-cycle-agenda-files t]
19679 ["Occur in all agenda files" org-occur-in-agenda-files t]
19680 "--")
19681 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19683 ;;;; Documentation
19685 ;;;###autoload
19686 (defun org-require-autoloaded-modules ()
19687 (interactive)
19688 (mapc 'require
19689 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19690 org-docbook org-exp org-html org-icalendar
19691 org-id org-latex
19692 org-publish org-remember org-table
19693 org-timer org-xoxo)))
19695 ;;;###autoload
19696 (defun org-reload (&optional uncompiled)
19697 "Reload all org lisp files.
19698 With prefix arg UNCOMPILED, load the uncompiled versions."
19699 (interactive "P")
19700 (require 'find-func)
19701 (let* ((file-re "^org\\(-.*\\)?\\.el")
19702 (dir-org (file-name-directory (org-find-library-dir "org")))
19703 (dir-org-contrib (ignore-errors
19704 (file-name-directory
19705 (org-find-library-dir "org-contribdir"))))
19706 (babel-files
19707 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19708 (append (list nil "comint" "eval" "exp" "keys"
19709 "lob" "ref" "table" "tangle")
19710 (delq nil
19711 (mapcar
19712 (lambda (lang)
19713 (when (cdr lang) (symbol-name (car lang))))
19714 org-babel-load-languages)))))
19715 (files
19716 (append babel-files
19717 (and dir-org-contrib
19718 (directory-files dir-org-contrib t file-re))
19719 (directory-files dir-org t file-re)))
19720 (remove-re (concat (if (featurep 'xemacs)
19721 "org-colview" "org-colview-xemacs")
19722 "\\'")))
19723 (setq files (mapcar 'file-name-sans-extension files))
19724 (setq files (mapcar
19725 (lambda (x) (if (string-match remove-re x) nil x))
19726 files))
19727 (setq files (delq nil files))
19728 (mapc
19729 (lambda (f)
19730 (when (featurep (intern (file-name-nondirectory f)))
19731 (if (and (not uncompiled)
19732 (file-exists-p (concat f ".elc")))
19733 (load (concat f ".elc") nil nil 'nosuffix)
19734 (load (concat f ".el") nil nil 'nosuffix))))
19735 files)
19736 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19737 (org-version nil 'full 'message))
19739 ;;;###autoload
19740 (defun org-customize ()
19741 "Call the customize function with org as argument."
19742 (interactive)
19743 (org-load-modules-maybe)
19744 (org-require-autoloaded-modules)
19745 (customize-browse 'org))
19747 (defun org-create-customize-menu ()
19748 "Create a full customization menu for Org-mode, insert it into the menu."
19749 (interactive)
19750 (org-load-modules-maybe)
19751 (org-require-autoloaded-modules)
19752 (if (fboundp 'customize-menu-create)
19753 (progn
19754 (easy-menu-change
19755 '("Org") "Customize"
19756 `(["Browse Org group" org-customize t]
19757 "--"
19758 ,(customize-menu-create 'org)
19759 ["Set" Custom-set t]
19760 ["Save" Custom-save t]
19761 ["Reset to Current" Custom-reset-current t]
19762 ["Reset to Saved" Custom-reset-saved t]
19763 ["Reset to Standard Settings" Custom-reset-standard t]))
19764 (message "\"Org\"-menu now contains full customization menu"))
19765 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19767 ;;;; Miscellaneous stuff
19769 ;;; Generally useful functions
19771 (defun org-get-at-bol (property)
19772 "Get text property PROPERTY at beginning of line."
19773 (get-text-property (point-at-bol) property))
19775 (defun org-find-text-property-in-string (prop s)
19776 "Return the first non-nil value of property PROP in string S."
19777 (or (get-text-property 0 prop s)
19778 (get-text-property (or (next-single-property-change 0 prop s) 0)
19779 prop s)))
19781 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19782 "Display the given MESSAGE as a warning."
19783 (if (fboundp 'display-warning)
19784 (display-warning 'org message
19785 (if (featurep 'xemacs) 'warning :warning))
19786 (let ((buf (get-buffer-create "*Org warnings*")))
19787 (with-current-buffer buf
19788 (goto-char (point-max))
19789 (insert "Warning (Org): " message)
19790 (unless (bolp)
19791 (newline)))
19792 (display-buffer buf)
19793 (sit-for 0))))
19795 (defun org-eval (form)
19796 "Eval FORM and return result."
19797 (condition-case error
19798 (eval form)
19799 (error (format "%%![Error: %s]" error))))
19801 (defun org-in-clocktable-p ()
19802 "Check if the cursor is in a clocktable."
19803 (let ((pos (point)) start)
19804 (save-excursion
19805 (end-of-line 1)
19806 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19807 (setq start (match-beginning 0))
19808 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19809 (>= (match-end 0) pos)
19810 start))))
19812 (defun org-in-commented-line ()
19813 "Is point in a line starting with `#'?"
19814 (equal (char-after (point-at-bol)) ?#))
19816 (defun org-in-indented-comment-line ()
19817 "Is point in a line starting with `#' after some white space?"
19818 (save-excursion
19819 (save-match-data
19820 (goto-char (point-at-bol))
19821 (looking-at "[ \t]*#"))))
19823 (defun org-in-verbatim-emphasis ()
19824 (save-match-data
19825 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19827 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19828 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19829 (if (and marker (marker-buffer marker)
19830 (buffer-live-p (marker-buffer marker)))
19831 (progn
19832 (org-pop-to-buffer-same-window (marker-buffer marker))
19833 (if (or (> marker (point-max)) (< marker (point-min)))
19834 (widen))
19835 (goto-char marker)
19836 (org-show-context 'org-goto))
19837 (if bookmark
19838 (bookmark-jump bookmark)
19839 (error "Cannot find location"))))
19841 (defun org-quote-csv-field (s)
19842 "Quote field for inclusion in CSV material."
19843 (if (string-match "[\",]" s)
19844 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19847 (defun org-force-self-insert (N)
19848 "Needed to enforce self-insert under remapping."
19849 (interactive "p")
19850 (self-insert-command N))
19852 (defun org-string-width (s)
19853 "Compute width of string, ignoring invisible characters.
19854 This ignores character with invisibility property `org-link', and also
19855 characters with property `org-cwidth', because these will become invisible
19856 upon the next fontification round."
19857 (let (b l)
19858 (when (or (eq t buffer-invisibility-spec)
19859 (assq 'org-link buffer-invisibility-spec))
19860 (while (setq b (text-property-any 0 (length s)
19861 'invisible 'org-link s))
19862 (setq s (concat (substring s 0 b)
19863 (substring s (or (next-single-property-change
19864 b 'invisible s) (length s)))))))
19865 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19866 (setq s (concat (substring s 0 b)
19867 (substring s (or (next-single-property-change
19868 b 'org-cwidth s) (length s))))))
19869 (setq l (string-width s) b -1)
19870 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19871 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19874 (defun org-shorten-string (s maxlength)
19875 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19876 If the string is shorter or has length MAXLENGTH, just return the
19877 original string. If it is longer, the functions finds a space in the
19878 string, breaks this string off at that locations and adds three dots
19879 as ellipsis. Including the ellipsis, the string will not be longer
19880 than MAXLENGTH. If finding a good breaking point in the string does
19881 not work, the string is just chopped off in the middle of a word
19882 if necessary."
19883 (if (<= (length s) maxlength)
19885 (let* ((n (max (- maxlength 4) 1))
19886 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19887 (if (string-match re s)
19888 (concat (match-string 1 s) "...")
19889 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19891 (defun org-get-indentation (&optional line)
19892 "Get the indentation of the current line, interpreting tabs.
19893 When LINE is given, assume it represents a line and compute its indentation."
19894 (if line
19895 (if (string-match "^ *" (org-remove-tabs line))
19896 (match-end 0))
19897 (save-excursion
19898 (beginning-of-line 1)
19899 (skip-chars-forward " \t")
19900 (current-column))))
19902 (defun org-get-string-indentation (s)
19903 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19904 (let ((n -1) (i 0) (w tab-width) c)
19905 (catch 'exit
19906 (while (< (setq n (1+ n)) (length s))
19907 (setq c (aref s n))
19908 (cond ((= c ?\ ) (setq i (1+ i)))
19909 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19910 (t (throw 'exit t)))))
19913 (defun org-remove-tabs (s &optional width)
19914 "Replace tabulators in S with spaces.
19915 Assumes that s is a single line, starting in column 0."
19916 (setq width (or width tab-width))
19917 (while (string-match "\t" s)
19918 (setq s (replace-match
19919 (make-string
19920 (- (* width (/ (+ (match-beginning 0) width) width))
19921 (match-beginning 0)) ?\ )
19922 t t s)))
19925 (defun org-fix-indentation (line ind)
19926 "Fix indentation in LINE.
19927 IND is a cons cell with target and minimum indentation.
19928 If the current indentation in LINE is smaller than the minimum,
19929 leave it alone. If it is larger than ind, set it to the target."
19930 (let* ((l (org-remove-tabs line))
19931 (i (org-get-indentation l))
19932 (i1 (car ind)) (i2 (cdr ind)))
19933 (if (>= i i2) (setq l (substring line i2)))
19934 (if (> i1 0)
19935 (concat (make-string i1 ?\ ) l)
19936 l)))
19938 (defun org-remove-indentation (code &optional n)
19939 "Remove the maximum common indentation from the lines in CODE.
19940 N may optionally be the number of spaces to remove."
19941 (with-temp-buffer
19942 (insert code)
19943 (org-do-remove-indentation n)
19944 (buffer-string)))
19946 (defun org-do-remove-indentation (&optional n)
19947 "Remove the maximum common indentation from the buffer."
19948 (untabify (point-min) (point-max))
19949 (let ((min 10000) re)
19950 (if n
19951 (setq min n)
19952 (goto-char (point-min))
19953 (while (re-search-forward "^ *[^ \n]" nil t)
19954 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19955 (unless (or (= min 0) (= min 10000))
19956 (setq re (format "^ \\{%d\\}" min))
19957 (goto-char (point-min))
19958 (while (re-search-forward re nil t)
19959 (replace-match "")
19960 (end-of-line 1))
19961 min)))
19963 (defun org-fill-template (template alist)
19964 "Find each %key of ALIST in TEMPLATE and replace it."
19965 (let ((case-fold-search nil)
19966 entry key value)
19967 (setq alist (sort (copy-sequence alist)
19968 (lambda (a b) (< (length (car a)) (length (car b))))))
19969 (while (setq entry (pop alist))
19970 (setq template
19971 (replace-regexp-in-string
19972 (concat "%" (regexp-quote (car entry)))
19973 (cdr entry) template t t)))
19974 template))
19976 (defun org-base-buffer (buffer)
19977 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19978 (if (not buffer)
19979 buffer
19980 (or (buffer-base-buffer buffer)
19981 buffer)))
19983 (defun org-trim (s)
19984 "Remove whitespace at beginning and end of string."
19985 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19986 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19989 (defun org-wrap (string &optional width lines)
19990 "Wrap string to either a number of lines, or a width in characters.
19991 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19992 that costs. If there is a word longer than WIDTH, the text is actually
19993 wrapped to the length of that word.
19994 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19995 many lines, whatever width that takes.
19996 The return value is a list of lines, without newlines at the end."
19997 (let* ((words (org-split-string string "[ \t\n]+"))
19998 (maxword (apply 'max (mapcar 'org-string-width words)))
19999 w ll)
20000 (cond (width
20001 (org-do-wrap words (max maxword width)))
20002 (lines
20003 (setq w maxword)
20004 (setq ll (org-do-wrap words maxword))
20005 (if (<= (length ll) lines)
20007 (setq ll words)
20008 (while (> (length ll) lines)
20009 (setq w (1+ w))
20010 (setq ll (org-do-wrap words w)))
20011 ll))
20012 (t (error "Cannot wrap this")))))
20014 (defun org-do-wrap (words width)
20015 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20016 (let (lines line)
20017 (while words
20018 (setq line (pop words))
20019 (while (and words (< (+ (length line) (length (car words))) width))
20020 (setq line (concat line " " (pop words))))
20021 (setq lines (push line lines)))
20022 (nreverse lines)))
20024 (defun org-split-string (string &optional separators)
20025 "Splits STRING into substrings at SEPARATORS.
20026 No empty strings are returned if there are matches at the beginning
20027 and end of string."
20028 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20029 (start 0)
20030 notfirst
20031 (list nil))
20032 (while (and (string-match rexp string
20033 (if (and notfirst
20034 (= start (match-beginning 0))
20035 (< start (length string)))
20036 (1+ start) start))
20037 (< (match-beginning 0) (length string)))
20038 (setq notfirst t)
20039 (or (eq (match-beginning 0) 0)
20040 (and (eq (match-beginning 0) (match-end 0))
20041 (eq (match-beginning 0) start))
20042 (setq list
20043 (cons (substring string start (match-beginning 0))
20044 list)))
20045 (setq start (match-end 0)))
20046 (or (eq start (length string))
20047 (setq list
20048 (cons (substring string start)
20049 list)))
20050 (nreverse list)))
20052 (defun org-quote-vert (s)
20053 "Replace \"|\" with \"\\vert\"."
20054 (while (string-match "|" s)
20055 (setq s (replace-match "\\vert" t t s)))
20058 (defun org-uuidgen-p (s)
20059 "Is S an ID created by UUIDGEN?"
20060 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20062 (defun org-in-src-block-p nil
20063 "Whether point is in a code source block."
20064 (let (ov)
20065 (when (setq ov (overlays-at (point)))
20066 (memq 'org-block-background
20067 (overlay-properties
20068 (car ov))))))
20070 (defun org-context ()
20071 "Return a list of contexts of the current cursor position.
20072 If several contexts apply, all are returned.
20073 Each context entry is a list with a symbol naming the context, and
20074 two positions indicating start and end of the context. Possible
20075 contexts are:
20077 :headline anywhere in a headline
20078 :headline-stars on the leading stars in a headline
20079 :todo-keyword on a TODO keyword (including DONE) in a headline
20080 :tags on the TAGS in a headline
20081 :priority on the priority cookie in a headline
20082 :item on the first line of a plain list item
20083 :item-bullet on the bullet/number of a plain list item
20084 :checkbox on the checkbox in a plain list item
20085 :table in an org-mode table
20086 :table-special on a special filed in a table
20087 :table-table in a table.el table
20088 :clocktable in a clocktable
20089 :src-block in a source block
20090 :link on a hyperlink
20091 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20092 :target on a <<target>>
20093 :radio-target on a <<<radio-target>>>
20094 :latex-fragment on a LaTeX fragment
20095 :latex-preview on a LaTeX fragment with overlaid preview image
20097 This function expects the position to be visible because it uses font-lock
20098 faces as a help to recognize the following contexts: :table-special, :link,
20099 and :keyword."
20100 (let* ((f (get-text-property (point) 'face))
20101 (faces (if (listp f) f (list f)))
20102 (case-fold-search t)
20103 (p (point)) clist o)
20104 ;; First the large context
20105 (cond
20106 ((org-at-heading-p t)
20107 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20108 (when (progn
20109 (beginning-of-line 1)
20110 (looking-at org-todo-line-tags-regexp))
20111 (push (org-point-in-group p 1 :headline-stars) clist)
20112 (push (org-point-in-group p 2 :todo-keyword) clist)
20113 (push (org-point-in-group p 4 :tags) clist))
20114 (goto-char p)
20115 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20116 (if (looking-at "\\[#[A-Z0-9]\\]")
20117 (push (org-point-in-group p 0 :priority) clist)))
20119 ((org-at-item-p)
20120 (push (org-point-in-group p 2 :item-bullet) clist)
20121 (push (list :item (point-at-bol)
20122 (save-excursion (org-end-of-item) (point)))
20123 clist)
20124 (and (org-at-item-checkbox-p)
20125 (push (org-point-in-group p 0 :checkbox) clist)))
20127 ((org-at-table-p)
20128 (push (list :table (org-table-begin) (org-table-end)) clist)
20129 (if (memq 'org-formula faces)
20130 (push (list :table-special
20131 (previous-single-property-change p 'face)
20132 (next-single-property-change p 'face)) clist)))
20133 ((org-at-table-p 'any)
20134 (push (list :table-table) clist)))
20135 (goto-char p)
20137 ;; New the "medium" contexts: clocktables, source blocks
20138 (cond ((org-in-clocktable-p)
20139 (push (list :clocktable
20140 (and (or (looking-at "#\\+BEGIN: clocktable")
20141 (search-backward "#+BEGIN: clocktable" nil t))
20142 (match-beginning 0))
20143 (and (re-search-forward "#\\+END:?" nil t)
20144 (match-end 0))) clist))
20145 ((org-in-src-block-p)
20146 (push (list :src-block
20147 (and (or (looking-at "#\\+BEGIN_SRC")
20148 (search-backward "#+BEGIN_SRC" nil t))
20149 (match-beginning 0))
20150 (and (search-forward "#+END_SRC" nil t)
20151 (match-beginning 0))) clist)))
20152 (goto-char p)
20154 ;; Now the small context
20155 (cond
20156 ((org-at-timestamp-p)
20157 (push (org-point-in-group p 0 :timestamp) clist))
20158 ((memq 'org-link faces)
20159 (push (list :link
20160 (previous-single-property-change p 'face)
20161 (next-single-property-change p 'face)) clist))
20162 ((memq 'org-special-keyword faces)
20163 (push (list :keyword
20164 (previous-single-property-change p 'face)
20165 (next-single-property-change p 'face)) clist))
20166 ((org-at-target-p)
20167 (push (org-point-in-group p 0 :target) clist)
20168 (goto-char (1- (match-beginning 0)))
20169 (if (looking-at org-radio-target-regexp)
20170 (push (org-point-in-group p 0 :radio-target) clist))
20171 (goto-char p))
20172 ((setq o (car (delq nil
20173 (mapcar
20174 (lambda (x)
20175 (if (memq x org-latex-fragment-image-overlays) x))
20176 (overlays-at (point))))))
20177 (push (list :latex-fragment
20178 (overlay-start o) (overlay-end o)) clist)
20179 (push (list :latex-preview
20180 (overlay-start o) (overlay-end o)) clist))
20181 ((org-inside-LaTeX-fragment-p)
20182 ;; FIXME: positions wrong.
20183 (push (list :latex-fragment (point) (point)) clist)))
20185 (setq clist (nreverse (delq nil clist)))
20186 clist))
20188 ;; FIXME: Compare with at-regexp-p Do we need both?
20189 (defun org-in-regexp (re &optional nlines visually)
20190 "Check if point is inside a match of regexp.
20191 Normally only the current line is checked, but you can include NLINES extra
20192 lines both before and after point into the search.
20193 If VISUALLY is set, require that the cursor is not after the match but
20194 really on, so that the block visually is on the match."
20195 (catch 'exit
20196 (let ((pos (point))
20197 (eol (point-at-eol (+ 1 (or nlines 0))))
20198 (inc (if visually 1 0)))
20199 (save-excursion
20200 (beginning-of-line (- 1 (or nlines 0)))
20201 (while (re-search-forward re eol t)
20202 (if (and (<= (match-beginning 0) pos)
20203 (>= (+ inc (match-end 0)) pos))
20204 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20206 (defun org-at-regexp-p (regexp)
20207 "Is point inside a match of REGEXP in the current line?"
20208 (catch 'exit
20209 (save-excursion
20210 (let ((pos (point)) (end (point-at-eol)))
20211 (beginning-of-line 1)
20212 (while (re-search-forward regexp end t)
20213 (if (and (<= (match-beginning 0) pos)
20214 (>= (match-end 0) pos))
20215 (throw 'exit t)))
20216 nil))))
20218 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20219 "Non-nil when point is between matches of START-RE and END-RE.
20221 Also return a non-nil value when point is on one of the matches.
20223 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20224 buffer positions. Default values are the positions of headlines
20225 surrounding the point.
20227 The functions returns a cons cell whose car (resp. cdr) is the
20228 position before START-RE (resp. after END-RE)."
20229 (save-match-data
20230 (let ((pos (point))
20231 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20232 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20233 beg end)
20234 (save-excursion
20235 ;; Point is on a block when on START-RE or if START-RE can be
20236 ;; found before it...
20237 (and (or (org-at-regexp-p start-re)
20238 (re-search-backward start-re limit-up t))
20239 (setq beg (match-beginning 0))
20240 ;; ... and END-RE after it...
20241 (goto-char (match-end 0))
20242 (re-search-forward end-re limit-down t)
20243 (> (setq end (match-end 0)) pos)
20244 ;; ... without another START-RE in-between.
20245 (goto-char (match-beginning 0))
20246 (not (re-search-backward start-re (1+ beg) t))
20247 ;; Return value.
20248 (cons beg end))))))
20250 (defun org-in-block-p (names)
20251 "Non-nil when point belongs to a block whose name belongs to NAMES.
20253 NAMES is a list of strings containing names of blocks.
20255 Return first block name matched, or nil. Beware that in case of
20256 nested blocks, the returned name may not belong to the closest
20257 block from point."
20258 (save-match-data
20259 (catch 'exit
20260 (let ((case-fold-search t)
20261 (lim-up (save-excursion (outline-previous-heading)))
20262 (lim-down (save-excursion (outline-next-heading))))
20263 (mapc (lambda (name)
20264 (let ((n (regexp-quote name)))
20265 (when (org-between-regexps-p
20266 (concat "^[ \t]*#\\+begin_" n)
20267 (concat "^[ \t]*#\\+end_" n)
20268 lim-up lim-down)
20269 (throw 'exit n))))
20270 names))
20271 nil)))
20273 (defun org-occur-in-agenda-files (regexp &optional nlines)
20274 "Call `multi-occur' with buffers for all agenda files."
20275 (interactive "sOrg-files matching: \np")
20276 (let* ((files (org-agenda-files))
20277 (tnames (mapcar 'file-truename files))
20278 (extra org-agenda-text-search-extra-files)
20280 (when (eq (car extra) 'agenda-archives)
20281 (setq extra (cdr extra))
20282 (setq files (org-add-archive-files files)))
20283 (while (setq f (pop extra))
20284 (unless (member (file-truename f) tnames)
20285 (add-to-list 'files f 'append)
20286 (add-to-list 'tnames (file-truename f) 'append)))
20287 (multi-occur
20288 (mapcar (lambda (x)
20289 (with-current-buffer
20290 (or (get-file-buffer x) (find-file-noselect x))
20291 (widen)
20292 (current-buffer)))
20293 files)
20294 regexp)))
20296 (if (boundp 'occur-mode-find-occurrence-hook)
20297 ;; Emacs 23
20298 (add-hook 'occur-mode-find-occurrence-hook
20299 (lambda ()
20300 (when (derived-mode-p 'org-mode)
20301 (org-reveal))))
20302 ;; Emacs 22
20303 (defadvice occur-mode-goto-occurrence
20304 (after org-occur-reveal activate)
20305 (and (derived-mode-p 'org-mode) (org-reveal)))
20306 (defadvice occur-mode-goto-occurrence-other-window
20307 (after org-occur-reveal activate)
20308 (and (derived-mode-p 'org-mode) (org-reveal)))
20309 (defadvice occur-mode-display-occurrence
20310 (after org-occur-reveal activate)
20311 (when (derived-mode-p 'org-mode)
20312 (let ((pos (occur-mode-find-occurrence)))
20313 (with-current-buffer (marker-buffer pos)
20314 (save-excursion
20315 (goto-char pos)
20316 (org-reveal)))))))
20318 (defun org-occur-link-in-agenda-files ()
20319 "Create a link and search for it in the agendas.
20320 The link is not stored in `org-stored-links', it is just created
20321 for the search purpose."
20322 (interactive)
20323 (let ((link (condition-case nil
20324 (org-store-link nil)
20325 (error "Unable to create a link to here"))))
20326 (org-occur-in-agenda-files (regexp-quote link))))
20328 (defun org-uniquify (list)
20329 "Remove duplicate elements from LIST."
20330 (let (res)
20331 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20332 res))
20334 (defun org-delete-all (elts list)
20335 "Remove all elements in ELTS from LIST."
20336 (while elts
20337 (setq list (delete (pop elts) list)))
20338 list)
20340 (defun org-count (cl-item cl-seq)
20341 "Count the number of occurrences of ITEM in SEQ.
20342 Taken from `count' in cl-seq.el with all keyword arguments removed."
20343 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20344 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20345 (while (< cl-start cl-end)
20346 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20347 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20348 (setq cl-start (1+ cl-start)))
20349 cl-count))
20351 (defun org-remove-if (predicate seq)
20352 "Remove everything from SEQ that fulfills PREDICATE."
20353 (let (res e)
20354 (while seq
20355 (setq e (pop seq))
20356 (if (not (funcall predicate e)) (push e res)))
20357 (nreverse res)))
20359 (defun org-remove-if-not (predicate seq)
20360 "Remove everything from SEQ that does not fulfill PREDICATE."
20361 (let (res e)
20362 (while seq
20363 (setq e (pop seq))
20364 (if (funcall predicate e) (push e res)))
20365 (nreverse res)))
20367 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20368 "Reduce two-argument FUNCTION across SEQ.
20369 Taken from `reduce' in cl-seq.el with all keyword arguments but
20370 \":initial-value\" removed."
20371 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20372 (cadr (memq :initial-value cl-keys)))
20373 (cl-seq (pop cl-seq))
20374 (t (funcall cl-func)))))
20375 (while cl-seq
20376 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20377 cl-accum))
20379 (defun org-back-over-empty-lines ()
20380 "Move backwards over whitespace, to the beginning of the first empty line.
20381 Returns the number of empty lines passed."
20382 (let ((pos (point)))
20383 (if (cdr (assoc 'heading org-blank-before-new-entry))
20384 (skip-chars-backward " \t\n\r")
20385 (unless (eobp)
20386 (forward-line -1)))
20387 (beginning-of-line 2)
20388 (goto-char (min (point) pos))
20389 (count-lines (point) pos)))
20391 (defun org-skip-whitespace ()
20392 (skip-chars-forward " \t\n\r"))
20394 (defun org-point-in-group (point group &optional context)
20395 "Check if POINT is in match-group GROUP.
20396 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20397 match. If the match group does not exist or point is not inside it,
20398 return nil."
20399 (and (match-beginning group)
20400 (>= point (match-beginning group))
20401 (<= point (match-end group))
20402 (if context
20403 (list context (match-beginning group) (match-end group))
20404 t)))
20406 (defun org-switch-to-buffer-other-window (&rest args)
20407 "Switch to buffer in a second window on the current frame.
20408 In particular, do not allow pop-up frames.
20409 Returns the newly created buffer."
20410 (let (pop-up-frames special-display-buffer-names special-display-regexps
20411 special-display-function)
20412 (apply 'switch-to-buffer-other-window args)))
20414 (defun org-combine-plists (&rest plists)
20415 "Create a single property list from all plists in PLISTS.
20416 The process starts by copying the first list, and then setting properties
20417 from the other lists. Settings in the last list are the most significant
20418 ones and overrule settings in the other lists."
20419 (let ((rtn (copy-sequence (pop plists)))
20420 p v ls)
20421 (while plists
20422 (setq ls (pop plists))
20423 (while ls
20424 (setq p (pop ls) v (pop ls))
20425 (setq rtn (plist-put rtn p v))))
20426 rtn))
20428 (defun org-replace-escapes (string table)
20429 "Replace %-escapes in STRING with values in TABLE.
20430 TABLE is an association list with keys like \"%a\" and string values.
20431 The sequences in STRING may contain normal field width and padding information,
20432 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20433 so values can contain further %-escapes if they are define later in TABLE."
20434 (let ((tbl (copy-alist table))
20435 (case-fold-search nil)
20436 (pchg 0)
20437 e re rpl)
20438 (while (setq e (pop tbl))
20439 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20440 (when (and (cdr e) (string-match re (cdr e)))
20441 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20442 (safe "SREF"))
20443 (add-text-properties 0 3 (list 'sref sref) safe)
20444 (setcdr e (replace-match safe t t (cdr e)))))
20445 (while (string-match re string)
20446 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20447 (cdr e)))
20448 (setq string (replace-match rpl t t string))))
20449 (while (setq pchg (next-property-change pchg string))
20450 (let ((sref (get-text-property pchg 'sref string)))
20451 (when (and sref (string-match "SREF" string pchg))
20452 (setq string (replace-match sref t t string)))))
20453 string))
20455 (defun org-sublist (list start end)
20456 "Return a section of LIST, from START to END.
20457 Counting starts at 1."
20458 (let (rtn (c start))
20459 (setq list (nthcdr (1- start) list))
20460 (while (and list (<= c end))
20461 (push (pop list) rtn)
20462 (setq c (1+ c)))
20463 (nreverse rtn)))
20465 (defun org-find-base-buffer-visiting (file)
20466 "Like `find-buffer-visiting' but always return the base buffer and
20467 not an indirect buffer."
20468 (let ((buf (or (get-file-buffer file)
20469 (find-buffer-visiting file))))
20470 (if buf
20471 (or (buffer-base-buffer buf) buf)
20472 nil)))
20474 (defun org-image-file-name-regexp (&optional extensions)
20475 "Return regexp matching the file names of images.
20476 If EXTENSIONS is given, only match these."
20477 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20478 (image-file-name-regexp)
20479 (let ((image-file-name-extensions
20480 (or extensions
20481 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20482 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20483 (concat "\\."
20484 (regexp-opt (nconc (mapcar 'upcase
20485 image-file-name-extensions)
20486 image-file-name-extensions)
20488 "\\'"))))
20490 (defun org-file-image-p (file &optional extensions)
20491 "Return non-nil if FILE is an image."
20492 (save-match-data
20493 (string-match (org-image-file-name-regexp extensions) file)))
20495 (defun org-get-cursor-date ()
20496 "Return the date at cursor in as a time.
20497 This works in the calendar and in the agenda, anywhere else it just
20498 returns the current time."
20499 (let (date day defd)
20500 (cond
20501 ((eq major-mode 'calendar-mode)
20502 (setq date (calendar-cursor-to-date)
20503 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20504 ((eq major-mode 'org-agenda-mode)
20505 (setq day (get-text-property (point) 'day))
20506 (if day
20507 (setq date (calendar-gregorian-from-absolute day)
20508 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20509 (nth 2 date))))))
20510 (or defd (current-time))))
20512 (defvar org-agenda-action-marker (make-marker)
20513 "Marker pointing to the entry for the next agenda action.")
20515 (defun org-mark-entry-for-agenda-action ()
20516 "Mark the current entry as target of an agenda action.
20517 Agenda actions are actions executed from the agenda with the key `k',
20518 which make use of the date at the cursor."
20519 (interactive)
20520 (move-marker org-agenda-action-marker
20521 (save-excursion (org-back-to-heading t) (point))
20522 (current-buffer))
20523 (message
20524 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20526 (defun org-mark-subtree ()
20527 "Mark the current subtree.
20528 This puts point at the start of the current subtree, and mark at the end.
20530 If point is in an inline task, mark that task instead."
20531 (interactive)
20532 (let ((inline-task-p
20533 (and (featurep 'org-inlinetask)
20534 (org-inlinetask-in-task-p)))
20535 (beg))
20536 ;; Get beginning of subtree
20537 (cond
20538 (inline-task-p (org-inlinetask-goto-beginning))
20539 ((org-at-heading-p) (beginning-of-line))
20540 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20541 (setq beg (point))
20542 ;; Get end of it
20543 (if inline-task-p
20544 (org-inlinetask-goto-end)
20545 (org-end-of-subtree))
20546 ;; Mark zone
20547 (push-mark (point) nil t)
20548 (goto-char beg)))
20550 ;;; Paragraph filling stuff.
20551 ;; We want this to be just right, so use the full arsenal.
20553 (defun org-indent-line ()
20554 "Indent line depending on context."
20555 (interactive)
20556 (let* ((pos (point))
20557 (itemp (org-at-item-p))
20558 (case-fold-search t)
20559 (org-drawer-regexp (or org-drawer-regexp "\000"))
20560 (inline-task-p (and (featurep 'org-inlinetask)
20561 (org-inlinetask-in-task-p)))
20562 (inline-re (and inline-task-p
20563 (org-inlinetask-outline-regexp)))
20564 column)
20565 (beginning-of-line 1)
20566 (cond
20567 ;; Comments
20568 ((looking-at "# ") (setq column 0))
20569 ;; Headings
20570 ((looking-at org-outline-regexp) (setq column 0))
20571 ;; Included files
20572 ((looking-at "#\\+include:") (setq column 0))
20573 ;; Footnote definition
20574 ((looking-at org-footnote-definition-re) (setq column 0))
20575 ;; Literal examples
20576 ((looking-at "[ \t]*:\\( \\|$\\)")
20577 (setq column (org-get-indentation))) ; do nothing
20578 ;; Lists
20579 ((ignore-errors (goto-char (org-in-item-p)))
20580 (setq column (if itemp
20581 (org-get-indentation)
20582 (org-list-item-body-column (point))))
20583 (goto-char pos))
20584 ;; Drawers
20585 ((and (looking-at "[ \t]*:END:")
20586 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20587 (save-excursion
20588 (goto-char (1- (match-beginning 1)))
20589 (setq column (current-column))))
20590 ;; Special blocks
20591 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20592 (save-excursion
20593 (re-search-backward
20594 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20595 (setq column (org-get-indentation (match-string 0))))
20596 ((and (not (looking-at "[ \t]*#\\+begin_"))
20597 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20598 (save-excursion
20599 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20600 (setq column
20601 (cond ((equal (downcase (match-string 1)) "src")
20602 ;; src blocks: let `org-edit-src-exit' handle them
20603 (org-get-indentation))
20604 ((equal (downcase (match-string 1)) "example")
20605 (max (org-get-indentation)
20606 (org-get-indentation (match-string 0))))
20608 (org-get-indentation (match-string 0))))))
20609 ;; This line has nothing special, look at the previous relevant
20610 ;; line to compute indentation
20612 (beginning-of-line 0)
20613 (while (and (not (bobp))
20614 (not (looking-at org-drawer-regexp))
20615 ;; When point started in an inline task, do not move
20616 ;; above task starting line.
20617 (not (and inline-task-p (looking-at inline-re)))
20618 ;; Skip drawers, blocks, empty lines, verbatim,
20619 ;; comments, tables, footnotes definitions, lists,
20620 ;; inline tasks.
20621 (or (and (looking-at "[ \t]*:END:")
20622 (re-search-backward org-drawer-regexp nil t))
20623 (and (looking-at "[ \t]*#\\+end_")
20624 (re-search-backward "[ \t]*#\\+begin_"nil t))
20625 (looking-at "[ \t]*[\n:#|]")
20626 (looking-at org-footnote-definition-re)
20627 (and (ignore-errors (goto-char (org-in-item-p)))
20628 (goto-char
20629 (org-list-get-top-point (org-list-struct))))
20630 (and (not inline-task-p)
20631 (featurep 'org-inlinetask)
20632 (org-inlinetask-in-task-p)
20633 (or (org-inlinetask-goto-beginning) t))))
20634 (beginning-of-line 0))
20635 (cond
20636 ;; There was an heading above.
20637 ((looking-at "\\*+[ \t]+")
20638 (if (not org-adapt-indentation)
20639 (setq column 0)
20640 (goto-char (match-end 0))
20641 (setq column (current-column))))
20642 ;; A drawer had started and is unfinished
20643 ((looking-at org-drawer-regexp)
20644 (goto-char (1- (match-beginning 1)))
20645 (setq column (current-column)))
20646 ;; Else, nothing noticeable found: get indentation and go on.
20647 (t (setq column (org-get-indentation))))))
20648 ;; Now apply indentation and move cursor accordingly
20649 (goto-char pos)
20650 (if (<= (current-column) (current-indentation))
20651 (org-indent-line-to column)
20652 (save-excursion (org-indent-line-to column)))
20653 ;; Special polishing for properties, see `org-property-format'
20654 (setq column (current-column))
20655 (beginning-of-line 1)
20656 (if (looking-at
20657 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20658 (replace-match (concat (match-string 1)
20659 (format org-property-format
20660 (match-string 2) (match-string 3)))
20661 t t))
20662 (org-move-to-column column)
20663 (when (and orgstruct-is-++ (eq pos (point)))
20664 (org-let org-fb-vars
20665 '(indent-according-to-mode)))))
20667 (defun org-indent-drawer ()
20668 "Indent the drawer at point."
20669 (interactive)
20670 (let ((p (point))
20671 (e (and (save-excursion (re-search-forward ":END:" nil t))
20672 (match-end 0)))
20673 (folded
20674 (save-excursion
20675 (end-of-line)
20676 (when (overlays-at (point))
20677 (member 'invisible (overlay-properties
20678 (car (overlays-at (point)))))))))
20679 (when folded (org-cycle))
20680 (indent-for-tab-command)
20681 (while (and (move-beginning-of-line 2) (< (point) e))
20682 (indent-for-tab-command))
20683 (goto-char p)
20684 (when folded (org-cycle)))
20685 (message "Drawer at point indented"))
20687 (defun org-indent-block ()
20688 "Indent the block at point."
20689 (interactive)
20690 (let ((p (point))
20691 (case-fold-search t)
20692 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20693 (match-end 0)))
20694 (folded
20695 (save-excursion
20696 (end-of-line)
20697 (when (overlays-at (point))
20698 (member 'invisible (overlay-properties
20699 (car (overlays-at (point)))))))))
20700 (when folded (org-cycle))
20701 (indent-for-tab-command)
20702 (while (and (move-beginning-of-line 2) (< (point) e))
20703 (indent-for-tab-command))
20704 (goto-char p)
20705 (when folded (org-cycle)))
20706 (message "Block at point indented"))
20708 (defun org-indent-region (start end)
20709 "Indent region."
20710 (interactive "r")
20711 (save-excursion
20712 (let ((line-end (org-current-line end)))
20713 (goto-char start)
20714 (while (< (org-current-line) line-end)
20715 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20716 (t (call-interactively 'org-indent-line)))
20717 (move-beginning-of-line 2)))))
20719 ;; For reference, this is the default value of adaptive-fill-regexp
20720 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20721 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20722 "Variable to store copy of `adaptive-fill-regexp'.
20723 Since `adaptive-fill-regexp' is set to never match, we need to
20724 store a backup of its value before entering `org-mode' so that
20725 the functionality can be provided as a fall-back.")
20727 (defun org-set-autofill-regexps ()
20728 (interactive)
20729 ;; In the paragraph separator we include headlines, because filling
20730 ;; text in a line directly attached to a headline would otherwise
20731 ;; fill the headline as well.
20732 (org-set-local 'comment-start-skip "^#+[ \t]*")
20733 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20734 ;; The paragraph starter includes hand-formatted lists.
20735 (org-set-local
20736 'paragraph-start
20737 (concat
20738 "\f" "\\|"
20739 "[ ]*$" "\\|"
20740 org-outline-regexp "\\|"
20741 "[ \t]*#" "\\|"
20742 (org-item-re) "\\|"
20743 "[ \t]*[:|]" "\\|"
20744 "\\$\\$" "\\|"
20745 "\\\\\\(begin\\|end\\|[][]\\)"))
20746 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20747 ;; But only if the user has not turned off tables or fixed-width regions
20748 (org-set-local
20749 'auto-fill-inhibit-regexp
20750 (concat org-outline-regexp
20751 "\\|#\\+"
20752 "\\|[ \t]*" org-keyword-time-regexp
20753 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20754 (concat
20755 "\\|[ \t]*["
20756 (if org-enable-table-editor "|" "")
20757 (if org-enable-fixed-width-editor ":" "")
20758 "]"))))
20759 ;; We use our own fill-paragraph function, to make sure that tables
20760 ;; and fixed-width regions are not wrapped. That function will pass
20761 ;; through to `fill-paragraph' when appropriate.
20762 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20763 ;; Prevent auto-fill from inserting unwanted new items.
20764 (if (boundp 'fill-nobreak-predicate)
20765 (org-set-local
20766 'fill-nobreak-predicate
20767 (org-uniquify
20768 (append fill-nobreak-predicate
20769 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20770 ;; Adaptive filling: To get full control, first make sure that
20771 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20772 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20773 (org-set-local 'org-adaptive-fill-regexp-backup
20774 adaptive-fill-regexp))
20775 (org-set-local 'adaptive-fill-regexp "\000")
20776 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20777 (org-set-local 'adaptive-fill-function
20778 'org-adaptive-fill-function)
20779 (org-set-local
20780 'align-mode-rules-list
20781 '((org-in-buffer-settings
20782 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20783 (modes . '(org-mode))))))
20785 (defun org-fill-item-nobreak-p ()
20786 "Non-nil when a line break at point would insert a new item."
20787 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20789 (defun org-fill-line-break-nobreak-p ()
20790 "Non-nil when a line break at point would create an Org line break."
20791 (save-excursion
20792 (skip-chars-backward "[ \t]")
20793 (skip-chars-backward "\\\\")
20794 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20796 (defun org-fill-paragraph (&optional justify)
20797 "Re-align a table, pass through to fill-paragraph if no table."
20798 (let ((table-p (org-at-table-p))
20799 (table.el-p (org-at-table.el-p))
20800 (itemp (org-in-item-p))
20801 (srcp (org-in-src-block-p)))
20802 (cond ((and (equal (char-after (point-at-bol)) ?*)
20803 (save-excursion (goto-char (point-at-bol))
20804 (looking-at org-outline-regexp)))
20805 t) ; skip headlines
20806 (table.el-p t) ; skip table.el tables
20807 (table-p (org-table-align) t) ; align Org tables
20808 (srcp ; indent entire src block to prevent
20809 (save-excursion ; fill-paragraph-as-region to mess up
20810 (org-babel-do-in-edit-buffer
20811 (indent-region (point-min) (point-max)))))
20812 (itemp ; align text in items
20813 (let* ((struct (save-excursion (goto-char itemp)
20814 (org-list-struct)))
20815 (parents (org-list-parents-alist struct))
20816 (children (org-list-get-children itemp struct parents))
20817 beg end prev next prefix)
20818 ;; Determine in which part of item point is: before
20819 ;; first child, after last child, between two
20820 ;; sub-lists, or simply in item if there's no child.
20821 (cond
20822 ((not children)
20823 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20824 beg itemp
20825 end (org-list-get-item-end itemp struct)))
20826 ((< (point) (setq next (car children)))
20827 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20828 beg itemp
20829 end next))
20830 ((> (point) (setq prev (car (last children))))
20831 (setq beg (org-list-get-item-end prev struct)
20832 end (org-list-get-item-end itemp struct)
20833 prefix (save-excursion
20834 (goto-char beg)
20835 (skip-chars-forward " \t")
20836 (make-string (current-column) ?\ ))))
20837 (t (catch 'exit
20838 (while (setq next (pop children))
20839 (if (> (point) next)
20840 (setq prev next)
20841 (setq beg (org-list-get-item-end prev struct)
20842 end next
20843 prefix (save-excursion
20844 (goto-char beg)
20845 (skip-chars-forward " \t")
20846 (make-string (current-column) ?\ )))
20847 (throw 'exit nil))))))
20848 ;; Use `fill-paragraph' with buffer narrowed to item
20849 ;; without any child, and with our computed PREFIX.
20850 (org-flet ((fill-context-prefix (from to &optional flr) prefix))
20851 (save-restriction
20852 (narrow-to-region beg end)
20853 (save-excursion (fill-paragraph justify)))) t))
20854 ;; Special case where point is not in a list but is on
20855 ;; a paragraph adjacent to a list: make sure this paragraph
20856 ;; doesn't get merged with the end of the list by narrowing
20857 ;; buffer first.
20858 ((and (derived-mode-p 'org-mode)
20859 (save-excursion (forward-paragraph -1)
20860 (setq itemp (org-in-item-p))))
20861 (let ((struct (save-excursion (goto-char itemp)
20862 (org-list-struct))))
20863 (save-restriction
20864 (narrow-to-region (org-list-get-bottom-point struct)
20865 (save-excursion (forward-paragraph 1)
20866 (point)))
20867 (fill-paragraph justify) t)))
20868 ;; Don't fill schedule/deadline line before a paragraph
20869 ;; This only makes sense in real org-mode buffers
20870 ((and (eq major-mode 'org-mode)
20871 (save-excursion (forward-paragraph -1)
20872 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20873 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20874 (save-restriction
20875 (narrow-to-region (1+ (match-end 0))
20876 (save-excursion (forward-paragraph 1) (point)))
20877 (fill-paragraph justify) t))
20878 ;; Else fall back on fill-paragraph-function as possibly
20879 ;; defined in `org-fb-vars'
20880 (orgstruct-is-++
20881 (org-let org-fb-vars
20882 '(fill-paragraph justify)))
20883 (t nil))))
20885 (defun org-adaptive-fill-function ()
20886 "Return a fill prefix for org-mode files."
20887 (let (itemp)
20888 (save-excursion
20889 (cond
20890 ;; Comment line
20891 ((looking-at "#[ \t]+")
20892 (match-string-no-properties 0))
20893 ;; Plain list item
20894 ((org-at-item-p)
20895 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20896 ;; Point is in a list after `backward-paragraph': original
20897 ;; point wasn't in the list, or filling would have been taken
20898 ;; care of by `org-auto-fill-function', but the list and the
20899 ;; real paragraph are not separated by a blank line. Thus, move
20900 ;; point after the list to go back to real paragraph and
20901 ;; determine fill-prefix.
20902 ((setq itemp (org-in-item-p))
20903 (goto-char itemp)
20904 (let* ((struct (org-list-struct))
20905 (bottom (org-list-get-bottom-point struct)))
20906 (goto-char bottom)
20907 (make-string (org-get-indentation) ?\ )))
20908 ;; Other text
20909 ((looking-at org-adaptive-fill-regexp-backup)
20910 (match-string-no-properties 0))))))
20912 (defun org-auto-fill-function ()
20913 "Auto-fill function."
20914 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20915 (let (itemp prefix)
20916 ;; When in a list, compute an appropriate fill-prefix and make
20917 ;; sure it will be used by `do-auto-fill'.
20918 (cond ((setq itemp (org-in-item-p))
20919 (progn
20920 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20921 (org-flet ((fill-context-prefix (from to &optional flr) prefix))
20922 (do-auto-fill))))
20923 (orgstruct-is-++
20924 (org-let org-fb-vars
20925 '(do-auto-fill)))
20926 (t (do-auto-fill))))))
20928 ;;; Other stuff.
20930 (defun org-toggle-fixed-width-section (arg)
20931 "Toggle the fixed-width export.
20932 If there is no active region, the QUOTE keyword at the current headline is
20933 inserted or removed. When present, it causes the text between this headline
20934 and the next to be exported as fixed-width text, and unmodified.
20935 If there is an active region, this command adds or removes a colon as the
20936 first character of this line. If the first character of a line is a colon,
20937 this line is also exported in fixed-width font."
20938 (interactive "P")
20939 (let* ((cc 0)
20940 (regionp (org-region-active-p))
20941 (beg (if regionp (region-beginning) (point)))
20942 (end (if regionp (region-end)))
20943 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20944 (case-fold-search nil)
20945 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20946 off)
20947 (if regionp
20948 (save-excursion
20949 (goto-char beg)
20950 (setq cc (current-column))
20951 (beginning-of-line 1)
20952 (setq off (looking-at re))
20953 (while (> nlines 0)
20954 (setq nlines (1- nlines))
20955 (beginning-of-line 1)
20956 (cond
20957 (arg
20958 (org-move-to-column cc t)
20959 (insert ": \n")
20960 (forward-line -1))
20961 ((and off (looking-at re))
20962 (replace-match "" t t nil 1))
20963 ((not off) (org-move-to-column cc t) (insert ": ")))
20964 (forward-line 1)))
20965 (save-excursion
20966 (org-back-to-heading)
20967 (cond
20968 ((looking-at (format org-heading-keyword-regexp-format
20969 org-quote-string))
20970 (goto-char (match-end 1))
20971 (looking-at (concat " +" org-quote-string))
20972 (replace-match "" t t)
20973 (when (eolp) (insert " ")))
20974 ((looking-at org-outline-regexp)
20975 (goto-char (match-end 0))
20976 (insert org-quote-string " ")))))))
20978 (defun org-reftex-citation ()
20979 "Use reftex-citation to insert a citation into the buffer.
20980 This looks for a line like
20982 #+BIBLIOGRAPHY: foo plain option:-d
20984 and derives from it that foo.bib is the bibliography file relevant
20985 for this document. It then installs the necessary environment for RefTeX
20986 to work in this buffer and calls `reftex-citation' to insert a citation
20987 into the buffer.
20989 Export of such citations to both LaTeX and HTML is handled by the contributed
20990 package org-exp-bibtex by Taru Karttunen."
20991 (interactive)
20992 (let ((reftex-docstruct-symbol 'rds)
20993 (reftex-cite-format "\\cite{%l}")
20994 rds bib)
20995 (save-excursion
20996 (save-restriction
20997 (widen)
20998 (let ((case-fold-search t)
20999 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21000 (if (not (save-excursion
21001 (or (re-search-forward re nil t)
21002 (re-search-backward re nil t))))
21003 (error "No bibliography defined in file")
21004 (setq bib (concat (match-string 1) ".bib")
21005 rds (list (list 'bib bib)))))))
21006 (call-interactively 'reftex-citation)))
21008 ;;;; Functions extending outline functionality
21010 (defun org-beginning-of-line (&optional arg)
21011 "Go to the beginning of the current line. If that is invisible, continue
21012 to a visible line beginning. This makes the function of C-a more intuitive.
21013 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21014 first attempt, and only move to after the tags when the cursor is already
21015 beyond the end of the headline."
21016 (interactive "P")
21017 (let ((pos (point))
21018 (special (if (consp org-special-ctrl-a/e)
21019 (car org-special-ctrl-a/e)
21020 org-special-ctrl-a/e))
21021 refpos)
21022 (if (org-bound-and-true-p line-move-visual)
21023 (beginning-of-visual-line 1)
21024 (beginning-of-line 1))
21025 (if (and arg (fboundp 'move-beginning-of-line))
21026 (call-interactively 'move-beginning-of-line)
21027 (if (bobp)
21029 (backward-char 1)
21030 (if (org-truely-invisible-p)
21031 (while (and (not (bobp)) (org-truely-invisible-p))
21032 (backward-char 1)
21033 (beginning-of-line 1))
21034 (forward-char 1))))
21035 (when special
21036 (cond
21037 ((and (looking-at org-complex-heading-regexp)
21038 (= (char-after (match-end 1)) ?\ ))
21039 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21040 (point-at-eol)))
21041 (goto-char
21042 (if (eq special t)
21043 (cond ((> pos refpos) refpos)
21044 ((= pos (point)) refpos)
21045 (t (point)))
21046 (cond ((> pos (point)) (point))
21047 ((not (eq last-command this-command)) (point))
21048 (t refpos)))))
21049 ((org-at-item-p)
21050 ;; Being at an item and not looking at an the item means point
21051 ;; was previously moved to beginning of a visual line, which
21052 ;; doesn't contain the item. Therefore, do nothing special,
21053 ;; just stay here.
21054 (when (looking-at org-list-full-item-re)
21055 ;; Set special position at first white space character after
21056 ;; bullet, and check-box, if any.
21057 (let ((after-bullet
21058 (let ((box (match-end 3)))
21059 (if (not box) (match-end 1)
21060 (let ((after (char-after box)))
21061 (if (and after (= after ? )) (1+ box) box))))))
21062 ;; Special case: Move point to special position when
21063 ;; currently after it or at beginning of line.
21064 (if (eq special t)
21065 (when (or (> pos after-bullet) (= (point) pos))
21066 (goto-char after-bullet))
21067 ;; Reversed case: Move point to special position when
21068 ;; point was already at beginning of line and command is
21069 ;; repeated.
21070 (when (and (= (point) pos) (eq last-command this-command))
21071 (goto-char after-bullet))))))))
21072 (org-no-warnings
21073 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21075 (defun org-end-of-line (&optional arg)
21076 "Go to the end of the line.
21077 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21078 first attempt, and only move to after the tags when the cursor is already
21079 beyond the end of the headline."
21080 (interactive "P")
21081 (let ((special (if (consp org-special-ctrl-a/e)
21082 (cdr org-special-ctrl-a/e)
21083 org-special-ctrl-a/e)))
21084 (cond
21085 ((or (not special) arg
21086 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21087 (call-interactively
21088 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21089 ((fboundp 'move-end-of-line) 'move-end-of-line)
21090 (t 'end-of-line))))
21091 ((org-at-heading-p)
21092 (let ((pos (point)))
21093 (beginning-of-line 1)
21094 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21095 (if (eq special t)
21096 (if (or (< pos (match-beginning 1))
21097 (= pos (match-end 0)))
21098 (goto-char (match-beginning 1))
21099 (goto-char (match-end 0)))
21100 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21101 (goto-char (match-end 0))
21102 (goto-char (match-beginning 1))))
21103 (call-interactively (if (fboundp 'move-end-of-line)
21104 'move-end-of-line
21105 'end-of-line)))))
21106 ((org-at-drawer-p)
21107 (move-end-of-line 1)
21108 (when (overlays-at (1- (point))) (backward-char 1)))
21109 ;; At an item: Move before any hidden text.
21110 (t (call-interactively
21111 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21112 ((fboundp 'move-end-of-line) 'move-end-of-line)
21113 (t 'end-of-line)))))
21114 (org-no-warnings
21115 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21117 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21118 (define-key org-mode-map "\C-e" 'org-end-of-line)
21120 (defun org-backward-sentence (&optional arg)
21121 "Go to beginning of sentence, or beginning of table field.
21122 This will call `backward-sentence' or `org-table-beginning-of-field',
21123 depending on context."
21124 (interactive "P")
21125 (cond
21126 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21127 (t (call-interactively 'backward-sentence))))
21129 (defun org-forward-sentence (&optional arg)
21130 "Go to end of sentence, or end of table field.
21131 This will call `forward-sentence' or `org-table-end-of-field',
21132 depending on context."
21133 (interactive "P")
21134 (cond
21135 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21136 (t (call-interactively 'forward-sentence))))
21138 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21139 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21141 (defun org-kill-line (&optional arg)
21142 "Kill line, to tags or end of line."
21143 (interactive "P")
21144 (cond
21145 ((or (not org-special-ctrl-k)
21146 (bolp)
21147 (not (org-at-heading-p)))
21148 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21149 org-ctrl-k-protect-subtree)
21150 (if (or (eq org-ctrl-k-protect-subtree 'error)
21151 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21152 (error "C-k aborted - would kill hidden subtree")))
21153 (call-interactively
21154 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21155 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21156 (kill-region (point) (match-beginning 1))
21157 (org-set-tags nil t))
21158 (t (kill-region (point) (point-at-eol)))))
21160 (define-key org-mode-map "\C-k" 'org-kill-line)
21162 (defun org-yank (&optional arg)
21163 "Yank. If the kill is a subtree, treat it specially.
21164 This command will look at the current kill and check if is a single
21165 subtree, or a series of subtrees[1]. If it passes the test, and if the
21166 cursor is at the beginning of a line or after the stars of a currently
21167 empty headline, then the yank is handled specially. How exactly depends
21168 on the value of the following variables, both set by default.
21170 org-yank-folded-subtrees
21171 When set, the subtree(s) will be folded after insertion, but only
21172 if doing so would now swallow text after the yanked text.
21174 org-yank-adjusted-subtrees
21175 When set, the subtree will be promoted or demoted in order to
21176 fit into the local outline tree structure, which means that the level
21177 will be adjusted so that it becomes the smaller one of the two
21178 *visible* surrounding headings.
21180 Any prefix to this command will cause `yank' to be called directly with
21181 no special treatment. In particular, a simple \\[universal-argument] prefix \
21182 will just
21183 plainly yank the text as it is.
21185 \[1] The test checks if the first non-white line is a heading
21186 and if there are no other headings with fewer stars."
21187 (interactive "P")
21188 (org-yank-generic 'yank arg))
21190 (defun org-yank-generic (command arg)
21191 "Perform some yank-like command.
21193 This function implements the behavior described in the `org-yank'
21194 documentation. However, it has been generalized to work for any
21195 interactive command with similar behavior."
21197 ;; pretend to be command COMMAND
21198 (setq this-command command)
21200 (if arg
21201 (call-interactively command)
21203 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21204 (and (org-kill-is-subtree-p)
21205 (or (bolp)
21206 (and (looking-at "[ \t]*$")
21207 (string-match
21208 "\\`\\*+\\'"
21209 (buffer-substring (point-at-bol) (point)))))))
21210 swallowp)
21211 (cond
21212 ((and subtreep org-yank-folded-subtrees)
21213 (let ((beg (point))
21214 end)
21215 (if (and subtreep org-yank-adjusted-subtrees)
21216 (org-paste-subtree nil nil 'for-yank)
21217 (call-interactively command))
21219 (setq end (point))
21220 (goto-char beg)
21221 (when (and (bolp) subtreep
21222 (not (setq swallowp
21223 (org-yank-folding-would-swallow-text beg end))))
21224 (org-with-limited-levels
21225 (or (looking-at org-outline-regexp)
21226 (re-search-forward org-outline-regexp-bol end t))
21227 (while (and (< (point) end) (looking-at org-outline-regexp))
21228 (hide-subtree)
21229 (org-cycle-show-empty-lines 'folded)
21230 (condition-case nil
21231 (outline-forward-same-level 1)
21232 (error (goto-char end))))))
21233 (when swallowp
21234 (message
21235 "Inserted text not folded because that would swallow text"))
21237 (goto-char end)
21238 (skip-chars-forward " \t\n\r")
21239 (beginning-of-line 1)
21240 (push-mark beg 'nomsg)))
21241 ((and subtreep org-yank-adjusted-subtrees)
21242 (let ((beg (point-at-bol)))
21243 (org-paste-subtree nil nil 'for-yank)
21244 (push-mark beg 'nomsg)))
21246 (call-interactively command))))))
21248 (defun org-yank-folding-would-swallow-text (beg end)
21249 "Would hide-subtree at BEG swallow any text after END?"
21250 (let (level)
21251 (org-with-limited-levels
21252 (save-excursion
21253 (goto-char beg)
21254 (when (or (looking-at org-outline-regexp)
21255 (re-search-forward org-outline-regexp-bol end t))
21256 (setq level (org-outline-level)))
21257 (goto-char end)
21258 (skip-chars-forward " \t\r\n\v\f")
21259 (if (or (eobp)
21260 (and (bolp) (looking-at org-outline-regexp)
21261 (<= (org-outline-level) level)))
21262 nil ; Nothing would be swallowed
21263 t))))) ; something would swallow
21265 (define-key org-mode-map "\C-y" 'org-yank)
21267 (defun org-truely-invisible-p ()
21268 "Check if point is at a character currently not visible.
21269 This version does not only check the character property, but also
21270 `visible-mode'."
21271 ;; Early versions of noutline don't have `outline-invisible-p'.
21272 (if (org-bound-and-true-p visible-mode)
21274 (outline-invisible-p)))
21276 (defun org-invisible-p2 ()
21277 "Check if point is at a character currently not visible."
21278 (save-excursion
21279 (if (and (eolp) (not (bobp))) (backward-char 1))
21280 ;; Early versions of noutline don't have `outline-invisible-p'.
21281 (outline-invisible-p)))
21283 (defun org-back-to-heading (&optional invisible-ok)
21284 "Call `outline-back-to-heading', but provide a better error message."
21285 (condition-case nil
21286 (outline-back-to-heading invisible-ok)
21287 (error (error "Before first headline at position %d in buffer %s"
21288 (point) (current-buffer)))))
21290 (defun org-beginning-of-defun ()
21291 "Go to the beginning of the subtree, i.e. back to the heading."
21292 (org-back-to-heading))
21293 (defun org-end-of-defun ()
21294 "Go to the end of the subtree."
21295 (org-end-of-subtree nil t))
21297 (defun org-before-first-heading-p ()
21298 "Before first heading?"
21299 (save-excursion
21300 (end-of-line)
21301 (null (re-search-backward org-outline-regexp-bol nil t))))
21303 (defun org-at-heading-p (&optional ignored)
21304 (outline-on-heading-p t))
21305 ;; Compatibility alias with Org versions < 7.8.03
21306 (defalias 'org-on-heading-p 'org-at-heading-p)
21308 (defun org-at-comment-p nil
21309 "Is cursor in a line starting with a # character?"
21310 (save-excursion
21311 (beginning-of-line)
21312 (looking-at "^#")))
21314 (defun org-at-drawer-p nil
21315 "Is cursor at a drawer keyword?"
21316 (save-excursion
21317 (move-beginning-of-line 1)
21318 (looking-at org-drawer-regexp)))
21320 (defun org-at-block-p nil
21321 "Is cursor at a block keyword?"
21322 (save-excursion
21323 (move-beginning-of-line 1)
21324 (looking-at org-block-regexp)))
21326 (defun org-point-at-end-of-empty-headline ()
21327 "If point is at the end of an empty headline, return t, else nil.
21328 If the heading only contains a TODO keyword, it is still still considered
21329 empty."
21330 (and (looking-at "[ \t]*$")
21331 (when org-todo-line-regexp
21332 (save-excursion
21333 (beginning-of-line 1)
21334 (let ((case-fold-search nil))
21335 (looking-at org-todo-line-regexp)
21336 (string= (match-string 3) ""))))))
21338 (defun org-at-heading-or-item-p ()
21339 (or (org-at-heading-p) (org-at-item-p)))
21341 (defun org-at-target-p ()
21342 (or (org-in-regexp org-radio-target-regexp)
21343 (org-in-regexp org-target-regexp)))
21344 ;; Compatibility alias with Org versions < 7.8.03
21345 (defalias 'org-on-target-p 'org-at-target-p)
21347 (defun org-up-heading-all (arg)
21348 "Move to the heading line of which the present line is a subheading.
21349 This function considers both visible and invisible heading lines.
21350 With argument, move up ARG levels."
21351 (if (fboundp 'outline-up-heading-all)
21352 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21353 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21355 (defun org-up-heading-safe ()
21356 "Move to the heading line of which the present line is a subheading.
21357 This version will not throw an error. It will return the level of the
21358 headline found, or nil if no higher level is found.
21360 Also, this function will be a lot faster than `outline-up-heading',
21361 because it relies on stars being the outline starters. This can really
21362 make a significant difference in outlines with very many siblings."
21363 (let (start-level re)
21364 (org-back-to-heading t)
21365 (setq start-level (funcall outline-level))
21366 (if (equal start-level 1)
21368 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21369 (if (re-search-backward re nil t)
21370 (funcall outline-level)))))
21372 (defun org-first-sibling-p ()
21373 "Is this heading the first child of its parents?"
21374 (interactive)
21375 (let ((re org-outline-regexp-bol)
21376 level l)
21377 (unless (org-at-heading-p t)
21378 (error "Not at a heading"))
21379 (setq level (funcall outline-level))
21380 (save-excursion
21381 (if (not (re-search-backward re nil t))
21383 (setq l (funcall outline-level))
21384 (< l level)))))
21386 (defun org-goto-sibling (&optional previous)
21387 "Goto the next sibling, even if it is invisible.
21388 When PREVIOUS is set, go to the previous sibling instead. Returns t
21389 when a sibling was found. When none is found, return nil and don't
21390 move point."
21391 (let ((fun (if previous 're-search-backward 're-search-forward))
21392 (pos (point))
21393 (re org-outline-regexp-bol)
21394 level l)
21395 (when (condition-case nil (org-back-to-heading t) (error nil))
21396 (setq level (funcall outline-level))
21397 (catch 'exit
21398 (or previous (forward-char 1))
21399 (while (funcall fun re nil t)
21400 (setq l (funcall outline-level))
21401 (when (< l level) (goto-char pos) (throw 'exit nil))
21402 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21403 (goto-char pos)
21404 nil))))
21406 (defun org-show-siblings ()
21407 "Show all siblings of the current headline."
21408 (save-excursion
21409 (while (org-goto-sibling) (org-flag-heading nil)))
21410 (save-excursion
21411 (while (org-goto-sibling 'previous)
21412 (org-flag-heading nil))))
21414 (defun org-goto-first-child ()
21415 "Goto the first child, even if it is invisible.
21416 Return t when a child was found. Otherwise don't move point and
21417 return nil."
21418 (let (level (pos (point)) (re org-outline-regexp-bol))
21419 (when (condition-case nil (org-back-to-heading t) (error nil))
21420 (setq level (outline-level))
21421 (forward-char 1)
21422 (if (and (re-search-forward re nil t) (> (outline-level) level))
21423 (progn (goto-char (match-beginning 0)) t)
21424 (goto-char pos) nil))))
21426 (defun org-show-hidden-entry ()
21427 "Show an entry where even the heading is hidden."
21428 (save-excursion
21429 (org-show-entry)))
21431 (defun org-flag-heading (flag &optional entry)
21432 "Flag the current heading. FLAG non-nil means make invisible.
21433 When ENTRY is non-nil, show the entire entry."
21434 (save-excursion
21435 (org-back-to-heading t)
21436 ;; Check if we should show the entire entry
21437 (if entry
21438 (progn
21439 (org-show-entry)
21440 (save-excursion
21441 (and (outline-next-heading)
21442 (org-flag-heading nil))))
21443 (outline-flag-region (max (point-min) (1- (point)))
21444 (save-excursion (outline-end-of-heading) (point))
21445 flag))))
21447 (defun org-get-next-sibling ()
21448 "Move to next heading of the same level, and return point.
21449 If there is no such heading, return nil.
21450 This is like outline-next-sibling, but invisible headings are ok."
21451 (let ((level (funcall outline-level)))
21452 (outline-next-heading)
21453 (while (and (not (eobp)) (> (funcall outline-level) level))
21454 (outline-next-heading))
21455 (if (or (eobp) (< (funcall outline-level) level))
21457 (point))))
21459 (defun org-get-last-sibling ()
21460 "Move to previous heading of the same level, and return point.
21461 If there is no such heading, return nil."
21462 (let ((opoint (point))
21463 (level (funcall outline-level)))
21464 (outline-previous-heading)
21465 (when (and (/= (point) opoint) (outline-on-heading-p t))
21466 (while (and (> (funcall outline-level) level)
21467 (not (bobp)))
21468 (outline-previous-heading))
21469 (if (< (funcall outline-level) level)
21471 (point)))))
21473 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21474 ;; This contains an exact copy of the original function, but it uses
21475 ;; `org-back-to-heading', to make it work also in invisible
21476 ;; trees. And is uses an invisible-OK argument.
21477 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21478 ;; Furthermore, when used inside Org, finding the end of a large subtree
21479 ;; with many children and grandchildren etc, this can be much faster
21480 ;; than the outline version.
21481 (org-back-to-heading invisible-OK)
21482 (let ((first t)
21483 (level (funcall outline-level)))
21484 (if (and (derived-mode-p 'org-mode) (< level 1000))
21485 ;; A true heading (not a plain list item), in Org-mode
21486 ;; This means we can easily find the end by looking
21487 ;; only for the right number of stars. Using a regexp to do
21488 ;; this is so much faster than using a Lisp loop.
21489 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21490 (forward-char 1)
21491 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21492 ;; something else, do it the slow way
21493 (while (and (not (eobp))
21494 (or first (> (funcall outline-level) level)))
21495 (setq first nil)
21496 (outline-next-heading)))
21497 (unless to-heading
21498 (if (memq (preceding-char) '(?\n ?\^M))
21499 (progn
21500 ;; Go to end of line before heading
21501 (forward-char -1)
21502 (if (memq (preceding-char) '(?\n ?\^M))
21503 ;; leave blank line before heading
21504 (forward-char -1))))))
21505 (point))
21507 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21508 "Use Org version in org-mode, for dramatic speed-up."
21509 (if (derived-mode-p 'org-mode)
21510 (progn
21511 (org-end-of-subtree nil t)
21512 (unless (eobp) (backward-char 1)))
21513 ad-do-it))
21515 (defun org-end-of-meta-data-and-drawers ()
21516 "Jump to the first text after meta data and drawers in the current entry.
21517 This will move over empty lines, lines with planning time stamps,
21518 clocking lines, and drawers."
21519 (org-back-to-heading t)
21520 (let ((end (save-excursion (outline-next-heading) (point)))
21521 (re (concat "\\(" org-drawer-regexp "\\)"
21522 "\\|" "[ \t]*" org-keyword-time-regexp)))
21523 (forward-line 1)
21524 (while (re-search-forward re end t)
21525 (if (not (match-end 1))
21526 ;; empty or planning line
21527 (forward-line 1)
21528 ;; a drawer, find the end
21529 (re-search-forward "^[ \t]*:END:" end 'move)
21530 (forward-line 1)))
21531 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21532 (point)))
21534 (defun org-forward-same-level (arg &optional invisible-ok)
21535 "Move forward to the arg'th subheading at same level as this one.
21536 Stop at the first and last subheadings of a superior heading.
21537 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21538 it wil also look at invisible ones."
21539 (interactive "p")
21540 (org-back-to-heading invisible-ok)
21541 (org-at-heading-p)
21542 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21543 (re (format "^\\*\\{1,%d\\} " level))
21545 (forward-char 1)
21546 (while (> arg 0)
21547 (while (and (re-search-forward re nil 'move)
21548 (setq l (- (match-end 0) (match-beginning 0) 1))
21549 (= l level)
21550 (not invisible-ok)
21551 (progn (backward-char 1) (outline-invisible-p)))
21552 (if (< l level) (setq arg 1)))
21553 (setq arg (1- arg)))
21554 (beginning-of-line 1)))
21556 (defun org-backward-same-level (arg &optional invisible-ok)
21557 "Move backward to the arg'th subheading at same level as this one.
21558 Stop at the first and last subheadings of a superior heading."
21559 (interactive "p")
21560 (org-back-to-heading)
21561 (org-at-heading-p)
21562 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21563 (re (format "^\\*\\{1,%d\\} " level))
21565 (while (> arg 0)
21566 (while (and (re-search-backward re nil 'move)
21567 (setq l (- (match-end 0) (match-beginning 0) 1))
21568 (= l level)
21569 (not invisible-ok)
21570 (outline-invisible-p))
21571 (if (< l level) (setq arg 1)))
21572 (setq arg (1- arg)))))
21574 (defun org-show-subtree ()
21575 "Show everything after this heading at deeper levels."
21576 (interactive)
21577 (outline-flag-region
21578 (point)
21579 (save-excursion
21580 (org-end-of-subtree t t))
21581 nil))
21583 (defun org-show-entry ()
21584 "Show the body directly following this heading.
21585 Show the heading too, if it is currently invisible."
21586 (interactive)
21587 (save-excursion
21588 (condition-case nil
21589 (progn
21590 (org-back-to-heading t)
21591 (outline-flag-region
21592 (max (point-min) (1- (point)))
21593 (save-excursion
21594 (if (re-search-forward
21595 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21596 (match-beginning 1)
21597 (point-max)))
21598 nil)
21599 (org-cycle-hide-drawers 'children))
21600 (error nil))))
21602 (defun org-make-options-regexp (kwds &optional extra)
21603 "Make a regular expression for keyword lines."
21604 (concat
21606 "#?[ \t]*\\+\\("
21607 (mapconcat 'regexp-quote kwds "\\|")
21608 (if extra (concat "\\|" extra))
21609 "\\):[ \t]*"
21610 "\\(.*\\)"))
21612 ;; Make isearch reveal the necessary context
21613 (defun org-isearch-end ()
21614 "Reveal context after isearch exits."
21615 (when isearch-success ; only if search was successful
21616 (if (featurep 'xemacs)
21617 ;; Under XEmacs, the hook is run in the correct place,
21618 ;; we directly show the context.
21619 (org-show-context 'isearch)
21620 ;; In Emacs the hook runs *before* restoring the overlays.
21621 ;; So we have to use a one-time post-command-hook to do this.
21622 ;; (Emacs 22 has a special variable, see function `org-mode')
21623 (unless (and (boundp 'isearch-mode-end-hook-quit)
21624 isearch-mode-end-hook-quit)
21625 ;; Only when the isearch was not quitted.
21626 (org-add-hook 'post-command-hook 'org-isearch-post-command
21627 'append 'local)))))
21629 (defun org-isearch-post-command ()
21630 "Remove self from hook, and show context."
21631 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21632 (org-show-context 'isearch))
21635 ;;;; Integration with and fixes for other packages
21637 ;;; Imenu support
21639 (defvar org-imenu-markers nil
21640 "All markers currently used by Imenu.")
21641 (make-variable-buffer-local 'org-imenu-markers)
21643 (defun org-imenu-new-marker (&optional pos)
21644 "Return a new marker for use by Imenu, and remember the marker."
21645 (let ((m (make-marker)))
21646 (move-marker m (or pos (point)))
21647 (push m org-imenu-markers)
21650 (defun org-imenu-get-tree ()
21651 "Produce the index for Imenu."
21652 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21653 (setq org-imenu-markers nil)
21654 (let* ((n org-imenu-depth)
21655 (re (concat "^" (org-get-limited-outline-regexp)))
21656 (subs (make-vector (1+ n) nil))
21657 (last-level 0)
21658 m level head)
21659 (save-excursion
21660 (save-restriction
21661 (widen)
21662 (goto-char (point-max))
21663 (while (re-search-backward re nil t)
21664 (setq level (org-reduced-level (funcall outline-level)))
21665 (when (and (<= level n)
21666 (looking-at org-complex-heading-regexp))
21667 (setq head (org-link-display-format
21668 (org-match-string-no-properties 4))
21669 m (org-imenu-new-marker))
21670 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21671 (if (>= level last-level)
21672 (push (cons head m) (aref subs level))
21673 (push (cons head (aref subs (1+ level))) (aref subs level))
21674 (loop for i from (1+ level) to n do (aset subs i nil)))
21675 (setq last-level level)))))
21676 (aref subs 1)))
21678 (eval-after-load "imenu"
21679 '(progn
21680 (add-hook 'imenu-after-jump-hook
21681 (lambda ()
21682 (if (derived-mode-p 'org-mode)
21683 (org-show-context 'org-goto))))))
21685 (defun org-link-display-format (link)
21686 "Replace a link with either the description, or the link target
21687 if no description is present"
21688 (save-match-data
21689 (if (string-match org-bracket-link-analytic-regexp link)
21690 (replace-match (if (match-end 5)
21691 (match-string 5 link)
21692 (concat (match-string 1 link)
21693 (match-string 3 link)))
21694 nil t link)
21695 link)))
21697 (defun org-toggle-link-display ()
21698 "Toggle the literal or descriptive display of links."
21699 (interactive)
21700 (if org-descriptive-links
21701 (progn (org-remove-from-invisibility-spec '(org-link))
21702 (org-restart-font-lock)
21703 (setq org-descriptive-links nil))
21704 (progn (add-to-invisibility-spec '(org-link))
21705 (org-restart-font-lock)
21706 (setq org-descriptive-links t))))
21708 ;; Speedbar support
21710 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21711 "Overlay marking the agenda restriction line in speedbar.")
21712 (overlay-put org-speedbar-restriction-lock-overlay
21713 'face 'org-agenda-restriction-lock)
21714 (overlay-put org-speedbar-restriction-lock-overlay
21715 'help-echo "Agendas are currently limited to this item.")
21716 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21718 (defun org-speedbar-set-agenda-restriction ()
21719 "Restrict future agenda commands to the location at point in speedbar.
21720 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21721 (interactive)
21722 (require 'org-agenda)
21723 (let (p m tp np dir txt)
21724 (cond
21725 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21726 'org-imenu t))
21727 (setq m (get-text-property p 'org-imenu-marker))
21728 (with-current-buffer (marker-buffer m)
21729 (goto-char m)
21730 (org-agenda-set-restriction-lock 'subtree)))
21731 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21732 'speedbar-function 'speedbar-find-file))
21733 (setq tp (previous-single-property-change
21734 (1+ p) 'speedbar-function)
21735 np (next-single-property-change
21736 tp 'speedbar-function)
21737 dir (speedbar-line-directory)
21738 txt (buffer-substring-no-properties (or tp (point-min))
21739 (or np (point-max))))
21740 (with-current-buffer (find-file-noselect
21741 (let ((default-directory dir))
21742 (expand-file-name txt)))
21743 (unless (derived-mode-p 'org-mode)
21744 (error "Cannot restrict to non-Org-mode file"))
21745 (org-agenda-set-restriction-lock 'file)))
21746 (t (error "Don't know how to restrict Org-mode's agenda")))
21747 (move-overlay org-speedbar-restriction-lock-overlay
21748 (point-at-bol) (point-at-eol))
21749 (setq current-prefix-arg nil)
21750 (org-agenda-maybe-redo)))
21752 (eval-after-load "speedbar"
21753 '(progn
21754 (speedbar-add-supported-extension ".org")
21755 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21756 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21757 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21758 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21759 (add-hook 'speedbar-visiting-tag-hook
21760 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21762 ;;; Fixes and Hacks for problems with other packages
21764 ;; Make flyspell not check words in links, to not mess up our keymap
21765 (defun org-mode-flyspell-verify ()
21766 "Don't let flyspell put overlays at active buttons, or on
21767 {todo,all-time,additional-option-like}-keywords."
21768 (let ((pos (max (1- (point)) (point-min)))
21769 (word (thing-at-point 'word)))
21770 (and (not (get-text-property pos 'keymap))
21771 (not (get-text-property pos 'org-no-flyspell))
21772 (not (member word org-todo-keywords-1))
21773 (not (member word org-all-time-keywords))
21774 (not (member word org-additional-option-like-keywords)))))
21776 (defun org-remove-flyspell-overlays-in (beg end)
21777 "Remove flyspell overlays in region."
21778 (and (org-bound-and-true-p flyspell-mode)
21779 (fboundp 'flyspell-delete-region-overlays)
21780 (flyspell-delete-region-overlays beg end))
21781 (add-text-properties beg end '(org-no-flyspell t)))
21783 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21784 (eval-after-load "bookmark"
21785 '(if (boundp 'bookmark-after-jump-hook)
21786 ;; We can use the hook
21787 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21788 ;; Hook not available, use advice
21789 (defadvice bookmark-jump (after org-make-visible activate)
21790 "Make the position visible."
21791 (org-bookmark-jump-unhide))))
21793 ;; Make sure saveplace shows the location if it was hidden
21794 (eval-after-load "saveplace"
21795 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21796 "Make the position visible."
21797 (org-bookmark-jump-unhide)))
21799 ;; Make sure ecb shows the location if it was hidden
21800 (eval-after-load "ecb"
21801 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21802 "Make hierarchy visible when jumping into location from ECB tree buffer."
21803 (if (derived-mode-p 'org-mode)
21804 (org-show-context))))
21806 (defun org-bookmark-jump-unhide ()
21807 "Unhide the current position, to show the bookmark location."
21808 (and (derived-mode-p 'org-mode)
21809 (or (outline-invisible-p)
21810 (save-excursion (goto-char (max (point-min) (1- (point))))
21811 (outline-invisible-p)))
21812 (org-show-context 'bookmark-jump)))
21814 ;; Make session.el ignore our circular variable
21815 (eval-after-load "session"
21816 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21818 ;;;; Experimental code
21820 (defun org-closed-in-range ()
21821 "Sparse tree of items closed in a certain time range.
21822 Still experimental, may disappear in the future."
21823 (interactive)
21824 ;; Get the time interval from the user.
21825 (let* ((time1 (org-float-time
21826 (org-read-date nil 'to-time nil "Starting date: ")))
21827 (time2 (org-float-time
21828 (org-read-date nil 'to-time nil "End date:")))
21829 ;; callback function
21830 (callback (lambda ()
21831 (let ((time
21832 (org-float-time
21833 (apply 'encode-time
21834 (org-parse-time-string
21835 (match-string 1))))))
21836 ;; check if time in interval
21837 (and (>= time time1) (<= time time2))))))
21838 ;; make tree, check each match with the callback
21839 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21841 ;;;; Finish up
21843 (provide 'org)
21845 (run-hooks 'org-load-hook)
21847 ;;; org.el ends here