Fix filling when point is at the very end of a paragraph
[org-mode.git] / lisp / org.el
blob8b388549eb06521893451e9149be9baff2db2ae8
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 "Lisp" lisp)
173 (const :tag "Maxima" maxima)
174 (const :tag "Matlab" matlab)
175 (const :tag "Mscgen" mscgen)
176 (const :tag "Ocaml" ocaml)
177 (const :tag "Octave" octave)
178 (const :tag "Org" org)
179 (const :tag "Perl" perl)
180 (const :tag "Pico Lisp" picolisp)
181 (const :tag "PlantUML" plantuml)
182 (const :tag "Python" python)
183 (const :tag "Ruby" ruby)
184 (const :tag "Sass" sass)
185 (const :tag "Scala" scala)
186 (const :tag "Scheme" scheme)
187 (const :tag "Screen" screen)
188 (const :tag "Shell Script" sh)
189 (const :tag "Shen" shen)
190 (const :tag "Sql" sql)
191 (const :tag "Sqlite" sqlite))
192 :value-type (boolean :tag "Activate" :value t)))
194 ;;;; Customization variables
195 (defcustom org-clone-delete-id nil
196 "Remove ID property of clones of a subtree.
197 When non-nil, clones of a subtree don't inherit the ID property.
198 Otherwise they inherit the ID property with a new unique
199 identifier."
200 :type 'boolean
201 :version "24.1"
202 :group 'org-id)
204 ;;; Version
205 (org-check-version)
206 ;;;###autoload
207 (defun org-version (&optional here full message)
208 "Show the org-mode version in the echo area.
209 With prefix arg HERE, insert it at point."
210 (interactive "P")
211 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
212 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
213 (org-trash (or
214 (and (fboundp 'org-release) (fboundp 'org-git-version))
215 (load (concat org-dir "org-version.el")
216 'noerror 'nomessage 'nosuffix)))
217 (org-version (org-release))
218 (git-version (org-git-version))
219 (version (format "Org-mode version %s (%s @ %s)"
220 org-version
221 git-version
222 (if org-install-dir
223 (if (string= org-dir org-install-dir)
224 org-install-dir
225 (concat "mixed installation! " org-install-dir " and " org-dir))
226 "org-install.el can not be found!")))
227 (_version (if full version org-version)))
228 (if (org-called-interactively-p 'interactive)
229 (if here
230 (insert version)
231 (message version))
232 (if message (message _version))
233 _version)))
235 ;;; Compatibility constants
237 ;;; The custom variables
239 (defgroup org nil
240 "Outline-based notes management and organizer."
241 :tag "Org"
242 :group 'outlines
243 :group 'calendar)
245 (defcustom org-mode-hook nil
246 "Mode hook for Org-mode, run after the mode was turned on."
247 :group 'org
248 :type 'hook)
250 (defcustom org-load-hook nil
251 "Hook that is run after org.el has been loaded."
252 :group 'org
253 :type 'hook)
255 (defcustom org-log-buffer-setup-hook nil
256 "Hook that is run after an Org log buffer is created."
257 :group 'org
258 :version "24.1"
259 :type 'hook)
261 (defvar org-modules) ; defined below
262 (defvar org-modules-loaded nil
263 "Have the modules been loaded already?")
265 (defun org-load-modules-maybe (&optional force)
266 "Load all extensions listed in `org-modules'."
267 (when (or force (not org-modules-loaded))
268 (mapc (lambda (ext)
269 (condition-case nil (require ext)
270 (error (message "Problems while trying to load feature `%s'" ext))))
271 org-modules)
272 (setq org-modules-loaded t)))
274 (defun org-set-modules (var value)
275 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
276 (set var value)
277 (when (featurep 'org)
278 (org-load-modules-maybe 'force)))
280 (when (org-bound-and-true-p org-modules)
281 (let ((a (member 'org-infojs org-modules)))
282 (and a (setcar a 'org-jsinfo))))
284 (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)
285 "Modules that should always be loaded together with org.el.
286 If a description starts with <C>, the file is not part of Emacs
287 and loading it will require that you have downloaded and properly installed
288 the org-mode distribution.
290 You can also use this system to load external packages (i.e. neither Org
291 core modules, nor modules from the CONTRIB directory). Just add symbols
292 to the end of the list. If the package is called org-xyz.el, then you need
293 to add the symbol `xyz', and the package must have a call to
295 (provide 'org-xyz)"
296 :group 'org
297 :set 'org-set-modules
298 :type
299 '(set :greedy t
300 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
301 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
302 (const :tag " crypt: Encryption of subtrees" org-crypt)
303 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
304 (const :tag " docview: Links to doc-view buffers" org-docview)
305 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
306 (const :tag " id: Global IDs for identifying entries" org-id)
307 (const :tag " info: Links to Info nodes" org-info)
308 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
309 (const :tag " habit: Track your consistency with habits" org-habit)
310 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
311 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
312 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
313 (const :tag " mew Links to Mew folders/messages" org-mew)
314 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
315 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
316 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
317 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
318 (const :tag " vm: Links to VM folders/messages" org-vm)
319 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
320 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
321 (const :tag " mouse: Additional mouse support" org-mouse)
322 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
324 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
325 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
326 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
327 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
328 (const :tag "C collector: Collect properties into tables" org-collector)
329 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
330 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
331 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
332 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
333 (const :tag "C eval: Include command output as text" org-eval)
334 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
335 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
336 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
337 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
338 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
340 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
342 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
343 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
344 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
345 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
346 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
347 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
348 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
349 (const :tag "C mtags: Support for muse-like tags" org-mtags)
350 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
351 (const :tag "C registry: A registry for Org-mode links" org-registry)
352 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
353 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
354 (const :tag "C secretary: Team management with org-mode" org-secretary)
355 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
356 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
357 (const :tag "C track: Keep up with Org-mode development" org-track)
358 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
359 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
360 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
362 (defcustom org-support-shift-select nil
363 "Non-nil means make shift-cursor commands select text when possible.
365 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
366 start selecting a region, or enlarge regions started in this way.
367 In Org-mode, in special contexts, these same keys are used for
368 other purposes, important enough to compete with shift selection.
369 Org tries to balance these needs by supporting `shift-select-mode'
370 outside these special contexts, under control of this variable.
372 The default of this variable is nil, to avoid confusing behavior. Shifted
373 cursor keys will then execute Org commands in the following contexts:
374 - on a headline, changing TODO state (left/right) and priority (up/down)
375 - on a time stamp, changing the time
376 - in a plain list item, changing the bullet type
377 - in a property definition line, switching between allowed values
378 - in the BEGIN line of a clock table (changing the time block).
379 Outside these contexts, the commands will throw an error.
381 When this variable is t and the cursor is not in a special
382 context, Org-mode will support shift-selection for making and
383 enlarging regions. To make this more effective, the bullet
384 cycling will no longer happen anywhere in an item line, but only
385 if the cursor is exactly on the bullet.
387 If you set this variable to the symbol `always', then the keys
388 will not be special in headlines, property lines, and item lines,
389 to make shift selection work there as well. If this is what you
390 want, you can use the following alternative commands: `C-c C-t'
391 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
392 can be used to switch TODO sets, `C-c -' to cycle item bullet
393 types, and properties can be edited by hand or in column view.
395 However, when the cursor is on a timestamp, shift-cursor commands
396 will still edit the time stamp - this is just too good to give up.
398 XEmacs user should have this variable set to nil, because
399 `shift-select-mode' is in Emacs 23 or later only."
400 :group 'org
401 :type '(choice
402 (const :tag "Never" nil)
403 (const :tag "When outside special context" t)
404 (const :tag "Everywhere except timestamps" always)))
406 (defcustom org-loop-over-headlines-in-active-region nil
407 "Shall some commands act upon headlines in the active region?
409 When set to `t', some commands will be performed in all headlines
410 within the active region.
412 When set to `start-level', some commands will be performed in all
413 headlines within the active region, provided that these headlines
414 are of the same level than the first one.
416 When set to a string, those commands will be performed on the
417 matching headlines within the active region. Such string must be
418 a tags/property/todo match as it is used in the agenda tags view.
420 The list of commands is: `org-schedule', `org-deadline',
421 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
422 `org-archive-to-archive-sibling'. The archiving commands skip
423 already archived entries."
424 :type '(choice (const :tag "Don't loop" nil)
425 (const :tag "All headlines in active region" t)
426 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
427 (string :tag "Tags/Property/Todo matcher"))
428 :version "24.1"
429 :group 'org-todo
430 :group 'org-archive)
432 (defgroup org-startup nil
433 "Options concerning startup of Org-mode."
434 :tag "Org Startup"
435 :group 'org)
437 (defcustom org-startup-folded t
438 "Non-nil means entering Org-mode will switch to OVERVIEW.
439 This can also be configured on a per-file basis by adding one of
440 the following lines anywhere in the buffer:
442 #+STARTUP: fold (or `overview', this is equivalent)
443 #+STARTUP: nofold (or `showall', this is equivalent)
444 #+STARTUP: content
445 #+STARTUP: showeverything"
446 :group 'org-startup
447 :type '(choice
448 (const :tag "nofold: show all" nil)
449 (const :tag "fold: overview" t)
450 (const :tag "content: all headlines" content)
451 (const :tag "show everything, even drawers" showeverything)))
453 (defcustom org-startup-truncated t
454 "Non-nil means entering Org-mode will set `truncate-lines'.
455 This is useful since some lines containing links can be very long and
456 uninteresting. Also tables look terrible when wrapped."
457 :group 'org-startup
458 :type 'boolean)
460 (defcustom org-startup-indented nil
461 "Non-nil means turn on `org-indent-mode' on startup.
462 This can also be configured on a per-file basis by adding one of
463 the following lines anywhere in the buffer:
465 #+STARTUP: indent
466 #+STARTUP: noindent"
467 :group 'org-structure
468 :type '(choice
469 (const :tag "Not" nil)
470 (const :tag "Globally (slow on startup in large files)" t)))
472 (defcustom org-use-sub-superscripts t
473 "Non-nil means interpret \"_\" and \"^\" for export.
474 When this option is turned on, you can use TeX-like syntax for sub- and
475 superscripts. Several characters after \"_\" or \"^\" will be
476 considered as a single item - so grouping with {} is normally not
477 needed. For example, the following things will be parsed as single
478 sub- or superscripts.
480 10^24 or 10^tau several digits will be considered 1 item.
481 10^-12 or 10^-tau a leading sign with digits or a word
482 x^2-y^3 will be read as x^2 - y^3, because items are
483 terminated by almost any nonword/nondigit char.
484 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
486 Still, ambiguity is possible - so when in doubt use {} to enclose the
487 sub/superscript. If you set this variable to the symbol `{}',
488 the braces are *required* in order to trigger interpretations as
489 sub/superscript. This can be helpful in documents that need \"_\"
490 frequently in plain text.
492 Not all export backends support this, but HTML does.
494 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
495 :group 'org-startup
496 :group 'org-export-translation
497 :version "24.1"
498 :type '(choice
499 (const :tag "Always interpret" t)
500 (const :tag "Only with braces" {})
501 (const :tag "Never interpret" nil)))
503 (if (fboundp 'defvaralias)
504 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
507 (defcustom org-startup-with-beamer-mode nil
508 "Non-nil means turn on `org-beamer-mode' on startup.
509 This can also be configured on a per-file basis by adding one of
510 the following lines anywhere in the buffer:
512 #+STARTUP: beamer"
513 :group 'org-startup
514 :version "24.1"
515 :type 'boolean)
517 (defcustom org-startup-align-all-tables nil
518 "Non-nil means align all tables when visiting a file.
519 This is useful when the column width in tables is forced with <N> cookies
520 in table fields. Such tables will look correct only after the first re-align.
521 This can also be configured on a per-file basis by adding one of
522 the following lines anywhere in the buffer:
523 #+STARTUP: align
524 #+STARTUP: noalign"
525 :group 'org-startup
526 :type 'boolean)
528 (defcustom org-startup-with-inline-images nil
529 "Non-nil means show inline images when loading a new Org file.
530 This can also be configured on a per-file basis by adding one of
531 the following lines anywhere in the buffer:
532 #+STARTUP: inlineimages
533 #+STARTUP: noinlineimages"
534 :group 'org-startup
535 :version "24.1"
536 :type 'boolean)
538 (defcustom org-insert-mode-line-in-empty-file nil
539 "Non-nil means insert the first line setting Org-mode in empty files.
540 When the function `org-mode' is called interactively in an empty file, this
541 normally means that the file name does not automatically trigger Org-mode.
542 To ensure that the file will always be in Org-mode in the future, a
543 line enforcing Org-mode will be inserted into the buffer, if this option
544 has been set."
545 :group 'org-startup
546 :type 'boolean)
548 (defcustom org-replace-disputed-keys nil
549 "Non-nil means use alternative key bindings for some keys.
550 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
551 These keys are also used by other packages like shift-selection-mode'
552 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
553 If you want to use Org-mode together with one of these other modes,
554 or more generally if you would like to move some Org-mode commands to
555 other keys, set this variable and configure the keys with the variable
556 `org-disputed-keys'.
558 This option is only relevant at load-time of Org-mode, and must be set
559 *before* org.el is loaded. Changing it requires a restart of Emacs to
560 become effective."
561 :group 'org-startup
562 :type 'boolean)
564 (defcustom org-use-extra-keys nil
565 "Non-nil means use extra key sequence definitions for certain commands.
566 This happens automatically if you run XEmacs or if `window-system'
567 is nil. This variable lets you do the same manually. You must
568 set it before loading org.
570 Example: on Carbon Emacs 22 running graphically, with an external
571 keyboard on a Powerbook, the default way of setting M-left might
572 not work for either Alt or ESC. Setting this variable will make
573 it work for ESC."
574 :group 'org-startup
575 :type 'boolean)
577 (if (fboundp 'defvaralias)
578 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
580 (defcustom org-disputed-keys
581 '(([(shift up)] . [(meta p)])
582 ([(shift down)] . [(meta n)])
583 ([(shift left)] . [(meta -)])
584 ([(shift right)] . [(meta +)])
585 ([(control shift right)] . [(meta shift +)])
586 ([(control shift left)] . [(meta shift -)]))
587 "Keys for which Org-mode and other modes compete.
588 This is an alist, cars are the default keys, second element specifies
589 the alternative to use when `org-replace-disputed-keys' is t.
591 Keys can be specified in any syntax supported by `define-key'.
592 The value of this option takes effect only at Org-mode's startup,
593 therefore you'll have to restart Emacs to apply it after changing."
594 :group 'org-startup
595 :type 'alist)
597 (defun org-key (key)
598 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
599 Or return the original if not disputed.
600 Also apply the translations defined in `org-xemacs-key-equivalents'."
601 (when org-replace-disputed-keys
602 (let* ((nkey (key-description key))
603 (x (org-find-if (lambda (x)
604 (equal (key-description (car x)) nkey))
605 org-disputed-keys)))
606 (setq key (if x (cdr x) key))))
607 (when (featurep 'xemacs)
608 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
609 key)
611 (defun org-find-if (predicate seq)
612 (catch 'exit
613 (while seq
614 (if (funcall predicate (car seq))
615 (throw 'exit (car seq))
616 (pop seq)))))
618 (defun org-defkey (keymap key def)
619 "Define a key, possibly translated, as returned by `org-key'."
620 (define-key keymap (org-key key) def))
622 (defcustom org-ellipsis nil
623 "The ellipsis to use in the Org-mode outline.
624 When nil, just use the standard three dots. When a string, use that instead,
625 When a face, use the standard 3 dots, but with the specified face.
626 The change affects only Org-mode (which will then use its own display table).
627 Changing this requires executing `M-x org-mode' in a buffer to become
628 effective."
629 :group 'org-startup
630 :type '(choice (const :tag "Default" nil)
631 (face :tag "Face" :value org-warning)
632 (string :tag "String" :value "...#")))
634 (defvar org-display-table nil
635 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
637 (defgroup org-keywords nil
638 "Keywords in Org-mode."
639 :tag "Org Keywords"
640 :group 'org)
642 (defcustom org-deadline-string "DEADLINE:"
643 "String to mark deadline entries.
644 A deadline is this string, followed by a time stamp. Should be a word,
645 terminated by a colon. You can insert a schedule keyword and
646 a timestamp with \\[org-deadline].
647 Changes become only effective after restarting Emacs."
648 :group 'org-keywords
649 :type 'string)
651 (defcustom org-scheduled-string "SCHEDULED:"
652 "String to mark scheduled TODO entries.
653 A schedule is this string, followed by a time stamp. Should be a word,
654 terminated by a colon. You can insert a schedule keyword and
655 a timestamp with \\[org-schedule].
656 Changes become only effective after restarting Emacs."
657 :group 'org-keywords
658 :type 'string)
660 (defcustom org-closed-string "CLOSED:"
661 "String used as the prefix for timestamps logging closing a TODO entry."
662 :group 'org-keywords
663 :type 'string)
665 (defcustom org-clock-string "CLOCK:"
666 "String used as prefix for timestamps clocking work hours on an item."
667 :group 'org-keywords
668 :type 'string)
670 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
671 org-scheduled-string "\\|"
672 org-deadline-string "\\|"
673 org-closed-string "\\|"
674 org-clock-string "\\)")
675 "Matches a line with planning or clock info.")
677 (defcustom org-comment-string "COMMENT"
678 "Entries starting with this keyword will never be exported.
679 An entry can be toggled between COMMENT and normal with
680 \\[org-toggle-comment].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-quote-string "QUOTE"
686 "Entries starting with this keyword will be exported in fixed-width font.
687 Quoting applies only to the text in the entry following the headline, and does
688 not extend beyond the next headline, even if that is lower level.
689 An entry can be toggled between QUOTE and normal with
690 \\[org-toggle-fixed-width-section]."
691 :group 'org-keywords
692 :type 'string)
694 (defconst org-repeat-re
695 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
696 "Regular expression for specifying repeated events.
697 After a match, group 1 contains the repeat expression.")
699 (defgroup org-structure nil
700 "Options concerning the general structure of Org-mode files."
701 :tag "Org Structure"
702 :group 'org)
704 (defgroup org-reveal-location nil
705 "Options about how to make context of a location visible."
706 :tag "Org Reveal Location"
707 :group 'org-structure)
709 (defconst org-context-choice
710 '(choice
711 (const :tag "Always" t)
712 (const :tag "Never" nil)
713 (repeat :greedy t :tag "Individual contexts"
714 (cons
715 (choice :tag "Context"
716 (const agenda)
717 (const org-goto)
718 (const occur-tree)
719 (const tags-tree)
720 (const link-search)
721 (const mark-goto)
722 (const bookmark-jump)
723 (const isearch)
724 (const default))
725 (boolean))))
726 "Contexts for the reveal options.")
728 (defcustom org-show-hierarchy-above '((default . t))
729 "Non-nil means show full hierarchy when revealing a location.
730 Org-mode often shows locations in an org-mode file which might have
731 been invisible before. When this is set, the hierarchy of headings
732 above the exposed location is shown.
733 Turning this off for example for sparse trees makes them very compact.
734 Instead of t, this can also be an alist specifying this option for different
735 contexts. Valid contexts are
736 agenda when exposing an entry from the agenda
737 org-goto when using the command `org-goto' on key C-c C-j
738 occur-tree when using the command `org-occur' on key C-c /
739 tags-tree when constructing a sparse tree based on tags matches
740 link-search when exposing search matches associated with a link
741 mark-goto when exposing the jump goal of a mark
742 bookmark-jump when exposing a bookmark location
743 isearch when exiting from an incremental search
744 default default for all contexts not set explicitly"
745 :group 'org-reveal-location
746 :type org-context-choice)
748 (defcustom org-show-following-heading '((default . nil))
749 "Non-nil means show following heading when revealing a location.
750 Org-mode often shows locations in an org-mode file which might have
751 been invisible before. When this is set, the heading following the
752 match is shown.
753 Turning this off for example for sparse trees makes them very compact,
754 but makes it harder to edit the location of the match. In such a case,
755 use the command \\[org-reveal] to show more context.
756 Instead of t, this can also be an alist specifying this option for different
757 contexts. See `org-show-hierarchy-above' for valid contexts."
758 :group 'org-reveal-location
759 :type org-context-choice)
761 (defcustom org-show-siblings '((default . nil) (isearch t))
762 "Non-nil means show all sibling heading when revealing a location.
763 Org-mode often shows locations in an org-mode file which might have
764 been invisible before. When this is set, the sibling of the current entry
765 heading are all made visible. If `org-show-hierarchy-above' is t,
766 the same happens on each level of the hierarchy above the current entry.
768 By default this is on for the isearch context, off for all other contexts.
769 Turning this off for example for sparse trees makes them very compact,
770 but makes it harder to edit the location of the match. In such a case,
771 use the command \\[org-reveal] to show more context.
772 Instead of t, this can also be an alist specifying this option for different
773 contexts. See `org-show-hierarchy-above' for valid contexts."
774 :group 'org-reveal-location
775 :type org-context-choice)
777 (defcustom org-show-entry-below '((default . nil))
778 "Non-nil means show the entry below a headline when revealing a location.
779 Org-mode often shows locations in an org-mode file which might have
780 been invisible before. When this is set, the text below the headline that is
781 exposed is also shown.
783 By default this is off for all contexts.
784 Instead of t, this can also be an alist specifying this option for different
785 contexts. See `org-show-hierarchy-above' for valid contexts."
786 :group 'org-reveal-location
787 :type org-context-choice)
789 (defcustom org-indirect-buffer-display 'other-window
790 "How should indirect tree buffers be displayed?
791 This applies to indirect buffers created with the commands
792 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
793 Valid values are:
794 current-window Display in the current window
795 other-window Just display in another window.
796 dedicated-frame Create one new frame, and re-use it each time.
797 new-frame Make a new frame each time. Note that in this case
798 previously-made indirect buffers are kept, and you need to
799 kill these buffers yourself."
800 :group 'org-structure
801 :group 'org-agenda-windows
802 :type '(choice
803 (const :tag "In current window" current-window)
804 (const :tag "In current frame, other window" other-window)
805 (const :tag "Each time a new frame" new-frame)
806 (const :tag "One dedicated frame" dedicated-frame)))
808 (defcustom org-use-speed-commands nil
809 "Non-nil means activate single letter commands at beginning of a headline.
810 This may also be a function to test for appropriate locations where speed
811 commands should be active."
812 :group 'org-structure
813 :type '(choice
814 (const :tag "Never" nil)
815 (const :tag "At beginning of headline stars" t)
816 (function)))
818 (defcustom org-speed-commands-user nil
819 "Alist of additional speed commands.
820 This list will be checked before `org-speed-commands-default'
821 when the variable `org-use-speed-commands' is non-nil
822 and when the cursor is at the beginning of a headline.
823 The car if each entry is a string with a single letter, which must
824 be assigned to `self-insert-command' in the global map.
825 The cdr is either a command to be called interactively, a function
826 to be called, or a form to be evaluated.
827 An entry that is just a list with a single string will be interpreted
828 as a descriptive headline that will be added when listing the speed
829 commands in the Help buffer using the `?' speed command."
830 :group 'org-structure
831 :type '(repeat :value ("k" . ignore)
832 (choice :value ("k" . ignore)
833 (list :tag "Descriptive Headline" (string :tag "Headline"))
834 (cons :tag "Letter and Command"
835 (string :tag "Command letter")
836 (choice
837 (function)
838 (sexp))))))
840 (defgroup org-cycle nil
841 "Options concerning visibility cycling in Org-mode."
842 :tag "Org Cycle"
843 :group 'org-structure)
845 (defcustom org-cycle-skip-children-state-if-no-children t
846 "Non-nil means skip CHILDREN state in entries that don't have any."
847 :group 'org-cycle
848 :type 'boolean)
850 (defcustom org-cycle-max-level nil
851 "Maximum level which should still be subject to visibility cycling.
852 Levels higher than this will, for cycling, be treated as text, not a headline.
853 When `org-odd-levels-only' is set, a value of N in this variable actually
854 means 2N-1 stars as the limiting headline.
855 When nil, cycle all levels.
856 Note that the limiting level of cycling is also influenced by
857 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
858 `org-inlinetask-min-level' is, cycling will be limited to levels one less
859 than its value."
860 :group 'org-cycle
861 :type '(choice
862 (const :tag "No limit" nil)
863 (integer :tag "Maximum level")))
865 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
866 "Names of drawers. Drawers are not opened by cycling on the headline above.
867 Drawers only open with a TAB on the drawer line itself. A drawer looks like
868 this:
869 :DRAWERNAME:
870 .....
871 :END:
872 The drawer \"PROPERTIES\" is special for capturing properties through
873 the property API.
875 Drawers can be defined on the per-file basis with a line like:
877 #+DRAWERS: HIDDEN STATE PROPERTIES"
878 :group 'org-structure
879 :group 'org-cycle
880 :type '(repeat (string :tag "Drawer Name")))
882 (defcustom org-hide-block-startup nil
883 "Non-nil means entering Org-mode will fold all blocks.
884 This can also be set in on a per-file basis with
886 #+STARTUP: hideblocks
887 #+STARTUP: showblocks"
888 :group 'org-startup
889 :group 'org-cycle
890 :type 'boolean)
892 (defcustom org-cycle-global-at-bob nil
893 "Cycle globally if cursor is at beginning of buffer and not at a headline.
894 This makes it possible to do global cycling without having to use S-TAB or
895 \\[universal-argument] TAB. For this special case to work, the first line \
896 of the buffer
897 must not be a headline - it may be empty or some other text. When used in
898 this way, `org-cycle-hook' is disables temporarily, to make sure the
899 cursor stays at the beginning of the buffer.
900 When this option is nil, don't do anything special at the beginning
901 of the buffer."
902 :group 'org-cycle
903 :type 'boolean)
905 (defcustom org-cycle-level-after-item/entry-creation t
906 "Non-nil means cycle entry level or item indentation in new empty entries.
908 When the cursor is at the end of an empty headline, i.e with only stars
909 and maybe a TODO keyword, TAB will then switch the entry to become a child,
910 and then all possible ancestor states, before returning to the original state.
911 This makes data entry extremely fast: M-RET to create a new headline,
912 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
914 When the cursor is at the end of an empty plain list item, one TAB will
915 make it a subitem, two or more tabs will back up to make this an item
916 higher up in the item hierarchy."
917 :group 'org-cycle
918 :type 'boolean)
920 (defcustom org-cycle-emulate-tab t
921 "Where should `org-cycle' emulate TAB.
922 nil Never
923 white Only in completely white lines
924 whitestart Only at the beginning of lines, before the first non-white char
925 t Everywhere except in headlines
926 exc-hl-bol Everywhere except at the start of a headline
927 If TAB is used in a place where it does not emulate TAB, the current subtree
928 visibility is cycled."
929 :group 'org-cycle
930 :type '(choice (const :tag "Never" nil)
931 (const :tag "Only in completely white lines" white)
932 (const :tag "Before first char in a line" whitestart)
933 (const :tag "Everywhere except in headlines" t)
934 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
937 (defcustom org-cycle-separator-lines 2
938 "Number of empty lines needed to keep an empty line between collapsed trees.
939 If you leave an empty line between the end of a subtree and the following
940 headline, this empty line is hidden when the subtree is folded.
941 Org-mode will leave (exactly) one empty line visible if the number of
942 empty lines is equal or larger to the number given in this variable.
943 So the default 2 means at least 2 empty lines after the end of a subtree
944 are needed to produce free space between a collapsed subtree and the
945 following headline.
947 If the number is negative, and the number of empty lines is at least -N,
948 all empty lines are shown.
950 Special case: when 0, never leave empty lines in collapsed view."
951 :group 'org-cycle
952 :type 'integer)
953 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
955 (defcustom org-pre-cycle-hook nil
956 "Hook that is run before visibility cycling is happening.
957 The function(s) in this hook must accept a single argument which indicates
958 the new state that will be set right after running this hook. The
959 argument is a symbol. Before a global state change, it can have the values
960 `overview', `content', or `all'. Before a local state change, it can have
961 the values `folded', `children', or `subtree'."
962 :group 'org-cycle
963 :type 'hook)
965 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
966 org-cycle-hide-drawers
967 org-cycle-show-empty-lines
968 org-optimize-window-after-visibility-change)
969 "Hook that is run after `org-cycle' has changed the buffer visibility.
970 The function(s) in this hook must accept a single argument which indicates
971 the new state that was set by the most recent `org-cycle' command. The
972 argument is a symbol. After a global state change, it can have the values
973 `overview', `content', or `all'. After a local state change, it can have
974 the values `folded', `children', or `subtree'."
975 :group 'org-cycle
976 :type 'hook)
978 (defgroup org-edit-structure nil
979 "Options concerning structure editing in Org-mode."
980 :tag "Org Edit Structure"
981 :group 'org-structure)
983 (defcustom org-odd-levels-only nil
984 "Non-nil means skip even levels and only use odd levels for the outline.
985 This has the effect that two stars are being added/taken away in
986 promotion/demotion commands. It also influences how levels are
987 handled by the exporters.
988 Changing it requires restart of `font-lock-mode' to become effective
989 for fontification also in regions already fontified.
990 You may also set this on a per-file basis by adding one of the following
991 lines to the buffer:
993 #+STARTUP: odd
994 #+STARTUP: oddeven"
995 :group 'org-edit-structure
996 :group 'org-appearance
997 :type 'boolean)
999 (defcustom org-adapt-indentation t
1000 "Non-nil means adapt indentation to outline node level.
1002 When this variable is set, Org assumes that you write outlines by
1003 indenting text in each node to align with the headline (after the stars).
1004 The following issues are influenced by this variable:
1006 - When this is set and the *entire* text in an entry is indented, the
1007 indentation is increased by one space in a demotion command, and
1008 decreased by one in a promotion command. If any line in the entry
1009 body starts with text at column 0, indentation is not changed at all.
1011 - Property drawers and planning information is inserted indented when
1012 this variable s set. When nil, they will not be indented.
1014 - TAB indents a line relative to context. The lines below a headline
1015 will be indented when this variable is set.
1017 Note that this is all about true indentation, by adding and removing
1018 space characters. See also `org-indent.el' which does level-dependent
1019 indentation in a virtual way, i.e. at display time in Emacs."
1020 :group 'org-edit-structure
1021 :type 'boolean)
1023 (defcustom org-special-ctrl-a/e nil
1024 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1026 When t, `C-a' will bring back the cursor to the beginning of the
1027 headline text, i.e. after the stars and after a possible TODO
1028 keyword. In an item, this will be the position after bullet and
1029 check-box, if any. When the cursor is already at that position,
1030 another `C-a' will bring it to the beginning of the line.
1032 `C-e' will jump to the end of the headline, ignoring the presence
1033 of tags in the headline. A second `C-e' will then jump to the
1034 true end of the line, after any tags. This also means that, when
1035 this variable is non-nil, `C-e' also will never jump beyond the
1036 end of the heading of a folded section, i.e. not after the
1037 ellipses.
1039 When set to the symbol `reversed', the first `C-a' or `C-e' works
1040 normally, going to the true line boundary first. Only a directly
1041 following, identical keypress will bring the cursor to the
1042 special positions.
1044 This may also be a cons cell where the behavior for `C-a' and
1045 `C-e' is set separately."
1046 :group 'org-edit-structure
1047 :type '(choice
1048 (const :tag "off" nil)
1049 (const :tag "on: after stars/bullet and before tags first" t)
1050 (const :tag "reversed: true line boundary first" reversed)
1051 (cons :tag "Set C-a and C-e separately"
1052 (choice :tag "Special C-a"
1053 (const :tag "off" nil)
1054 (const :tag "on: after stars/bullet first" t)
1055 (const :tag "reversed: before stars/bullet first" reversed))
1056 (choice :tag "Special C-e"
1057 (const :tag "off" nil)
1058 (const :tag "on: before tags first" t)
1059 (const :tag "reversed: after tags first" reversed)))))
1060 (if (fboundp 'defvaralias)
1061 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1063 (defcustom org-special-ctrl-k nil
1064 "Non-nil means `C-k' will behave specially in headlines.
1065 When nil, `C-k' will call the default `kill-line' command.
1066 When t, the following will happen while the cursor is in the headline:
1068 - When the cursor is at the beginning of a headline, kill the entire
1069 line and possible the folded subtree below the line.
1070 - When in the middle of the headline text, kill the headline up to the tags.
1071 - When after the headline text, kill the tags."
1072 :group 'org-edit-structure
1073 :type 'boolean)
1075 (defcustom org-ctrl-k-protect-subtree nil
1076 "Non-nil means, do not delete a hidden subtree with C-k.
1077 When set to the symbol `error', simply throw an error when C-k is
1078 used to kill (part-of) a headline that has hidden text behind it.
1079 Any other non-nil value will result in a query to the user, if it is
1080 OK to kill that hidden subtree. When nil, kill without remorse."
1081 :group 'org-edit-structure
1082 :version "24.1"
1083 :type '(choice
1084 (const :tag "Do not protect hidden subtrees" nil)
1085 (const :tag "Protect hidden subtrees with a security query" t)
1086 (const :tag "Never kill a hidden subtree with C-k" error)))
1088 (defcustom org-catch-invisible-edits nil
1089 "Check if in invisible region before inserting or deleting a character.
1090 Valid values are:
1092 nil Do not check, so just do invisible edits.
1093 error Throw an error and do nothing.
1094 show Make point visible, and do the requested edit.
1095 show-and-error Make point visible, then throw an error and abort the edit.
1096 smart Make point visible, and do insertion/deletion if it is
1097 adjacent to visible text and the change feels predictable.
1098 Never delete a previously invisible character or add in the
1099 middle or right after an invisible region. Basically, this
1100 allows insertion and backward-delete right before ellipses.
1101 FIXME: maybe in this case we should not even show?"
1102 :group 'org-edit-structure
1103 :version "24.1"
1104 :type '(choice
1105 (const :tag "Do not check" nil)
1106 (const :tag "Throw error when trying to edit" error)
1107 (const :tag "Unhide, but do not do the edit" show-and-error)
1108 (const :tag "Show invisible part and do the edit" show)
1109 (const :tag "Be smart and do the right thing" smart)))
1111 (defcustom org-yank-folded-subtrees t
1112 "Non-nil means when yanking subtrees, fold them.
1113 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1114 it starts with a heading and all other headings in it are either children
1115 or siblings, then fold all the subtrees. However, do this only if no
1116 text after the yank would be swallowed into a folded tree by this action."
1117 :group 'org-edit-structure
1118 :type 'boolean)
1120 (defcustom org-yank-adjusted-subtrees nil
1121 "Non-nil means when yanking subtrees, adjust the level.
1122 With this setting, `org-paste-subtree' is used to insert the subtree, see
1123 this function for details."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defcustom org-M-RET-may-split-line '((default . t))
1128 "Non-nil means M-RET will split the line at the cursor position.
1129 When nil, it will go to the end of the line before making a
1130 new line.
1131 You may also set this option in a different way for different
1132 contexts. Valid contexts are:
1134 headline when creating a new headline
1135 item when creating a new item
1136 table in a table field
1137 default the value to be used for all contexts not explicitly
1138 customized"
1139 :group 'org-structure
1140 :group 'org-table
1141 :type '(choice
1142 (const :tag "Always" t)
1143 (const :tag "Never" nil)
1144 (repeat :greedy t :tag "Individual contexts"
1145 (cons
1146 (choice :tag "Context"
1147 (const headline)
1148 (const item)
1149 (const table)
1150 (const default))
1151 (boolean)))))
1154 (defcustom org-insert-heading-respect-content nil
1155 "Non-nil means insert new headings after the current subtree.
1156 When nil, the new heading is created directly after the current line.
1157 The commands \\[org-insert-heading-respect-content] and
1158 \\[org-insert-todo-heading-respect-content] turn this variable on
1159 for the duration of the command."
1160 :group 'org-structure
1161 :type 'boolean)
1163 (defcustom org-blank-before-new-entry '((heading . auto)
1164 (plain-list-item . auto))
1165 "Should `org-insert-heading' leave a blank line before new heading/item?
1166 The value is an alist, with `heading' and `plain-list-item' as CAR,
1167 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1168 which case Org will look at the surrounding headings/items and try to
1169 make an intelligent decision whether to insert a blank line or not.
1171 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1172 set, the setting here is ignored and no empty line is inserted, to avoid
1173 breaking the list structure."
1174 :group 'org-edit-structure
1175 :type '(list
1176 (cons (const heading)
1177 (choice (const :tag "Never" nil)
1178 (const :tag "Always" t)
1179 (const :tag "Auto" auto)))
1180 (cons (const plain-list-item)
1181 (choice (const :tag "Never" nil)
1182 (const :tag "Always" t)
1183 (const :tag "Auto" auto)))))
1185 (defcustom org-insert-heading-hook nil
1186 "Hook being run after inserting a new heading."
1187 :group 'org-edit-structure
1188 :type 'hook)
1190 (defcustom org-enable-fixed-width-editor t
1191 "Non-nil means lines starting with \":\" are treated as fixed-width.
1192 This currently only means they are never auto-wrapped.
1193 When nil, such lines will be treated like ordinary lines.
1194 See also the QUOTE keyword."
1195 :group 'org-edit-structure
1196 :type 'boolean)
1198 (defcustom org-goto-auto-isearch t
1199 "Non-nil means typing characters in `org-goto' starts incremental search."
1200 :group 'org-edit-structure
1201 :type 'boolean)
1203 (defgroup org-sparse-trees nil
1204 "Options concerning sparse trees in Org-mode."
1205 :tag "Org Sparse Trees"
1206 :group 'org-structure)
1208 (defcustom org-highlight-sparse-tree-matches t
1209 "Non-nil means highlight all matches that define a sparse tree.
1210 The highlights will automatically disappear the next time the buffer is
1211 changed by an edit command."
1212 :group 'org-sparse-trees
1213 :type 'boolean)
1215 (defcustom org-remove-highlights-with-change t
1216 "Non-nil means any change to the buffer will remove temporary highlights.
1217 Such highlights are created by `org-occur' and `org-clock-display'.
1218 When nil, `C-c C-c needs to be used to get rid of the highlights.
1219 The highlights created by `org-preview-latex-fragment' always need
1220 `C-c C-c' to be removed."
1221 :group 'org-sparse-trees
1222 :group 'org-time
1223 :type 'boolean)
1226 (defcustom org-occur-hook '(org-first-headline-recenter)
1227 "Hook that is run after `org-occur' has constructed a sparse tree.
1228 This can be used to recenter the window to show as much of the structure
1229 as possible."
1230 :group 'org-sparse-trees
1231 :type 'hook)
1233 (defgroup org-imenu-and-speedbar nil
1234 "Options concerning imenu and speedbar in Org-mode."
1235 :tag "Org Imenu and Speedbar"
1236 :group 'org-structure)
1238 (defcustom org-imenu-depth 2
1239 "The maximum level for Imenu access to Org-mode headlines.
1240 This also applied for speedbar access."
1241 :group 'org-imenu-and-speedbar
1242 :type 'integer)
1244 (defgroup org-table nil
1245 "Options concerning tables in Org-mode."
1246 :tag "Org Table"
1247 :group 'org)
1249 (defcustom org-enable-table-editor 'optimized
1250 "Non-nil means lines starting with \"|\" are handled by the table editor.
1251 When nil, such lines will be treated like ordinary lines.
1253 When equal to the symbol `optimized', the table editor will be optimized to
1254 do the following:
1255 - Automatic overwrite mode in front of whitespace in table fields.
1256 This makes the structure of the table stay in tact as long as the edited
1257 field does not exceed the column width.
1258 - Minimize the number of realigns. Normally, the table is aligned each time
1259 TAB or RET are pressed to move to another field. With optimization this
1260 happens only if changes to a field might have changed the column width.
1261 Optimization requires replacing the functions `self-insert-command',
1262 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1263 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1264 very good at guessing when a re-align will be necessary, but you can always
1265 force one with \\[org-ctrl-c-ctrl-c].
1267 If you would like to use the optimized version in Org-mode, but the
1268 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1270 This variable can be used to turn on and off the table editor during a session,
1271 but in order to toggle optimization, a restart is required.
1273 See also the variable `org-table-auto-blank-field'."
1274 :group 'org-table
1275 :type '(choice
1276 (const :tag "off" nil)
1277 (const :tag "on" t)
1278 (const :tag "on, optimized" optimized)))
1280 (defcustom org-self-insert-cluster-for-undo t
1281 "Non-nil means cluster self-insert commands for undo when possible.
1282 If this is set, then, like in the Emacs command loop, 20 consecutive
1283 characters will be undone together.
1284 This is configurable, because there is some impact on typing performance."
1285 :group 'org-table
1286 :type 'boolean)
1288 (defcustom org-table-tab-recognizes-table.el t
1289 "Non-nil means TAB will automatically notice a table.el table.
1290 When it sees such a table, it moves point into it and - if necessary -
1291 calls `table-recognize-table'."
1292 :group 'org-table-editing
1293 :type 'boolean)
1295 (defgroup org-link nil
1296 "Options concerning links in Org-mode."
1297 :tag "Org Link"
1298 :group 'org)
1300 (defvar org-link-abbrev-alist-local nil
1301 "Buffer-local version of `org-link-abbrev-alist', which see.
1302 The value of this is taken from the #+LINK lines.")
1303 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1305 (defcustom org-link-abbrev-alist nil
1306 "Alist of link abbreviations.
1307 The car of each element is a string, to be replaced at the start of a link.
1308 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1309 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1311 [[linkkey:tag][description]]
1313 The 'linkkey' must be a word word, starting with a letter, followed
1314 by letters, numbers, '-' or '_'.
1316 If REPLACE is a string, the tag will simply be appended to create the link.
1317 If the string contains \"%s\", the tag will be inserted there. If the string
1318 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1319 at that point (see the function `url-hexify-string'). If the string contains
1320 the specifier \"%(my-function)\", then the custom function `my-function' will
1321 be invoked: this function takes the tag as its only argument and must return
1322 a string.
1324 REPLACE may also be a function that will be called with the tag as the
1325 only argument to create the link, which should be returned as a string.
1327 See the manual for examples."
1328 :group 'org-link
1329 :type '(repeat
1330 (cons
1331 (string :tag "Protocol")
1332 (choice
1333 (string :tag "Format")
1334 (function)))))
1336 (defcustom org-descriptive-links t
1337 "Non-nil means Org will display descriptive links.
1338 E.g. [[http://orgmode.org][Org website]] will be displayed as
1339 \"Org Website\", hiding the link itself and just displaying its
1340 description. When set to `nil', Org will display the full links
1341 literally.
1343 You can interactively set the value of this variable by calling
1344 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1345 :group 'org-link
1346 :type 'boolean)
1348 (defcustom org-link-file-path-type 'adaptive
1349 "How the path name in file links should be stored.
1350 Valid values are:
1352 relative Relative to the current directory, i.e. the directory of the file
1353 into which the link is being inserted.
1354 absolute Absolute path, if possible with ~ for home directory.
1355 noabbrev Absolute path, no abbreviation of home directory.
1356 adaptive Use relative path for files in the current directory and sub-
1357 directories of it. For other files, use an absolute path."
1358 :group 'org-link
1359 :type '(choice
1360 (const relative)
1361 (const absolute)
1362 (const noabbrev)
1363 (const adaptive)))
1365 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1366 "Types of links that should be activated in Org-mode files.
1367 This is a list of symbols, each leading to the activation of a certain link
1368 type. In principle, it does not hurt to turn on most link types - there may
1369 be a small gain when turning off unused link types. The types are:
1371 bracket The recommended [[link][description]] or [[link]] links with hiding.
1372 angle Links in angular brackets that may contain whitespace like
1373 <bbdb:Carsten Dominik>.
1374 plain Plain links in normal text, no whitespace, like http://google.com.
1375 radio Text that is matched by a radio target, see manual for details.
1376 tag Tag settings in a headline (link to tag search).
1377 date Time stamps (link to calendar).
1378 footnote Footnote labels.
1380 Changing this variable requires a restart of Emacs to become effective."
1381 :group 'org-link
1382 :type '(set :greedy t
1383 (const :tag "Double bracket links" bracket)
1384 (const :tag "Angular bracket links" angle)
1385 (const :tag "Plain text links" plain)
1386 (const :tag "Radio target matches" radio)
1387 (const :tag "Tags" tag)
1388 (const :tag "Timestamps" date)
1389 (const :tag "Footnotes" footnote)))
1391 (defcustom org-make-link-description-function nil
1392 "Function to use to generate link descriptions from links.
1393 If nil the link location will be used. This function must take
1394 two parameters; the first is the link and the second the
1395 description `org-insert-link' has generated, and should return the
1396 description to use."
1397 :group 'org-link
1398 :type 'function)
1400 (defgroup org-link-store nil
1401 "Options concerning storing links in Org-mode."
1402 :tag "Org Store Link"
1403 :group 'org-link)
1405 (defcustom org-email-link-description-format "Email %c: %.30s"
1406 "Format of the description part of a link to an email or usenet message.
1407 The following %-escapes will be replaced by corresponding information:
1409 %F full \"From\" field
1410 %f name, taken from \"From\" field, address if no name
1411 %T full \"To\" field
1412 %t first name in \"To\" field, address if no name
1413 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1414 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1415 %s subject
1416 %d date
1417 %m message-id.
1419 You may use normal field width specification between the % and the letter.
1420 This is for example useful to limit the length of the subject.
1422 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1423 :group 'org-link-store
1424 :type 'string)
1426 (defcustom org-from-is-user-regexp
1427 (let (r1 r2)
1428 (when (and user-mail-address (not (string= user-mail-address "")))
1429 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1430 (when (and user-full-name (not (string= user-full-name "")))
1431 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1432 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1433 "Regexp matched against the \"From:\" header of an email or usenet message.
1434 It should match if the message is from the user him/herself."
1435 :group 'org-link-store
1436 :type 'regexp)
1438 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1439 "Non-nil means storing a link to an Org file will use entry IDs.
1441 Note that before this variable is even considered, org-id must be loaded,
1442 so please customize `org-modules' and turn it on.
1444 The variable can have the following values:
1446 t Create an ID if needed to make a link to the current entry.
1448 create-if-interactive
1449 If `org-store-link' is called directly (interactively, as a user
1450 command), do create an ID to support the link. But when doing the
1451 job for remember, only use the ID if it already exists. The
1452 purpose of this setting is to avoid proliferation of unwanted
1453 IDs, just because you happen to be in an Org file when you
1454 call `org-remember' that automatically and preemptively
1455 creates a link. If you do want to get an ID link in a remember
1456 template to an entry not having an ID, create it first by
1457 explicitly creating a link to it, using `C-c C-l' first.
1459 create-if-interactive-and-no-custom-id
1460 Like create-if-interactive, but do not create an ID if there is
1461 a CUSTOM_ID property defined in the entry. This is the default.
1463 use-existing
1464 Use existing ID, do not create one.
1466 nil Never use an ID to make a link, instead link using a text search for
1467 the headline text."
1468 :group 'org-link-store
1469 :type '(choice
1470 (const :tag "Create ID to make link" t)
1471 (const :tag "Create if storing link interactively"
1472 create-if-interactive)
1473 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1474 create-if-interactive-and-no-custom-id)
1475 (const :tag "Only use existing" use-existing)
1476 (const :tag "Do not use ID to create link" nil)))
1478 (defcustom org-context-in-file-links t
1479 "Non-nil means file links from `org-store-link' contain context.
1480 A search string will be added to the file name with :: as separator and
1481 used to find the context when the link is activated by the command
1482 `org-open-at-point'. When this option is t, the entire active region
1483 will be placed in the search string of the file link. If set to a
1484 positive integer, only the first n lines of context will be stored.
1486 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1487 negates this setting for the duration of the command."
1488 :group 'org-link-store
1489 :type '(choice boolean integer))
1491 (defcustom org-keep-stored-link-after-insertion nil
1492 "Non-nil means keep link in list for entire session.
1494 The command `org-store-link' adds a link pointing to the current
1495 location to an internal list. These links accumulate during a session.
1496 The command `org-insert-link' can be used to insert links into any
1497 Org-mode file (offering completion for all stored links). When this
1498 option is nil, every link which has been inserted once using \\[org-insert-link]
1499 will be removed from the list, to make completing the unused links
1500 more efficient."
1501 :group 'org-link-store
1502 :type 'boolean)
1504 (defgroup org-link-follow nil
1505 "Options concerning following links in Org-mode."
1506 :tag "Org Follow Link"
1507 :group 'org-link)
1509 (defcustom org-link-translation-function nil
1510 "Function to translate links with different syntax to Org syntax.
1511 This can be used to translate links created for example by the Planner
1512 or emacs-wiki packages to Org syntax.
1513 The function must accept two parameters, a TYPE containing the link
1514 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1515 which is everything after the link protocol. It should return a cons
1516 with possibly modified values of type and path.
1517 Org contains a function for this, so if you set this variable to
1518 `org-translate-link-from-planner', you should be able follow many
1519 links created by planner."
1520 :group 'org-link-follow
1521 :type 'function)
1523 (defcustom org-follow-link-hook nil
1524 "Hook that is run after a link has been followed."
1525 :group 'org-link-follow
1526 :type 'hook)
1528 (defcustom org-tab-follows-link nil
1529 "Non-nil means on links TAB will follow the link.
1530 Needs to be set before org.el is loaded.
1531 This really should not be used, it does not make sense, and the
1532 implementation is bad."
1533 :group 'org-link-follow
1534 :type 'boolean)
1536 (defcustom org-return-follows-link nil
1537 "Non-nil means on links RET will follow the link."
1538 :group 'org-link-follow
1539 :type 'boolean)
1541 (defcustom org-mouse-1-follows-link
1542 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1543 "Non-nil means mouse-1 on a link will follow the link.
1544 A longer mouse click will still set point. Does not work on XEmacs.
1545 Needs to be set before org.el is loaded."
1546 :group 'org-link-follow
1547 :type 'boolean)
1549 (defcustom org-mark-ring-length 4
1550 "Number of different positions to be recorded in the ring.
1551 Changing this requires a restart of Emacs to work correctly."
1552 :group 'org-link-follow
1553 :type 'integer)
1555 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1556 "Non-nil means internal links in Org files must exactly match a headline.
1557 When nil, the link search tries to match a phrase with all words
1558 in the search text."
1559 :group 'org-link-follow
1560 :version "24.1"
1561 :type '(choice
1562 (const :tag "Use fuzzy text search" nil)
1563 (const :tag "Match only exact headline" t)
1564 (const :tag "Match exact headline or query to create it"
1565 query-to-create)))
1567 (defcustom org-link-frame-setup
1568 '((vm . vm-visit-folder-other-frame)
1569 (vm-imap . vm-visit-imap-folder-other-frame)
1570 (gnus . org-gnus-no-new-news)
1571 (file . find-file-other-window)
1572 (wl . wl-other-frame))
1573 "Setup the frame configuration for following links.
1574 When following a link with Emacs, it may often be useful to display
1575 this link in another window or frame. This variable can be used to
1576 set this up for the different types of links.
1577 For VM, use any of
1578 `vm-visit-folder'
1579 `vm-visit-folder-other-window'
1580 `vm-visit-folder-other-frame'
1581 For Gnus, use any of
1582 `gnus'
1583 `gnus-other-frame'
1584 `org-gnus-no-new-news'
1585 For FILE, use any of
1586 `find-file'
1587 `find-file-other-window'
1588 `find-file-other-frame'
1589 For Wanderlust use any of
1590 `wl'
1591 `wl-other-frame'
1592 For the calendar, use the variable `calendar-setup'.
1593 For BBDB, it is currently only possible to display the matches in
1594 another window."
1595 :group 'org-link-follow
1596 :type '(list
1597 (cons (const vm)
1598 (choice
1599 (const vm-visit-folder)
1600 (const vm-visit-folder-other-window)
1601 (const vm-visit-folder-other-frame)))
1602 (cons (const gnus)
1603 (choice
1604 (const gnus)
1605 (const gnus-other-frame)
1606 (const org-gnus-no-new-news)))
1607 (cons (const file)
1608 (choice
1609 (const find-file)
1610 (const find-file-other-window)
1611 (const find-file-other-frame)))
1612 (cons (const wl)
1613 (choice
1614 (const wl)
1615 (const wl-other-frame)))))
1617 (defcustom org-display-internal-link-with-indirect-buffer nil
1618 "Non-nil means use indirect buffer to display infile links.
1619 Activating internal links (from one location in a file to another location
1620 in the same file) normally just jumps to the location. When the link is
1621 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1622 is displayed in
1623 another window. When this option is set, the other window actually displays
1624 an indirect buffer clone of the current buffer, to avoid any visibility
1625 changes to the current buffer."
1626 :group 'org-link-follow
1627 :type 'boolean)
1629 (defcustom org-open-non-existing-files nil
1630 "Non-nil means `org-open-file' will open non-existing files.
1631 When nil, an error will be generated.
1632 This variable applies only to external applications because they
1633 might choke on non-existing files. If the link is to a file that
1634 will be opened in Emacs, the variable is ignored."
1635 :group 'org-link-follow
1636 :type 'boolean)
1638 (defcustom org-open-directory-means-index-dot-org nil
1639 "Non-nil means a link to a directory really means to index.org.
1640 When nil, following a directory link will run dired or open a finder/explorer
1641 window on that directory."
1642 :group 'org-link-follow
1643 :type 'boolean)
1645 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1646 "Function and arguments to call for following mailto links.
1647 This is a list with the first element being a Lisp function, and the
1648 remaining elements being arguments to the function. In string arguments,
1649 %a will be replaced by the address, and %s will be replaced by the subject
1650 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1651 :group 'org-link-follow
1652 :type '(choice
1653 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1654 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1655 (const :tag "message-mail" (message-mail "%a" "%s"))
1656 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1658 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1659 "Non-nil means ask for confirmation before executing shell links.
1660 Shell links can be dangerous: just think about a link
1662 [[shell:rm -rf ~/*][Google Search]]
1664 This link would show up in your Org-mode document as \"Google Search\",
1665 but really it would remove your entire home directory.
1666 Therefore we advise against setting this variable to nil.
1667 Just change it to `y-or-n-p' if you want to confirm with a
1668 single keystroke rather than having to type \"yes\"."
1669 :group 'org-link-follow
1670 :type '(choice
1671 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1672 (const :tag "with y-or-n (faster)" y-or-n-p)
1673 (const :tag "no confirmation (dangerous)" nil)))
1674 (put 'org-confirm-shell-link-function
1675 'safe-local-variable
1676 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1678 (defcustom org-confirm-shell-link-not-regexp ""
1679 "A regexp to skip confirmation for shell links."
1680 :group 'org-link-follow
1681 :version "24.1"
1682 :type 'regexp)
1684 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1685 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1686 Elisp links can be dangerous: just think about a link
1688 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1690 This link would show up in your Org-mode document as \"Google Search\",
1691 but really it would remove your entire home directory.
1692 Therefore we advise against setting this variable to nil.
1693 Just change it to `y-or-n-p' if you want to confirm with a
1694 single keystroke rather than having to type \"yes\"."
1695 :group 'org-link-follow
1696 :type '(choice
1697 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1698 (const :tag "with y-or-n (faster)" y-or-n-p)
1699 (const :tag "no confirmation (dangerous)" nil)))
1700 (put 'org-confirm-shell-link-function
1701 'safe-local-variable
1702 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1704 (defcustom org-confirm-elisp-link-not-regexp ""
1705 "A regexp to skip confirmation for Elisp links."
1706 :group 'org-link-follow
1707 :version "24.1"
1708 :type 'regexp)
1710 (defconst org-file-apps-defaults-gnu
1711 '((remote . emacs)
1712 (system . mailcap)
1713 (t . mailcap))
1714 "Default file applications on a UNIX or GNU/Linux system.
1715 See `org-file-apps'.")
1717 (defconst org-file-apps-defaults-macosx
1718 '((remote . emacs)
1719 (t . "open %s")
1720 (system . "open %s")
1721 ("ps.gz" . "gv %s")
1722 ("eps.gz" . "gv %s")
1723 ("dvi" . "xdvi %s")
1724 ("fig" . "xfig %s"))
1725 "Default file applications on a MacOS X system.
1726 The system \"open\" is known as a default, but we use X11 applications
1727 for some files for which the OS does not have a good default.
1728 See `org-file-apps'.")
1730 (defconst org-file-apps-defaults-windowsnt
1731 (list
1732 '(remote . emacs)
1733 (cons t
1734 (list (if (featurep 'xemacs)
1735 'mswindows-shell-execute
1736 'w32-shell-execute)
1737 "open" 'file))
1738 (cons 'system
1739 (list (if (featurep 'xemacs)
1740 'mswindows-shell-execute
1741 'w32-shell-execute)
1742 "open" 'file)))
1743 "Default file applications on a Windows NT system.
1744 The system \"open\" is used for most files.
1745 See `org-file-apps'.")
1747 (defcustom org-file-apps
1749 (auto-mode . emacs)
1750 ("\\.mm\\'" . default)
1751 ("\\.x?html?\\'" . default)
1752 ("\\.pdf\\'" . default)
1754 "External applications for opening `file:path' items in a document.
1755 Org-mode uses system defaults for different file types, but
1756 you can use this variable to set the application for a given file
1757 extension. The entries in this list are cons cells where the car identifies
1758 files and the cdr the corresponding command. Possible values for the
1759 file identifier are
1760 \"string\" A string as a file identifier can be interpreted in different
1761 ways, depending on its contents:
1763 - Alphanumeric characters only:
1764 Match links with this file extension.
1765 Example: (\"pdf\" . \"evince %s\")
1766 to open PDFs with evince.
1768 - Regular expression: Match links where the
1769 filename matches the regexp. If you want to
1770 use groups here, use shy groups.
1772 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1773 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1774 to open *.html and *.xhtml with firefox.
1776 - Regular expression which contains (non-shy) groups:
1777 Match links where the whole link, including \"::\", and
1778 anything after that, matches the regexp.
1779 In a custom command string, %1, %2, etc. are replaced with
1780 the parts of the link that were matched by the groups.
1781 For backwards compatibility, if a command string is given
1782 that does not use any of the group matches, this case is
1783 handled identically to the second one (i.e. match against
1784 file name only).
1785 In a custom lisp form, you can access the group matches with
1786 (match-string n link).
1788 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1789 to open [[file:document.pdf::5]] with evince at page 5.
1791 `directory' Matches a directory
1792 `remote' Matches a remote file, accessible through tramp or efs.
1793 Remote files most likely should be visited through Emacs
1794 because external applications cannot handle such paths.
1795 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1796 so all files Emacs knows how to handle. Using this with
1797 command `emacs' will open most files in Emacs. Beware that this
1798 will also open html files inside Emacs, unless you add
1799 (\"html\" . default) to the list as well.
1800 t Default for files not matched by any of the other options.
1801 `system' The system command to open files, like `open' on Windows
1802 and Mac OS X, and mailcap under GNU/Linux. This is the command
1803 that will be selected if you call `C-c C-o' with a double
1804 \\[universal-argument] \\[universal-argument] prefix.
1806 Possible values for the command are:
1807 `emacs' The file will be visited by the current Emacs process.
1808 `default' Use the default application for this file type, which is the
1809 association for t in the list, most likely in the system-specific
1810 part.
1811 This can be used to overrule an unwanted setting in the
1812 system-specific variable.
1813 `system' Use the system command for opening files, like \"open\".
1814 This command is specified by the entry whose car is `system'.
1815 Most likely, the system-specific version of this variable
1816 does define this command, but you can overrule/replace it
1817 here.
1818 string A command to be executed by a shell; %s will be replaced
1819 by the path to the file.
1820 sexp A Lisp form which will be evaluated. The file path will
1821 be available in the Lisp variable `file'.
1822 For more examples, see the system specific constants
1823 `org-file-apps-defaults-macosx'
1824 `org-file-apps-defaults-windowsnt'
1825 `org-file-apps-defaults-gnu'."
1826 :group 'org-link-follow
1827 :type '(repeat
1828 (cons (choice :value ""
1829 (string :tag "Extension")
1830 (const :tag "System command to open files" system)
1831 (const :tag "Default for unrecognized files" t)
1832 (const :tag "Remote file" remote)
1833 (const :tag "Links to a directory" directory)
1834 (const :tag "Any files that have Emacs modes"
1835 auto-mode))
1836 (choice :value ""
1837 (const :tag "Visit with Emacs" emacs)
1838 (const :tag "Use default" default)
1839 (const :tag "Use the system command" system)
1840 (string :tag "Command")
1841 (sexp :tag "Lisp form")))))
1843 (defcustom org-doi-server-url "http://dx.doi.org/"
1844 "The URL of the DOI server."
1845 :type 'string
1846 :version "24.2"
1847 :group 'org-link-follow)
1849 (defgroup org-refile nil
1850 "Options concerning refiling entries in Org-mode."
1851 :tag "Org Refile"
1852 :group 'org)
1854 (defcustom org-directory "~/org"
1855 "Directory with org files.
1856 This is just a default location to look for Org files. There is no need
1857 at all to put your files into this directory. It is only used in the
1858 following situations:
1860 1. When a remember template specifies a target file that is not an
1861 absolute path. The path will then be interpreted relative to
1862 `org-directory'
1863 2. When a remember note is filed away in an interactive way (when exiting the
1864 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1865 with `org-directory' as the default path."
1866 :group 'org-refile
1867 :group 'org-remember
1868 :type 'directory)
1870 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1871 "Default target for storing notes.
1872 Used as a fall back file for org-remember.el and org-capture.el, for
1873 templates that do not specify a target file."
1874 :group 'org-refile
1875 :group 'org-remember
1876 :type '(choice
1877 (const :tag "Default from remember-data-file" nil)
1878 file))
1880 (defcustom org-goto-interface 'outline
1881 "The default interface to be used for `org-goto'.
1882 Allowed values are:
1883 outline The interface shows an outline of the relevant file
1884 and the correct heading is found by moving through
1885 the outline or by searching with incremental search.
1886 outline-path-completion Headlines in the current buffer are offered via
1887 completion. This is the interface also used by
1888 the refile command."
1889 :group 'org-refile
1890 :type '(choice
1891 (const :tag "Outline" outline)
1892 (const :tag "Outline-path-completion" outline-path-completion)))
1894 (defcustom org-goto-max-level 5
1895 "Maximum target level when running `org-goto' with refile interface."
1896 :group 'org-refile
1897 :type 'integer)
1899 (defcustom org-reverse-note-order nil
1900 "Non-nil means store new notes at the beginning of a file or entry.
1901 When nil, new notes will be filed to the end of a file or entry.
1902 This can also be a list with cons cells of regular expressions that
1903 are matched against file names, and values."
1904 :group 'org-remember
1905 :group 'org-refile
1906 :type '(choice
1907 (const :tag "Reverse always" t)
1908 (const :tag "Reverse never" nil)
1909 (repeat :tag "By file name regexp"
1910 (cons regexp boolean))))
1912 (defcustom org-log-refile nil
1913 "Information to record when a task is refiled.
1915 Possible values are:
1917 nil Don't add anything
1918 time Add a time stamp to the task
1919 note Prompt for a note and add it with template `org-log-note-headings'
1921 This option can also be set with on a per-file-basis with
1923 #+STARTUP: nologrefile
1924 #+STARTUP: logrefile
1925 #+STARTUP: lognoterefile
1927 You can have local logging settings for a subtree by setting the LOGGING
1928 property to one or more of these keywords.
1930 When bulk-refiling from the agenda, the value `note' is forbidden and
1931 will temporarily be changed to `time'."
1932 :group 'org-refile
1933 :group 'org-progress
1934 :version "24.1"
1935 :type '(choice
1936 (const :tag "No logging" nil)
1937 (const :tag "Record timestamp" time)
1938 (const :tag "Record timestamp with note." note)))
1940 (defcustom org-refile-targets nil
1941 "Targets for refiling entries with \\[org-refile].
1942 This is a list of cons cells. Each cell contains:
1943 - a specification of the files to be considered, either a list of files,
1944 or a symbol whose function or variable value will be used to retrieve
1945 a file name or a list of file names. If you use `org-agenda-files' for
1946 that, all agenda files will be scanned for targets. Nil means consider
1947 headings in the current buffer.
1948 - A specification of how to find candidate refile targets. This may be
1949 any of:
1950 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1951 This tag has to be present in all target headlines, inheritance will
1952 not be considered.
1953 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1954 todo keyword.
1955 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1956 headlines that are refiling targets.
1957 - a cons cell (:level . N). Any headline of level N is considered a target.
1958 Note that, when `org-odd-levels-only' is set, level corresponds to
1959 order in hierarchy, not to the number of stars.
1960 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1961 Note that, when `org-odd-levels-only' is set, level corresponds to
1962 order in hierarchy, not to the number of stars.
1964 Each element of this list generates a set of possible targets.
1965 The union of these sets is presented (with completion) to
1966 the user by `org-refile'.
1968 You can set the variable `org-refile-target-verify-function' to a function
1969 to verify each headline found by the simple criteria above.
1971 When this variable is nil, all top-level headlines in the current buffer
1972 are used, equivalent to the value `((nil . (:level . 1))'."
1973 :group 'org-refile
1974 :type '(repeat
1975 (cons
1976 (choice :value org-agenda-files
1977 (const :tag "All agenda files" org-agenda-files)
1978 (const :tag "Current buffer" nil)
1979 (function) (variable) (file))
1980 (choice :tag "Identify target headline by"
1981 (cons :tag "Specific tag" (const :value :tag) (string))
1982 (cons :tag "TODO keyword" (const :value :todo) (string))
1983 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1984 (cons :tag "Level number" (const :value :level) (integer))
1985 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1987 (defcustom org-refile-target-verify-function nil
1988 "Function to verify if the headline at point should be a refile target.
1989 The function will be called without arguments, with point at the
1990 beginning of the headline. It should return t and leave point
1991 where it is if the headline is a valid target for refiling.
1993 If the target should not be selected, the function must return nil.
1994 In addition to this, it may move point to a place from where the search
1995 should be continued. For example, the function may decide that the entire
1996 subtree of the current entry should be excluded and move point to the end
1997 of the subtree."
1998 :group 'org-refile
1999 :type 'function)
2001 (defcustom org-refile-use-cache nil
2002 "Non-nil means cache refile targets to speed up the process.
2003 The cache for a particular file will be updated automatically when
2004 the buffer has been killed, or when any of the marker used for flagging
2005 refile targets no longer points at a live buffer.
2006 If you have added new entries to a buffer that might themselves be targets,
2007 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2008 find that easier, `C-u C-u C-u C-c C-w'."
2009 :group 'org-refile
2010 :version "24.1"
2011 :type 'boolean)
2013 (defcustom org-refile-use-outline-path nil
2014 "Non-nil means provide refile targets as paths.
2015 So a level 3 headline will be available as level1/level2/level3.
2017 When the value is `file', also include the file name (without directory)
2018 into the path. In this case, you can also stop the completion after
2019 the file name, to get entries inserted as top level in the file.
2021 When `full-file-path', include the full file path."
2022 :group 'org-refile
2023 :type '(choice
2024 (const :tag "Not" nil)
2025 (const :tag "Yes" t)
2026 (const :tag "Start with file name" file)
2027 (const :tag "Start with full file path" full-file-path)))
2029 (defcustom org-outline-path-complete-in-steps t
2030 "Non-nil means complete the outline path in hierarchical steps.
2031 When Org-mode uses the refile interface to select an outline path
2032 \(see variable `org-refile-use-outline-path'), the completion of
2033 the path can be done is a single go, or if can be done in steps down
2034 the headline hierarchy. Going in steps is probably the best if you
2035 do not use a special completion package like `ido' or `icicles'.
2036 However, when using these packages, going in one step can be very
2037 fast, while still showing the whole path to the entry."
2038 :group 'org-refile
2039 :type 'boolean)
2041 (defcustom org-refile-allow-creating-parent-nodes nil
2042 "Non-nil means allow to create new nodes as refile targets.
2043 New nodes are then created by adding \"/new node name\" to the completion
2044 of an existing node. When the value of this variable is `confirm',
2045 new node creation must be confirmed by the user (recommended)
2046 When nil, the completion must match an existing entry.
2048 Note that, if the new heading is not seen by the criteria
2049 listed in `org-refile-targets', multiple instances of the same
2050 heading would be created by trying again to file under the new
2051 heading."
2052 :group 'org-refile
2053 :type '(choice
2054 (const :tag "Never" nil)
2055 (const :tag "Always" t)
2056 (const :tag "Prompt for confirmation" confirm)))
2058 (defcustom org-refile-active-region-within-subtree nil
2059 "Non-nil means also refile active region within a subtree.
2061 By default `org-refile' doesn't allow refiling regions if they
2062 don't contain a set of subtrees, but it might be convenient to
2063 do so sometimes: in that case, the first line of the region is
2064 converted to a headline before refiling."
2065 :group 'org-refile
2066 :version "24.1"
2067 :type 'boolean)
2069 (defgroup org-todo nil
2070 "Options concerning TODO items in Org-mode."
2071 :tag "Org TODO"
2072 :group 'org)
2074 (defgroup org-progress nil
2075 "Options concerning Progress logging in Org-mode."
2076 :tag "Org Progress"
2077 :group 'org-time)
2079 (defvar org-todo-interpretation-widgets
2080 '((:tag "Sequence (cycling hits every state)" sequence)
2081 (:tag "Type (cycling directly to DONE)" type))
2082 "The available interpretation symbols for customizing `org-todo-keywords'.
2083 Interested libraries should add to this list.")
2085 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2086 "List of TODO entry keyword sequences and their interpretation.
2087 \\<org-mode-map>This is a list of sequences.
2089 Each sequence starts with a symbol, either `sequence' or `type',
2090 indicating if the keywords should be interpreted as a sequence of
2091 action steps, or as different types of TODO items. The first
2092 keywords are states requiring action - these states will select a headline
2093 for inclusion into the global TODO list Org-mode produces. If one of
2094 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2095 signify that no further action is necessary. If \"|\" is not found,
2096 the last keyword is treated as the only DONE state of the sequence.
2098 The command \\[org-todo] cycles an entry through these states, and one
2099 additional state where no keyword is present. For details about this
2100 cycling, see the manual.
2102 TODO keywords and interpretation can also be set on a per-file basis with
2103 the special #+SEQ_TODO and #+TYP_TODO lines.
2105 Each keyword can optionally specify a letter for fast state selection
2106 \(in combination with the variable `org-use-fast-todo-selection')
2107 and specifiers for state change logging, using the same syntax that
2108 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2109 the WAIT state can be selected with the \"w\" letter. \"WAIT(w!)\"
2110 indicates to record a time stamp each time this state is selected.
2112 Each keyword may also specify if a timestamp or a note should be
2113 recorded when entering or leaving the state, by adding additional
2114 characters in the parenthesis after the keyword. This looks like this:
2115 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2116 record only the time of the state change. With X and Y being either
2117 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2118 Y when leaving the state if and only if the *target* state does not
2119 define X. You may omit any of the fast-selection key or X or /Y,
2120 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2122 For backward compatibility, this variable may also be just a list
2123 of keywords. In this case the interpretation (sequence or type) will be
2124 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2125 :group 'org-todo
2126 :group 'org-keywords
2127 :type '(choice
2128 (repeat :tag "Old syntax, just keywords"
2129 (string :tag "Keyword"))
2130 (repeat :tag "New syntax"
2131 (cons
2132 (choice
2133 :tag "Interpretation"
2134 ;;Quick and dirty way to see
2135 ;;`org-todo-interpretations'. This takes the
2136 ;;place of item arguments
2137 :convert-widget
2138 (lambda (widget)
2139 (widget-put widget
2140 :args (mapcar
2141 #'(lambda (x)
2142 (widget-convert
2143 (cons 'const x)))
2144 org-todo-interpretation-widgets))
2145 widget))
2146 (repeat
2147 (string :tag "Keyword"))))))
2149 (defvar org-todo-keywords-1 nil
2150 "All TODO and DONE keywords active in a buffer.")
2151 (make-variable-buffer-local 'org-todo-keywords-1)
2152 (defvar org-todo-keywords-for-agenda nil)
2153 (defvar org-done-keywords-for-agenda nil)
2154 (defvar org-drawers-for-agenda nil)
2155 (defvar org-todo-keyword-alist-for-agenda nil)
2156 (defvar org-tag-alist-for-agenda nil)
2157 (defvar org-agenda-contributing-files nil)
2158 (defvar org-not-done-keywords nil)
2159 (make-variable-buffer-local 'org-not-done-keywords)
2160 (defvar org-done-keywords nil)
2161 (make-variable-buffer-local 'org-done-keywords)
2162 (defvar org-todo-heads nil)
2163 (make-variable-buffer-local 'org-todo-heads)
2164 (defvar org-todo-sets nil)
2165 (make-variable-buffer-local 'org-todo-sets)
2166 (defvar org-todo-log-states nil)
2167 (make-variable-buffer-local 'org-todo-log-states)
2168 (defvar org-todo-kwd-alist nil)
2169 (make-variable-buffer-local 'org-todo-kwd-alist)
2170 (defvar org-todo-key-alist nil)
2171 (make-variable-buffer-local 'org-todo-key-alist)
2172 (defvar org-todo-key-trigger nil)
2173 (make-variable-buffer-local 'org-todo-key-trigger)
2175 (defcustom org-todo-interpretation 'sequence
2176 "Controls how TODO keywords are interpreted.
2177 This variable is in principle obsolete and is only used for
2178 backward compatibility, if the interpretation of todo keywords is
2179 not given already in `org-todo-keywords'. See that variable for
2180 more information."
2181 :group 'org-todo
2182 :group 'org-keywords
2183 :type '(choice (const sequence)
2184 (const type)))
2186 (defcustom org-use-fast-todo-selection t
2187 "Non-nil means use the fast todo selection scheme with C-c C-t.
2188 This variable describes if and under what circumstances the cycling
2189 mechanism for TODO keywords will be replaced by a single-key, direct
2190 selection scheme.
2192 When nil, fast selection is never used.
2194 When the symbol `prefix', it will be used when `org-todo' is called
2195 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2196 `C-u t' in an agenda buffer.
2198 When t, fast selection is used by default. In this case, the prefix
2199 argument forces cycling instead.
2201 In all cases, the special interface is only used if access keys have
2202 actually been assigned by the user, i.e. if keywords in the configuration
2203 are followed by a letter in parenthesis, like TODO(t)."
2204 :group 'org-todo
2205 :type '(choice
2206 (const :tag "Never" nil)
2207 (const :tag "By default" t)
2208 (const :tag "Only with C-u C-c C-t" prefix)))
2210 (defcustom org-provide-todo-statistics t
2211 "Non-nil means update todo statistics after insert and toggle.
2212 ALL-HEADLINES means update todo statistics by including headlines
2213 with no TODO keyword as well, counting them as not done.
2214 A list of TODO keywords means the same, but skip keywords that are
2215 not in this list.
2217 When this is set, todo statistics is updated in the parent of the
2218 current entry each time a todo state is changed."
2219 :group 'org-todo
2220 :type '(choice
2221 (const :tag "Yes, only for TODO entries" t)
2222 (const :tag "Yes, including all entries" 'all-headlines)
2223 (repeat :tag "Yes, for TODOs in this list"
2224 (string :tag "TODO keyword"))
2225 (other :tag "No TODO statistics" nil)))
2227 (defcustom org-hierarchical-todo-statistics t
2228 "Non-nil means TODO statistics covers just direct children.
2229 When nil, all entries in the subtree are considered.
2230 This has only an effect if `org-provide-todo-statistics' is set.
2231 To set this to nil for only a single subtree, use a COOKIE_DATA
2232 property and include the word \"recursive\" into the value."
2233 :group 'org-todo
2234 :type 'boolean)
2236 (defcustom org-after-todo-state-change-hook nil
2237 "Hook which is run after the state of a TODO item was changed.
2238 The new state (a string with a TODO keyword, or nil) is available in the
2239 Lisp variable `org-state'."
2240 :group 'org-todo
2241 :type 'hook)
2243 (defvar org-blocker-hook nil
2244 "Hook for functions that are allowed to block a state change.
2246 Each function gets as its single argument a property list, see
2247 `org-trigger-hook' for more information about this list.
2249 If any of the functions in this hook returns nil, the state change
2250 is blocked.")
2252 (defvar org-trigger-hook nil
2253 "Hook for functions that are triggered by a state change.
2255 Each function gets as its single argument a property list with at least
2256 the following elements:
2258 (:type type-of-change :position pos-at-entry-start
2259 :from old-state :to new-state)
2261 Depending on the type, more properties may be present.
2263 This mechanism is currently implemented for:
2265 TODO state changes
2266 ------------------
2267 :type todo-state-change
2268 :from previous state (keyword as a string), or nil, or a symbol
2269 'todo' or 'done', to indicate the general type of state.
2270 :to new state, like in :from")
2272 (defcustom org-enforce-todo-dependencies nil
2273 "Non-nil means undone TODO entries will block switching the parent to DONE.
2274 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2275 be blocked if any prior sibling is not yet done.
2276 Finally, if the parent is blocked because of ordered siblings of its own,
2277 the child will also be blocked."
2278 :set (lambda (var val)
2279 (set var val)
2280 (if val
2281 (add-hook 'org-blocker-hook
2282 'org-block-todo-from-children-or-siblings-or-parent)
2283 (remove-hook 'org-blocker-hook
2284 'org-block-todo-from-children-or-siblings-or-parent)))
2285 :group 'org-todo
2286 :type 'boolean)
2288 (defcustom org-enforce-todo-checkbox-dependencies nil
2289 "Non-nil means unchecked boxes will block switching the parent to DONE.
2290 When this is nil, checkboxes have no influence on switching TODO states.
2291 When non-nil, you first need to check off all check boxes before the TODO
2292 entry can be switched to DONE.
2293 This variable needs to be set before org.el is loaded, and you need to
2294 restart Emacs after a change to make the change effective. The only way
2295 to change is while Emacs is running is through the customize interface."
2296 :set (lambda (var val)
2297 (set var val)
2298 (if val
2299 (add-hook 'org-blocker-hook
2300 'org-block-todo-from-checkboxes)
2301 (remove-hook 'org-blocker-hook
2302 'org-block-todo-from-checkboxes)))
2303 :group 'org-todo
2304 :type 'boolean)
2306 (defcustom org-treat-insert-todo-heading-as-state-change nil
2307 "Non-nil means inserting a TODO heading is treated as state change.
2308 So when the command \\[org-insert-todo-heading] is used, state change
2309 logging will apply if appropriate. When nil, the new TODO item will
2310 be inserted directly, and no logging will take place."
2311 :group 'org-todo
2312 :type 'boolean)
2314 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2315 "Non-nil means switching TODO states with S-cursor counts as state change.
2316 This is the default behavior. However, setting this to nil allows a
2317 convenient way to select a TODO state and bypass any logging associated
2318 with that."
2319 :group 'org-todo
2320 :type 'boolean)
2322 (defcustom org-todo-state-tags-triggers nil
2323 "Tag changes that should be triggered by TODO state changes.
2324 This is a list. Each entry is
2326 (state-change (tag . flag) .......)
2328 State-change can be a string with a state, and empty string to indicate the
2329 state that has no TODO keyword, or it can be one of the symbols `todo'
2330 or `done', meaning any not-done or done state, respectively."
2331 :group 'org-todo
2332 :group 'org-tags
2333 :type '(repeat
2334 (cons (choice :tag "When changing to"
2335 (const :tag "Not-done state" todo)
2336 (const :tag "Done state" done)
2337 (string :tag "State"))
2338 (repeat
2339 (cons :tag "Tag action"
2340 (string :tag "Tag")
2341 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2343 (defcustom org-log-done nil
2344 "Information to record when a task moves to the DONE state.
2346 Possible values are:
2348 nil Don't add anything, just change the keyword
2349 time Add a time stamp to the task
2350 note Prompt for a note and add it with template `org-log-note-headings'
2352 This option can also be set with on a per-file-basis with
2354 #+STARTUP: nologdone
2355 #+STARTUP: logdone
2356 #+STARTUP: lognotedone
2358 You can have local logging settings for a subtree by setting the LOGGING
2359 property to one or more of these keywords."
2360 :group 'org-todo
2361 :group 'org-progress
2362 :type '(choice
2363 (const :tag "No logging" nil)
2364 (const :tag "Record CLOSED timestamp" time)
2365 (const :tag "Record CLOSED timestamp with note." note)))
2367 ;; Normalize old uses of org-log-done.
2368 (cond
2369 ((eq org-log-done t) (setq org-log-done 'time))
2370 ((and (listp org-log-done) (memq 'done org-log-done))
2371 (setq org-log-done 'note)))
2373 (defcustom org-log-reschedule nil
2374 "Information to record when the scheduling date of a tasks is modified.
2376 Possible values are:
2378 nil Don't add anything, just change the date
2379 time Add a time stamp to the task
2380 note Prompt for a note and add it with template `org-log-note-headings'
2382 This option can also be set with on a per-file-basis with
2384 #+STARTUP: nologreschedule
2385 #+STARTUP: logreschedule
2386 #+STARTUP: lognotereschedule"
2387 :group 'org-todo
2388 :group 'org-progress
2389 :type '(choice
2390 (const :tag "No logging" nil)
2391 (const :tag "Record timestamp" time)
2392 (const :tag "Record timestamp with note." note)))
2394 (defcustom org-log-redeadline nil
2395 "Information to record when the deadline date of a tasks is modified.
2397 Possible values are:
2399 nil Don't add anything, just change the date
2400 time Add a time stamp to the task
2401 note Prompt for a note and add it with template `org-log-note-headings'
2403 This option can also be set with on a per-file-basis with
2405 #+STARTUP: nologredeadline
2406 #+STARTUP: logredeadline
2407 #+STARTUP: lognoteredeadline
2409 You can have local logging settings for a subtree by setting the LOGGING
2410 property to one or more of these keywords."
2411 :group 'org-todo
2412 :group 'org-progress
2413 :type '(choice
2414 (const :tag "No logging" nil)
2415 (const :tag "Record timestamp" time)
2416 (const :tag "Record timestamp with note." note)))
2418 (defcustom org-log-note-clock-out nil
2419 "Non-nil means record a note when clocking out of an item.
2420 This can also be configured on a per-file basis by adding one of
2421 the following lines anywhere in the buffer:
2423 #+STARTUP: lognoteclock-out
2424 #+STARTUP: nolognoteclock-out"
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type 'boolean)
2429 (defcustom org-log-done-with-time t
2430 "Non-nil means the CLOSED time stamp will contain date and time.
2431 When nil, only the date will be recorded."
2432 :group 'org-progress
2433 :type 'boolean)
2435 (defcustom org-log-note-headings
2436 '((done . "CLOSING NOTE %t")
2437 (state . "State %-12s from %-12S %t")
2438 (note . "Note taken on %t")
2439 (reschedule . "Rescheduled from %S on %t")
2440 (delschedule . "Not scheduled, was %S on %t")
2441 (redeadline . "New deadline from %S on %t")
2442 (deldeadline . "Removed deadline, was %S on %t")
2443 (refile . "Refiled on %t")
2444 (clock-out . ""))
2445 "Headings for notes added to entries.
2446 The value is an alist, with the car being a symbol indicating the note
2447 context, and the cdr is the heading to be used. The heading may also be the
2448 empty string.
2449 %t in the heading will be replaced by a time stamp.
2450 %T will be an active time stamp instead the default inactive one
2451 %d will be replaced by a short-format time stamp.
2452 %D will be replaced by an active short-format time stamp.
2453 %s will be replaced by the new TODO state, in double quotes.
2454 %S will be replaced by the old TODO state, in double quotes.
2455 %u will be replaced by the user name.
2456 %U will be replaced by the full user name.
2458 In fact, it is not a good idea to change the `state' entry, because
2459 agenda log mode depends on the format of these entries."
2460 :group 'org-todo
2461 :group 'org-progress
2462 :type '(list :greedy t
2463 (cons (const :tag "Heading when closing an item" done) string)
2464 (cons (const :tag
2465 "Heading when changing todo state (todo sequence only)"
2466 state) string)
2467 (cons (const :tag "Heading when just taking a note" note) string)
2468 (cons (const :tag "Heading when clocking out" clock-out) string)
2469 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2470 (cons (const :tag "Heading when rescheduling" reschedule) string)
2471 (cons (const :tag "Heading when changing deadline" redeadline) string)
2472 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2473 (cons (const :tag "Heading when refiling" refile) string)))
2475 (unless (assq 'note org-log-note-headings)
2476 (push '(note . "%t") org-log-note-headings))
2478 (defcustom org-log-into-drawer nil
2479 "Non-nil means insert state change notes and time stamps into a drawer.
2480 When nil, state changes notes will be inserted after the headline and
2481 any scheduling and clock lines, but not inside a drawer.
2483 The value of this variable should be the name of the drawer to use.
2484 LOGBOOK is proposed as the default drawer for this purpose, you can
2485 also set this to a string to define the drawer of your choice.
2487 A value of t is also allowed, representing \"LOGBOOK\".
2489 If this variable is set, `org-log-state-notes-insert-after-drawers'
2490 will be ignored.
2492 You can set the property LOG_INTO_DRAWER to overrule this setting for
2493 a subtree."
2494 :group 'org-todo
2495 :group 'org-progress
2496 :type '(choice
2497 (const :tag "Not into a drawer" nil)
2498 (const :tag "LOGBOOK" t)
2499 (string :tag "Other")))
2501 (if (fboundp 'defvaralias)
2502 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2504 (defun org-log-into-drawer ()
2505 "Return the value of `org-log-into-drawer', but let properties overrule.
2506 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2507 used instead of the default value."
2508 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2509 (cond
2510 ((or (not p) (equal p "nil")) org-log-into-drawer)
2511 ((equal p "t") "LOGBOOK")
2512 (t p))))
2514 (defcustom org-log-state-notes-insert-after-drawers nil
2515 "Non-nil means insert state change notes after any drawers in entry.
2516 Only the drawers that *immediately* follow the headline and the
2517 deadline/scheduled line are skipped.
2518 When nil, insert notes right after the heading and perhaps the line
2519 with deadline/scheduling if present.
2521 This variable will have no effect if `org-log-into-drawer' is
2522 set."
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type 'boolean)
2527 (defcustom org-log-states-order-reversed t
2528 "Non-nil means the latest state note will be directly after heading.
2529 When nil, the state change notes will be ordered according to time."
2530 :group 'org-todo
2531 :group 'org-progress
2532 :type 'boolean)
2534 (defcustom org-todo-repeat-to-state nil
2535 "The TODO state to which a repeater should return the repeating task.
2536 By default this is the first task in a TODO sequence, or the previous state
2537 in a TODO_TYP set. But you can specify another task here.
2538 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2539 :group 'org-todo
2540 :version "24.1"
2541 :type '(choice (const :tag "Head of sequence" nil)
2542 (string :tag "Specific state")))
2544 (defcustom org-log-repeat 'time
2545 "Non-nil means record moving through the DONE state when triggering repeat.
2546 An auto-repeating task is immediately switched back to TODO when
2547 marked DONE. If you are not logging state changes (by adding \"@\"
2548 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2549 record a closing note, there will be no record of the task moving
2550 through DONE. This variable forces taking a note anyway.
2552 nil Don't force a record
2553 time Record a time stamp
2554 note Record a note
2556 This option can also be set with on a per-file-basis with
2558 #+STARTUP: logrepeat
2559 #+STARTUP: lognoterepeat
2560 #+STARTUP: nologrepeat
2562 You can have local logging settings for a subtree by setting the LOGGING
2563 property to one or more of these keywords."
2564 :group 'org-todo
2565 :group 'org-progress
2566 :type '(choice
2567 (const :tag "Don't force a record" nil)
2568 (const :tag "Force recording the DONE state" time)
2569 (const :tag "Force recording a note with the DONE state" note)))
2572 (defgroup org-priorities nil
2573 "Priorities in Org-mode."
2574 :tag "Org Priorities"
2575 :group 'org-todo)
2577 (defcustom org-enable-priority-commands t
2578 "Non-nil means priority commands are active.
2579 When nil, these commands will be disabled, so that you never accidentally
2580 set a priority."
2581 :group 'org-priorities
2582 :type 'boolean)
2584 (defcustom org-highest-priority ?A
2585 "The highest priority of TODO items. A character like ?A, ?B etc.
2586 Must have a smaller ASCII number than `org-lowest-priority'."
2587 :group 'org-priorities
2588 :type 'character)
2590 (defcustom org-lowest-priority ?C
2591 "The lowest priority of TODO items. A character like ?A, ?B etc.
2592 Must have a larger ASCII number than `org-highest-priority'."
2593 :group 'org-priorities
2594 :type 'character)
2596 (defcustom org-default-priority ?B
2597 "The default priority of TODO items.
2598 This is the priority an item gets if no explicit priority is given.
2599 When starting to cycle on an empty priority the first step in the cycle
2600 depends on `org-priority-start-cycle-with-default'. The resulting first
2601 step priority must not exceed the range from `org-highest-priority' to
2602 `org-lowest-priority' which means that `org-default-priority' has to be
2603 in this range exclusive or inclusive the range boundaries. Else the
2604 first step refuses to set the default and the second will fall back
2605 to (depending on the command used) the highest or lowest priority."
2606 :group 'org-priorities
2607 :type 'character)
2609 (defcustom org-priority-start-cycle-with-default t
2610 "Non-nil means start with default priority when starting to cycle.
2611 When this is nil, the first step in the cycle will be (depending on the
2612 command used) one higher or lower than the default priority.
2613 See also `org-default-priority'."
2614 :group 'org-priorities
2615 :type 'boolean)
2617 (defcustom org-get-priority-function nil
2618 "Function to extract the priority from a string.
2619 The string is normally the headline. If this is nil Org computes the
2620 priority from the priority cookie like [#A] in the headline. It returns
2621 an integer, increasing by 1000 for each priority level.
2622 The user can set a different function here, which should take a string
2623 as an argument and return the numeric priority."
2624 :group 'org-priorities
2625 :version "24.1"
2626 :type 'function)
2628 (defgroup org-time nil
2629 "Options concerning time stamps and deadlines in Org-mode."
2630 :tag "Org Time"
2631 :group 'org)
2633 (defcustom org-insert-labeled-timestamps-at-point nil
2634 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2635 When nil, these labeled time stamps are forces into the second line of an
2636 entry, just after the headline. When scheduling from the global TODO list,
2637 the time stamp will always be forced into the second line."
2638 :group 'org-time
2639 :type 'boolean)
2641 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2642 "Formats for `format-time-string' which are used for time stamps.
2643 It is not recommended to change this constant.")
2645 (defcustom org-time-stamp-rounding-minutes '(0 5)
2646 "Number of minutes to round time stamps to.
2647 These are two values, the first applies when first creating a time stamp.
2648 The second applies when changing it with the commands `S-up' and `S-down'.
2649 When changing the time stamp, this means that it will change in steps
2650 of N minutes, as given by the second value.
2652 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2653 numbers should be factors of 60, so for example 5, 10, 15.
2655 When this is larger than 1, you can still force an exact time stamp by using
2656 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2657 and by using a prefix arg to `S-up/down' to specify the exact number
2658 of minutes to shift."
2659 :group 'org-time
2660 :get #'(lambda (var) ; Make sure both elements are there
2661 (if (integerp (default-value var))
2662 (list (default-value var) 5)
2663 (default-value var)))
2664 :type '(list
2665 (integer :tag "when inserting times")
2666 (integer :tag "when modifying times")))
2668 ;; Normalize old customizations of this variable.
2669 (when (integerp org-time-stamp-rounding-minutes)
2670 (setq org-time-stamp-rounding-minutes
2671 (list org-time-stamp-rounding-minutes
2672 org-time-stamp-rounding-minutes)))
2674 (defcustom org-display-custom-times nil
2675 "Non-nil means overlay custom formats over all time stamps.
2676 The formats are defined through the variable `org-time-stamp-custom-formats'.
2677 To turn this on on a per-file basis, insert anywhere in the file:
2678 #+STARTUP: customtime"
2679 :group 'org-time
2680 :set 'set-default
2681 :type 'sexp)
2682 (make-variable-buffer-local 'org-display-custom-times)
2684 (defcustom org-time-stamp-custom-formats
2685 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2686 "Custom formats for time stamps. See `format-time-string' for the syntax.
2687 These are overlaid over the default ISO format if the variable
2688 `org-display-custom-times' is set. Time like %H:%M should be at the
2689 end of the second format. The custom formats are also honored by export
2690 commands, if custom time display is turned on at the time of export."
2691 :group 'org-time
2692 :type 'sexp)
2694 (defun org-time-stamp-format (&optional long inactive)
2695 "Get the right format for a time string."
2696 (let ((f (if long (cdr org-time-stamp-formats)
2697 (car org-time-stamp-formats))))
2698 (if inactive
2699 (concat "[" (substring f 1 -1) "]")
2700 f)))
2702 (defcustom org-time-clocksum-format "%d:%02d"
2703 "The format string used when creating CLOCKSUM lines.
2704 This is also used when org-mode generates a time duration."
2705 :group 'org-time
2706 :type 'string)
2708 (defcustom org-time-clocksum-use-fractional nil
2709 "If non-nil, \\[org-clock-display] uses fractional times.
2710 org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'boolean)
2714 (defcustom org-time-clocksum-fractional-format "%.2f"
2715 "The format string used when creating CLOCKSUM lines, or when
2716 org-mode generates a time duration."
2717 :group 'org-time
2718 :type 'string)
2720 (defcustom org-deadline-warning-days 14
2721 "No. of days before expiration during which a deadline becomes active.
2722 This variable governs the display in sparse trees and in the agenda.
2723 When 0 or negative, it means use this number (the absolute value of it)
2724 even if a deadline has a different individual lead time specified.
2726 Custom commands can set this variable in the options section."
2727 :group 'org-time
2728 :group 'org-agenda-daily/weekly
2729 :type 'integer)
2731 (defcustom org-read-date-prefer-future t
2732 "Non-nil means assume future for incomplete date input from user.
2733 This affects the following situations:
2734 1. The user gives a month but not a year.
2735 For example, if it is April and you enter \"feb 2\", this will be read
2736 as Feb 2, *next* year. \"May 5\", however, will be this year.
2737 2. The user gives a day, but no month.
2738 For example, if today is the 15th, and you enter \"3\", Org-mode will
2739 read this as the third of *next* month. However, if you enter \"17\",
2740 it will be considered as *this* month.
2742 If you set this variable to the symbol `time', then also the following
2743 will work:
2745 3. If the user gives a time, but no day. If the time is before now,
2746 to will be interpreted as tomorrow.
2748 Currently none of this works for ISO week specifications.
2750 When this option is nil, the current day, month and year will always be
2751 used as defaults.
2753 See also `org-agenda-jump-prefer-future'."
2754 :group 'org-time
2755 :type '(choice
2756 (const :tag "Never" nil)
2757 (const :tag "Check month and day" t)
2758 (const :tag "Check month, day, and time" time)))
2760 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2761 "Should the agenda jump command prefer the future for incomplete dates?
2762 The default is to do the same as configured in `org-read-date-prefer-future'.
2763 But you can also set a deviating value here.
2764 This may t or nil, or the symbol `org-read-date-prefer-future'."
2765 :group 'org-agenda
2766 :group 'org-time
2767 :version "24.1"
2768 :type '(choice
2769 (const :tag "Use org-read-date-prefer-future"
2770 org-read-date-prefer-future)
2771 (const :tag "Never" nil)
2772 (const :tag "Always" t)))
2774 (defcustom org-read-date-force-compatible-dates t
2775 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2777 Depending on the system Emacs is running on, certain dates cannot
2778 be represented with the type used internally to represent time.
2779 Dates between 1970-1-1 and 2038-1-1 can always be represented
2780 correctly. Some systems allow for earlier dates, some for later,
2781 some for both. One way to find out it to insert any date into an
2782 Org buffer, putting the cursor on the year and hitting S-up and
2783 S-down to test the range.
2785 When this variable is set to t, the date/time prompt will not let
2786 you specify dates outside the 1970-2037 range, so it is certain that
2787 these dates will work in whatever version of Emacs you are
2788 running, and also that you can move a file from one Emacs implementation
2789 to another. WHenever Org is forcing the year for you, it will display
2790 a message and beep.
2792 When this variable is nil, Org will check if the date is
2793 representable in the specific Emacs implementation you are using.
2794 If not, it will force a year, usually the current year, and beep
2795 to remind you. Currently this setting is not recommended because
2796 the likelihood that you will open your Org files in an Emacs that
2797 has limited date range is not negligible.
2799 A workaround for this problem is to use diary sexp dates for time
2800 stamps outside of this range."
2801 :group 'org-time
2802 :version "24.1"
2803 :type 'boolean)
2805 (defcustom org-read-date-display-live t
2806 "Non-nil means display current interpretation of date prompt live.
2807 This display will be in an overlay, in the minibuffer."
2808 :group 'org-time
2809 :type 'boolean)
2811 (defcustom org-read-date-popup-calendar t
2812 "Non-nil means pop up a calendar when prompting for a date.
2813 In the calendar, the date can be selected with mouse-1. However, the
2814 minibuffer will also be active, and you can simply enter the date as well.
2815 When nil, only the minibuffer will be available."
2816 :group 'org-time
2817 :type 'boolean)
2818 (if (fboundp 'defvaralias)
2819 (defvaralias 'org-popup-calendar-for-date-prompt
2820 'org-read-date-popup-calendar))
2822 (defcustom org-read-date-minibuffer-setup-hook nil
2823 "Hook to be used to set up keys for the date/time interface.
2824 Add key definitions to `minibuffer-local-map', which will be a temporary
2825 copy."
2826 :group 'org-time
2827 :type 'hook)
2829 (defcustom org-extend-today-until 0
2830 "The hour when your day really ends. Must be an integer.
2831 This has influence for the following applications:
2832 - When switching the agenda to \"today\". It it is still earlier than
2833 the time given here, the day recognized as TODAY is actually yesterday.
2834 - When a date is read from the user and it is still before the time given
2835 here, the current date and time will be assumed to be yesterday, 23:59.
2836 Also, timestamps inserted in remember templates follow this rule.
2838 IMPORTANT: This is a feature whose implementation is and likely will
2839 remain incomplete. Really, it is only here because past midnight seems to
2840 be the favorite working time of John Wiegley :-)"
2841 :group 'org-time
2842 :type 'integer)
2844 (defcustom org-use-effective-time nil
2845 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2846 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2847 \"effective time\" of any timestamps between midnight and 8am will be
2848 23:59 of the previous day."
2849 :group 'org-time
2850 :version "24.1"
2851 :type 'boolean)
2853 (defcustom org-edit-timestamp-down-means-later nil
2854 "Non-nil means S-down will increase the time in a time stamp.
2855 When nil, S-up will increase."
2856 :group 'org-time
2857 :type 'boolean)
2859 (defcustom org-calendar-follow-timestamp-change t
2860 "Non-nil means make the calendar window follow timestamp changes.
2861 When a timestamp is modified and the calendar window is visible, it will be
2862 moved to the new date."
2863 :group 'org-time
2864 :type 'boolean)
2866 (defgroup org-tags nil
2867 "Options concerning tags in Org-mode."
2868 :tag "Org Tags"
2869 :group 'org)
2871 (defcustom org-tag-alist nil
2872 "List of tags allowed in Org-mode files.
2873 When this list is nil, Org-mode will base TAG input on what is already in the
2874 buffer.
2875 The value of this variable is an alist, the car of each entry must be a
2876 keyword as a string, the cdr may be a character that is used to select
2877 that tag through the fast-tag-selection interface.
2878 See the manual for details."
2879 :group 'org-tags
2880 :type '(repeat
2881 (choice
2882 (cons (string :tag "Tag name")
2883 (character :tag "Access char"))
2884 (list :tag "Start radio group"
2885 (const :startgroup)
2886 (option (string :tag "Group description")))
2887 (list :tag "End radio group"
2888 (const :endgroup)
2889 (option (string :tag "Group description")))
2890 (const :tag "New line" (:newline)))))
2892 (defcustom org-tag-persistent-alist nil
2893 "List of tags that will always appear in all Org-mode files.
2894 This is in addition to any in buffer settings or customizations
2895 of `org-tag-alist'.
2896 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2897 The value of this variable is an alist, the car of each entry must be a
2898 keyword as a string, the cdr may be a character that is used to select
2899 that tag through the fast-tag-selection interface.
2900 See the manual for details.
2901 To disable these tags on a per-file basis, insert anywhere in the file:
2902 #+STARTUP: noptag"
2903 :group 'org-tags
2904 :type '(repeat
2905 (choice
2906 (cons (string :tag "Tag name")
2907 (character :tag "Access char"))
2908 (const :tag "Start radio group" (:startgroup))
2909 (const :tag "End radio group" (:endgroup))
2910 (const :tag "New line" (:newline)))))
2912 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2913 "If non-nil, always offer completion for all tags of all agenda files.
2914 Instead of customizing this variable directly, you might want to
2915 set it locally for capture buffers, because there no list of
2916 tags in that file can be created dynamically (there are none).
2918 (add-hook 'org-capture-mode-hook
2919 (lambda ()
2920 (set (make-local-variable
2921 'org-complete-tags-always-offer-all-agenda-tags)
2922 t)))"
2923 :group 'org-tags
2924 :version "24.1"
2925 :type 'boolean)
2927 (defvar org-file-tags nil
2928 "List of tags that can be inherited by all entries in the file.
2929 The tags will be inherited if the variable `org-use-tag-inheritance'
2930 says they should be.
2931 This variable is populated from #+FILETAGS lines.")
2933 (defcustom org-use-fast-tag-selection 'auto
2934 "Non-nil means use fast tag selection scheme.
2935 This is a special interface to select and deselect tags with single keys.
2936 When nil, fast selection is never used.
2937 When the symbol `auto', fast selection is used if and only if selection
2938 characters for tags have been configured, either through the variable
2939 `org-tag-alist' or through a #+TAGS line in the buffer.
2940 When t, fast selection is always used and selection keys are assigned
2941 automatically if necessary."
2942 :group 'org-tags
2943 :type '(choice
2944 (const :tag "Always" t)
2945 (const :tag "Never" nil)
2946 (const :tag "When selection characters are configured" 'auto)))
2948 (defcustom org-fast-tag-selection-single-key nil
2949 "Non-nil means fast tag selection exits after first change.
2950 When nil, you have to press RET to exit it.
2951 During fast tag selection, you can toggle this flag with `C-c'.
2952 This variable can also have the value `expert'. In this case, the window
2953 displaying the tags menu is not even shown, until you press C-c again."
2954 :group 'org-tags
2955 :type '(choice
2956 (const :tag "No" nil)
2957 (const :tag "Yes" t)
2958 (const :tag "Expert" expert)))
2960 (defvar org-fast-tag-selection-include-todo nil
2961 "Non-nil means fast tags selection interface will also offer TODO states.
2962 This is an undocumented feature, you should not rely on it.")
2964 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2965 "The column to which tags should be indented in a headline.
2966 If this number is positive, it specifies the column. If it is negative,
2967 it means that the tags should be flushright to that column. For example,
2968 -80 works well for a normal 80 character screen.
2969 When 0, place tags directly after headline text, with only one space in
2970 between."
2971 :group 'org-tags
2972 :type 'integer)
2974 (defcustom org-auto-align-tags t
2975 "Non-nil keeps tags aligned when modifying headlines.
2976 Some operations (i.e. demoting) change the length of a headline and
2977 therefore shift the tags around. With this option turned on, after
2978 each such operation the tags are again aligned to `org-tags-column'."
2979 :group 'org-tags
2980 :type 'boolean)
2982 (defcustom org-use-tag-inheritance t
2983 "Non-nil means tags in levels apply also for sublevels.
2984 When nil, only the tags directly given in a specific line apply there.
2985 This may also be a list of tags that should be inherited, or a regexp that
2986 matches tags that should be inherited. Additional control is possible
2987 with the variable `org-tags-exclude-from-inheritance' which gives an
2988 explicit list of tags to be excluded from inheritance., even if the value of
2989 `org-use-tag-inheritance' would select it for inheritance.
2991 If this option is t, a match early-on in a tree can lead to a large
2992 number of matches in the subtree when constructing the agenda or creating
2993 a sparse tree. If you only want to see the first match in a tree during
2994 a search, check out the variable `org-tags-match-list-sublevels'."
2995 :group 'org-tags
2996 :type '(choice
2997 (const :tag "Not" nil)
2998 (const :tag "Always" t)
2999 (repeat :tag "Specific tags" (string :tag "Tag"))
3000 (regexp :tag "Tags matched by regexp")))
3002 (defcustom org-tags-exclude-from-inheritance nil
3003 "List of tags that should never be inherited.
3004 This is a way to exclude a few tags from inheritance. For way to do
3005 the opposite, to actively allow inheritance for selected tags,
3006 see the variable `org-use-tag-inheritance'."
3007 :group 'org-tags
3008 :type '(repeat (string :tag "Tag")))
3010 (defun org-tag-inherit-p (tag)
3011 "Check if TAG is one that should be inherited."
3012 (cond
3013 ((member tag org-tags-exclude-from-inheritance) nil)
3014 ((eq org-use-tag-inheritance t) t)
3015 ((not org-use-tag-inheritance) nil)
3016 ((stringp org-use-tag-inheritance)
3017 (string-match org-use-tag-inheritance tag))
3018 ((listp org-use-tag-inheritance)
3019 (member tag org-use-tag-inheritance))
3020 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3022 (defcustom org-tags-match-list-sublevels t
3023 "Non-nil means list also sublevels of headlines matching a search.
3024 This variable applies to tags/property searches, and also to stuck
3025 projects because this search is based on a tags match as well.
3027 When set to the symbol `indented', sublevels are indented with
3028 leading dots.
3030 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3031 the sublevels of a headline matching a tag search often also match
3032 the same search. Listing all of them can create very long lists.
3033 Setting this variable to nil causes subtrees of a match to be skipped.
3035 This variable is semi-obsolete and probably should always be true. It
3036 is better to limit inheritance to certain tags using the variables
3037 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3038 :group 'org-tags
3039 :type '(choice
3040 (const :tag "No, don't list them" nil)
3041 (const :tag "Yes, do list them" t)
3042 (const :tag "List them, indented with leading dots" indented)))
3044 (defcustom org-tags-sort-function nil
3045 "When set, tags are sorted using this function as a comparator."
3046 :group 'org-tags
3047 :type '(choice
3048 (const :tag "No sorting" nil)
3049 (const :tag "Alphabetical" string<)
3050 (const :tag "Reverse alphabetical" string>)
3051 (function :tag "Custom function" nil)))
3053 (defvar org-tags-history nil
3054 "History of minibuffer reads for tags.")
3055 (defvar org-last-tags-completion-table nil
3056 "The last used completion table for tags.")
3057 (defvar org-after-tags-change-hook nil
3058 "Hook that is run after the tags in a line have changed.")
3060 (defgroup org-properties nil
3061 "Options concerning properties in Org-mode."
3062 :tag "Org Properties"
3063 :group 'org)
3065 (defcustom org-property-format "%-10s %s"
3066 "How property key/value pairs should be formatted by `indent-line'.
3067 When `indent-line' hits a property definition, it will format the line
3068 according to this format, mainly to make sure that the values are
3069 lined-up with respect to each other."
3070 :group 'org-properties
3071 :type 'string)
3073 (defcustom org-properties-postprocess-alist nil
3074 "Alist of properties and functions to adjust inserted values.
3075 Elements of this alist must be of the form
3077 ([string] [function])
3079 where [string] must be a property name and [function] must be a
3080 lambda expression: this lambda expression must take one argument,
3081 the value to adjust, and return the new value as a string.
3083 For example, this element will allow the property \"Remaining\"
3084 to be updated wrt the relation between the \"Effort\" property
3085 and the clock summary:
3087 ((\"Remaining\" (lambda(value)
3088 (let ((clocksum (org-clock-sum-current-item))
3089 (effort (org-duration-string-to-minutes
3090 (org-entry-get (point) \"Effort\"))))
3091 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3092 :group 'org-properties
3093 :version "24.1"
3094 :type '(alist :key-type (string :tag "Property")
3095 :value-type (function :tag "Function")))
3097 (defcustom org-use-property-inheritance nil
3098 "Non-nil means properties apply also for sublevels.
3100 This setting is chiefly used during property searches. Turning it on can
3101 cause significant overhead when doing a search, which is why it is not
3102 on by default.
3104 When nil, only the properties directly given in the current entry count.
3105 When t, every property is inherited. The value may also be a list of
3106 properties that should have inheritance, or a regular expression matching
3107 properties that should be inherited.
3109 However, note that some special properties use inheritance under special
3110 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3111 and the properties ending in \"_ALL\" when they are used as descriptor
3112 for valid values of a property.
3114 Note for programmers:
3115 When querying an entry with `org-entry-get', you can control if inheritance
3116 should be used. By default, `org-entry-get' looks only at the local
3117 properties. You can request inheritance by setting the inherit argument
3118 to t (to force inheritance) or to `selective' (to respect the setting
3119 in this variable)."
3120 :group 'org-properties
3121 :type '(choice
3122 (const :tag "Not" nil)
3123 (const :tag "Always" t)
3124 (repeat :tag "Specific properties" (string :tag "Property"))
3125 (regexp :tag "Properties matched by regexp")))
3127 (defun org-property-inherit-p (property)
3128 "Check if PROPERTY is one that should be inherited."
3129 (cond
3130 ((eq org-use-property-inheritance t) t)
3131 ((not org-use-property-inheritance) nil)
3132 ((stringp org-use-property-inheritance)
3133 (string-match org-use-property-inheritance property))
3134 ((listp org-use-property-inheritance)
3135 (member property org-use-property-inheritance))
3136 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3138 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3139 "The default column format, if no other format has been defined.
3140 This variable can be set on the per-file basis by inserting a line
3142 #+COLUMNS: %25ITEM ....."
3143 :group 'org-properties
3144 :type 'string)
3146 (defcustom org-columns-ellipses ".."
3147 "The ellipses to be used when a field in column view is truncated.
3148 When this is the empty string, as many characters as possible are shown,
3149 but then there will be no visual indication that the field has been truncated.
3150 When this is a string of length N, the last N characters of a truncated
3151 field are replaced by this string. If the column is narrower than the
3152 ellipses string, only part of the ellipses string will be shown."
3153 :group 'org-properties
3154 :type 'string)
3156 (defcustom org-columns-modify-value-for-display-function nil
3157 "Function that modifies values for display in column view.
3158 For example, it can be used to cut out a certain part from a time stamp.
3159 The function must take 2 arguments:
3161 column-title The title of the column (*not* the property name)
3162 value The value that should be modified.
3164 The function should return the value that should be displayed,
3165 or nil if the normal value should be used."
3166 :group 'org-properties
3167 :type 'function)
3169 (defcustom org-effort-property "Effort"
3170 "The property that is being used to keep track of effort estimates.
3171 Effort estimates given in this property need to have the format H:MM."
3172 :group 'org-properties
3173 :group 'org-progress
3174 :type '(string :tag "Property"))
3176 (defconst org-global-properties-fixed
3177 '(("VISIBILITY_ALL" . "folded children content all")
3178 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3179 "List of property/value pairs that can be inherited by any entry.
3181 These are fixed values, for the preset properties. The user variable
3182 that can be used to add to this list is `org-global-properties'.
3184 The entries in this list are cons cells where the car is a property
3185 name and cdr is a string with the value. If the value represents
3186 multiple items like an \"_ALL\" property, separate the items by
3187 spaces.")
3189 (defcustom org-global-properties nil
3190 "List of property/value pairs that can be inherited by any entry.
3192 This list will be combined with the constant `org-global-properties-fixed'.
3194 The entries in this list are cons cells where the car is a property
3195 name and cdr is a string with the value.
3197 You can set buffer-local values for the same purpose in the variable
3198 `org-file-properties' this by adding lines like
3200 #+PROPERTY: NAME VALUE"
3201 :group 'org-properties
3202 :type '(repeat
3203 (cons (string :tag "Property")
3204 (string :tag "Value"))))
3206 (defvar org-file-properties nil
3207 "List of property/value pairs that can be inherited by any entry.
3208 Valid for the current buffer.
3209 This variable is populated from #+PROPERTY lines.")
3210 (make-variable-buffer-local 'org-file-properties)
3212 (defgroup org-agenda nil
3213 "Options concerning agenda views in Org-mode."
3214 :tag "Org Agenda"
3215 :group 'org)
3217 (defvar org-category nil
3218 "Variable used by org files to set a category for agenda display.
3219 Such files should use a file variable to set it, for example
3221 # -*- mode: org; org-category: \"ELisp\"
3223 or contain a special line
3225 #+CATEGORY: ELisp
3227 If the file does not specify a category, then file's base name
3228 is used instead.")
3229 (make-variable-buffer-local 'org-category)
3230 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3232 (defcustom org-agenda-files nil
3233 "The files to be used for agenda display.
3234 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3235 \\[org-remove-file]. You can also use customize to edit the list.
3237 If an entry is a directory, all files in that directory that are matched by
3238 `org-agenda-file-regexp' will be part of the file list.
3240 If the value of the variable is not a list but a single file name, then
3241 the list of agenda files is actually stored and maintained in that file, one
3242 agenda file per line. In this file paths can be given relative to
3243 `org-directory'. Tilde expansion and environment variable substitution
3244 are also made."
3245 :group 'org-agenda
3246 :type '(choice
3247 (repeat :tag "List of files and directories" file)
3248 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3250 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3251 "Regular expression to match files for `org-agenda-files'.
3252 If any element in the list in that variable contains a directory instead
3253 of a normal file, all files in that directory that are matched by this
3254 regular expression will be included."
3255 :group 'org-agenda
3256 :type 'regexp)
3258 (defcustom org-agenda-text-search-extra-files nil
3259 "List of extra files to be searched by text search commands.
3260 These files will be search in addition to the agenda files by the
3261 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3262 Note that these files will only be searched for text search commands,
3263 not for the other agenda views like todo lists, tag searches or the weekly
3264 agenda. This variable is intended to list notes and possibly archive files
3265 that should also be searched by these two commands.
3266 In fact, if the first element in the list is the symbol `agenda-archives',
3267 than all archive files of all agenda files will be added to the search
3268 scope."
3269 :group 'org-agenda
3270 :type '(set :greedy t
3271 (const :tag "Agenda Archives" agenda-archives)
3272 (repeat :inline t (file))))
3274 (if (fboundp 'defvaralias)
3275 (defvaralias 'org-agenda-multi-occur-extra-files
3276 'org-agenda-text-search-extra-files))
3278 (defcustom org-agenda-skip-unavailable-files nil
3279 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3280 A nil value means to remove them, after a query, from the list."
3281 :group 'org-agenda
3282 :type 'boolean)
3284 (defcustom org-calendar-to-agenda-key [?c]
3285 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3286 The command `org-calendar-goto-agenda' will be bound to this key. The
3287 default is the character `c' because then `c' can be used to switch back and
3288 forth between agenda and calendar."
3289 :group 'org-agenda
3290 :type 'sexp)
3292 (defcustom org-calendar-agenda-action-key [?k]
3293 "The key to be installed in `calendar-mode-map' for agenda-action.
3294 The command `org-agenda-action' will be bound to this key. The
3295 default is the character `k' because we use the same key in the agenda."
3296 :group 'org-agenda
3297 :type 'sexp)
3299 (defcustom org-calendar-insert-diary-entry-key [?i]
3300 "The key to be installed in `calendar-mode-map' for adding diary entries.
3301 This option is irrelevant until `org-agenda-diary-file' has been configured
3302 to point to an Org-mode file. When that is the case, the command
3303 `org-agenda-diary-entry' will be bound to the key given here, by default
3304 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3305 if you want to continue doing this, you need to change this to a different
3306 key."
3307 :group 'org-agenda
3308 :type 'sexp)
3310 (defcustom org-agenda-diary-file 'diary-file
3311 "File to which to add new entries with the `i' key in agenda and calendar.
3312 When this is the symbol `diary-file', the functionality in the Emacs
3313 calendar will be used to add entries to the `diary-file'. But when this
3314 points to a file, `org-agenda-diary-entry' will be used instead."
3315 :group 'org-agenda
3316 :type '(choice
3317 (const :tag "The standard Emacs diary file" diary-file)
3318 (file :tag "Special Org file diary entries")))
3320 (eval-after-load "calendar"
3321 '(progn
3322 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3323 'org-calendar-goto-agenda)
3324 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3325 'org-agenda-action)
3326 (add-hook 'calendar-mode-hook
3327 (lambda ()
3328 (unless (eq org-agenda-diary-file 'diary-file)
3329 (define-key calendar-mode-map
3330 org-calendar-insert-diary-entry-key
3331 'org-agenda-diary-entry))))))
3333 (defgroup org-latex nil
3334 "Options for embedding LaTeX code into Org-mode."
3335 :tag "Org LaTeX"
3336 :group 'org)
3338 (defcustom org-format-latex-options
3339 '(:foreground default :background default :scale 1.0
3340 :html-foreground "Black" :html-background "Transparent"
3341 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3342 "Options for creating images from LaTeX fragments.
3343 This is a property list with the following properties:
3344 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3345 `default' means use the foreground of the default face.
3346 :background the background color, or \"Transparent\".
3347 `default' means use the background of the default face.
3348 :scale a scaling factor for the size of the images, to get more pixels
3349 :html-foreground, :html-background, :html-scale
3350 the same numbers for HTML export.
3351 :matchers a list indicating which matchers should be used to
3352 find LaTeX fragments. Valid members of this list are:
3353 \"begin\" find environments
3354 \"$1\" find single characters surrounded by $.$
3355 \"$\" find math expressions surrounded by $...$
3356 \"$$\" find math expressions surrounded by $$....$$
3357 \"\\(\" find math expressions surrounded by \\(...\\)
3358 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3359 :group 'org-latex
3360 :type 'plist)
3362 (defcustom org-format-latex-signal-error t
3363 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3364 When nil, just push out a message."
3365 :group 'org-latex
3366 :version "24.1"
3367 :type 'boolean)
3369 (defcustom org-latex-to-mathml-jar-file nil
3370 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3371 Use this to specify additional executable file say a jar file.
3373 When using MathToWeb as the converter, specify the full-path to
3374 your mathtoweb.jar file."
3375 :group 'org-latex
3376 :version "24.1"
3377 :type '(choice
3378 (const :tag "None" nil)
3379 (file :tag "JAR file" :must-match t)))
3381 (defcustom org-latex-to-mathml-convert-command nil
3382 "Command to convert LaTeX fragments to MathML.
3383 Replace format-specifiers in the command as noted below and use
3384 `shell-command' to convert LaTeX to MathML.
3385 %j: Executable file in fully expanded form as specified by
3386 `org-latex-to-mathml-jar-file'.
3387 %I: Input LaTeX file in fully expanded form
3388 %o: Output MathML file
3389 This command is used by `org-create-math-formula'.
3391 When using MathToWeb as the converter, set this to
3392 \"java -jar %j -unicode -force -df %o %I\"."
3393 :group 'org-latex
3394 :version "24.1"
3395 :type '(choice
3396 (const :tag "None" nil)
3397 (string :tag "\nShell command")))
3399 (defcustom org-latex-create-formula-image-program 'dvipng
3400 "Program to convert LaTeX fragments with.
3402 dvipng Process the LaTeX fragments to dvi file, then convert
3403 dvi files to png files using dvipng.
3404 This will also include processing of non-math environments.
3405 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3406 to convert pdf files to png files"
3407 :group 'org-latex
3408 :version "24.1"
3409 :type '(choice
3410 (const :tag "dvipng" dvipng)
3411 (const :tag "imagemagick" imagemagick)))
3413 (defun org-format-latex-mathml-available-p ()
3414 "Return t if `org-latex-to-mathml-convert-command' is usable."
3415 (save-match-data
3416 (when (and (boundp 'org-latex-to-mathml-convert-command)
3417 org-latex-to-mathml-convert-command)
3418 (let ((executable (car (split-string
3419 org-latex-to-mathml-convert-command))))
3420 (when (executable-find executable)
3421 (if (string-match
3422 "%j" org-latex-to-mathml-convert-command)
3423 (file-readable-p org-latex-to-mathml-jar-file)
3424 t))))))
3426 (defcustom org-format-latex-header "\\documentclass{article}
3427 \\usepackage[usenames]{color}
3428 \\usepackage{amsmath}
3429 \\usepackage[mathscr]{eucal}
3430 \\pagestyle{empty} % do not remove
3431 \[PACKAGES]
3432 \[DEFAULT-PACKAGES]
3433 % The settings below are copied from fullpage.sty
3434 \\setlength{\\textwidth}{\\paperwidth}
3435 \\addtolength{\\textwidth}{-3cm}
3436 \\setlength{\\oddsidemargin}{1.5cm}
3437 \\addtolength{\\oddsidemargin}{-2.54cm}
3438 \\setlength{\\evensidemargin}{\\oddsidemargin}
3439 \\setlength{\\textheight}{\\paperheight}
3440 \\addtolength{\\textheight}{-\\headheight}
3441 \\addtolength{\\textheight}{-\\headsep}
3442 \\addtolength{\\textheight}{-\\footskip}
3443 \\addtolength{\\textheight}{-3cm}
3444 \\setlength{\\topmargin}{1.5cm}
3445 \\addtolength{\\topmargin}{-2.54cm}"
3446 "The document header used for processing LaTeX fragments.
3447 It is imperative that this header make sure that no page number
3448 appears on the page. The package defined in the variables
3449 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3450 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3451 will be appended."
3452 :group 'org-latex
3453 :type 'string)
3455 (defvar org-format-latex-header-extra nil)
3457 (defun org-set-packages-alist (var val)
3458 "Set the packages alist and make sure it has 3 elements per entry."
3459 (set var (mapcar (lambda (x)
3460 (if (and (consp x) (= (length x) 2))
3461 (list (car x) (nth 1 x) t)
3463 val)))
3465 (defun org-get-packages-alist (var)
3467 "Get the packages alist and make sure it has 3 elements per entry."
3468 (mapcar (lambda (x)
3469 (if (and (consp x) (= (length x) 2))
3470 (list (car x) (nth 1 x) t)
3472 (default-value var)))
3474 ;; The following variables are defined here because is it also used
3475 ;; when formatting latex fragments. Originally it was part of the
3476 ;; LaTeX exporter, which is why the name includes "export".
3477 (defcustom org-export-latex-default-packages-alist
3478 '(("AUTO" "inputenc" t)
3479 ("T1" "fontenc" t)
3480 ("" "fixltx2e" nil)
3481 ("" "graphicx" t)
3482 ("" "longtable" nil)
3483 ("" "float" nil)
3484 ("" "wrapfig" nil)
3485 ("" "soul" t)
3486 ("" "textcomp" t)
3487 ("" "marvosym" t)
3488 ("" "wasysym" t)
3489 ("" "latexsym" t)
3490 ("" "amssymb" t)
3491 ("" "hyperref" nil)
3492 "\\tolerance=1000"
3494 "Alist of default packages to be inserted in the header.
3495 Change this only if one of the packages here causes an incompatibility
3496 with another package you are using.
3497 The packages in this list are needed by one part or another of Org-mode
3498 to function properly.
3500 - inputenc, fontenc: for basic font and character selection
3501 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3502 for interpreting the entities in `org-entities'. You can skip some of these
3503 packages if you don't use any of the symbols in it.
3504 - graphicx: for including images
3505 - float, wrapfig: for figure placement
3506 - longtable: for long tables
3507 - hyperref: for cross references
3509 Therefore you should not modify this variable unless you know what you
3510 are doing. The one reason to change it anyway is that you might be loading
3511 some other package that conflicts with one of the default packages.
3512 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3513 If SNIPPET-FLAG is t, the package also needs to be included when
3514 compiling LaTeX snippets into images for inclusion into HTML."
3515 :group 'org-export-latex
3516 :set 'org-set-packages-alist
3517 :get 'org-get-packages-alist
3518 :version "24.1"
3519 :type '(repeat
3520 (choice
3521 (list :tag "options/package pair"
3522 (string :tag "options")
3523 (string :tag "package")
3524 (boolean :tag "Snippet"))
3525 (string :tag "A line of LaTeX"))))
3527 (defcustom org-export-latex-packages-alist nil
3528 "Alist of packages to be inserted in every LaTeX header.
3529 These will be inserted after `org-export-latex-default-packages-alist'.
3530 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3531 SNIPPET-FLAG, when t, indicates that this package is also needed when
3532 turning LaTeX snippets into images for inclusion into HTML.
3533 Make sure that you only list packages here which:
3534 - you want in every file
3535 - do not conflict with the default packages in
3536 `org-export-latex-default-packages-alist'
3537 - do not conflict with the setup in `org-format-latex-header'."
3538 :group 'org-export-latex
3539 :set 'org-set-packages-alist
3540 :get 'org-get-packages-alist
3541 :type '(repeat
3542 (choice
3543 (list :tag "options/package pair"
3544 (string :tag "options")
3545 (string :tag "package")
3546 (boolean :tag "Snippet"))
3547 (string :tag "A line of LaTeX"))))
3550 (defgroup org-appearance nil
3551 "Settings for Org-mode appearance."
3552 :tag "Org Appearance"
3553 :group 'org)
3555 (defcustom org-level-color-stars-only nil
3556 "Non-nil means fontify only the stars in each headline.
3557 When nil, the entire headline is fontified.
3558 Changing it requires restart of `font-lock-mode' to become effective
3559 also in regions already fontified."
3560 :group 'org-appearance
3561 :type 'boolean)
3563 (defcustom org-hide-leading-stars nil
3564 "Non-nil means hide the first N-1 stars in a headline.
3565 This works by using the face `org-hide' for these stars. This
3566 face is white for a light background, and black for a dark
3567 background. You may have to customize the face `org-hide' to
3568 make this work.
3569 Changing it requires restart of `font-lock-mode' to become effective
3570 also in regions already fontified.
3571 You may also set this on a per-file basis by adding one of the following
3572 lines to the buffer:
3574 #+STARTUP: hidestars
3575 #+STARTUP: showstars"
3576 :group 'org-appearance
3577 :type 'boolean)
3579 (defcustom org-hidden-keywords nil
3580 "List of symbols corresponding to keywords to be hidden the org buffer.
3581 For example, a value '(title) for this list will make the document's title
3582 appear in the buffer without the initial #+TITLE: keyword."
3583 :group 'org-appearance
3584 :version "24.1"
3585 :type '(set (const :tag "#+AUTHOR" author)
3586 (const :tag "#+DATE" date)
3587 (const :tag "#+EMAIL" email)
3588 (const :tag "#+TITLE" title)))
3590 (defcustom org-fontify-done-headline nil
3591 "Non-nil means change the face of a headline if it is marked DONE.
3592 Normally, only the TODO/DONE keyword indicates the state of a headline.
3593 When this is non-nil, the headline after the keyword is set to the
3594 `org-headline-done' as an additional indication."
3595 :group 'org-appearance
3596 :type 'boolean)
3598 (defcustom org-fontify-emphasized-text t
3599 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3600 Changing this variable requires a restart of Emacs to take effect."
3601 :group 'org-appearance
3602 :type 'boolean)
3604 (defcustom org-fontify-whole-heading-line nil
3605 "Non-nil means fontify the whole line for headings.
3606 This is useful when setting a background color for the
3607 org-level-* faces."
3608 :group 'org-appearance
3609 :type 'boolean)
3611 (defcustom org-highlight-latex-fragments-and-specials nil
3612 "Non-nil means fontify what is treated specially by the exporters."
3613 :group 'org-appearance
3614 :type 'boolean)
3616 (defcustom org-hide-emphasis-markers nil
3617 "Non-nil mean font-lock should hide the emphasis marker characters."
3618 :group 'org-appearance
3619 :type 'boolean)
3621 (defcustom org-pretty-entities nil
3622 "Non-nil means show entities as UTF8 characters.
3623 When nil, the \\name form remains in the buffer."
3624 :group 'org-appearance
3625 :version "24.1"
3626 :type 'boolean)
3628 (defcustom org-pretty-entities-include-sub-superscripts t
3629 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3630 :group 'org-appearance
3631 :version "24.1"
3632 :type 'boolean)
3634 (defvar org-emph-re nil
3635 "Regular expression for matching emphasis.
3636 After a match, the match groups contain these elements:
3637 0 The match of the full regular expression, including the characters
3638 before and after the proper match
3639 1 The character before the proper match, or empty at beginning of line
3640 2 The proper match, including the leading and trailing markers
3641 3 The leading marker like * or /, indicating the type of highlighting
3642 4 The text between the emphasis markers, not including the markers
3643 5 The character after the match, empty at the end of a line")
3644 (defvar org-verbatim-re nil
3645 "Regular expression for matching verbatim text.")
3646 (defvar org-emphasis-regexp-components) ; defined just below
3647 (defvar org-emphasis-alist) ; defined just below
3648 (defun org-set-emph-re (var val)
3649 "Set variable and compute the emphasis regular expression."
3650 (set var val)
3651 (when (and (boundp 'org-emphasis-alist)
3652 (boundp 'org-emphasis-regexp-components)
3653 org-emphasis-alist org-emphasis-regexp-components)
3654 (let* ((e org-emphasis-regexp-components)
3655 (pre (car e))
3656 (post (nth 1 e))
3657 (border (nth 2 e))
3658 (body (nth 3 e))
3659 (nl (nth 4 e))
3660 (body1 (concat body "*?"))
3661 (markers (mapconcat 'car org-emphasis-alist ""))
3662 (vmarkers (mapconcat
3663 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3664 org-emphasis-alist "")))
3665 ;; make sure special characters appear at the right position in the class
3666 (if (string-match "\\^" markers)
3667 (setq markers (concat (replace-match "" t t markers) "^")))
3668 (if (string-match "-" markers)
3669 (setq markers (concat (replace-match "" t t markers) "-")))
3670 (if (string-match "\\^" vmarkers)
3671 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3672 (if (string-match "-" vmarkers)
3673 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3674 (if (> nl 0)
3675 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3676 (int-to-string nl) "\\}")))
3677 ;; Make the regexp
3678 (setq org-emph-re
3679 (concat "\\([" pre "]\\|^\\)"
3680 "\\("
3681 "\\([" markers "]\\)"
3682 "\\("
3683 "[^" border "]\\|"
3684 "[^" border "]"
3685 body1
3686 "[^" border "]"
3687 "\\)"
3688 "\\3\\)"
3689 "\\([" post "]\\|$\\)"))
3690 (setq org-verbatim-re
3691 (concat "\\([" pre "]\\|^\\)"
3692 "\\("
3693 "\\([" vmarkers "]\\)"
3694 "\\("
3695 "[^" border "]\\|"
3696 "[^" border "]"
3697 body1
3698 "[^" border "]"
3699 "\\)"
3700 "\\3\\)"
3701 "\\([" post "]\\|$\\)")))))
3703 (defcustom org-emphasis-regexp-components
3704 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3705 "Components used to build the regular expression for emphasis.
3706 This is a list with five entries. Terminology: In an emphasis string
3707 like \" *strong word* \", we call the initial space PREMATCH, the final
3708 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3709 and \"trong wor\" is the body. The different components in this variable
3710 specify what is allowed/forbidden in each part:
3712 pre Chars allowed as prematch. Beginning of line will be allowed too.
3713 post Chars allowed as postmatch. End of line will be allowed too.
3714 border The chars *forbidden* as border characters.
3715 body-regexp A regexp like \".\" to match a body character. Don't use
3716 non-shy groups here, and don't allow newline here.
3717 newline The maximum number of newlines allowed in an emphasis exp.
3719 Use customize to modify this, or restart Emacs after changing it."
3720 :group 'org-appearance
3721 :set 'org-set-emph-re
3722 :type '(list
3723 (sexp :tag "Allowed chars in pre ")
3724 (sexp :tag "Allowed chars in post ")
3725 (sexp :tag "Forbidden chars in border ")
3726 (sexp :tag "Regexp for body ")
3727 (integer :tag "number of newlines allowed")
3728 (option (boolean :tag "Please ignore this button"))))
3730 (defcustom org-emphasis-alist
3731 `(("*" bold "<b>" "</b>")
3732 ("/" italic "<i>" "</i>")
3733 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3734 ("=" org-code "<code>" "</code>" verbatim)
3735 ("~" org-verbatim "<code>" "</code>" verbatim)
3736 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3737 "<del>" "</del>")
3739 "Special syntax for emphasized text.
3740 Text starting and ending with a special character will be emphasized, for
3741 example *bold*, _underlined_ and /italic/. This variable sets the marker
3742 characters, the face to be used by font-lock for highlighting in Org-mode
3743 Emacs buffers, and the HTML tags to be used for this.
3744 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3745 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3746 Use customize to modify this, or restart Emacs after changing it."
3747 :group 'org-appearance
3748 :set 'org-set-emph-re
3749 :type '(repeat
3750 (list
3751 (string :tag "Marker character")
3752 (choice
3753 (face :tag "Font-lock-face")
3754 (plist :tag "Face property list"))
3755 (string :tag "HTML start tag")
3756 (string :tag "HTML end tag")
3757 (option (const verbatim)))))
3759 (defvar org-protecting-blocks
3760 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3761 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3762 This is needed for font-lock setup.")
3764 ;;; Miscellaneous options
3766 (defgroup org-completion nil
3767 "Completion in Org-mode."
3768 :tag "Org Completion"
3769 :group 'org)
3771 (defcustom org-completion-use-ido nil
3772 "Non-nil means use ido completion wherever possible.
3773 Note that `ido-mode' must be active for this variable to be relevant.
3774 If you decide to turn this variable on, you might well want to turn off
3775 `org-outline-path-complete-in-steps'.
3776 See also `org-completion-use-iswitchb'."
3777 :group 'org-completion
3778 :type 'boolean)
3780 (defcustom org-completion-use-iswitchb nil
3781 "Non-nil means use iswitchb completion wherever possible.
3782 Note that `iswitchb-mode' must be active for this variable to be relevant.
3783 If you decide to turn this variable on, you might well want to turn off
3784 `org-outline-path-complete-in-steps'.
3785 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3786 :group 'org-completion
3787 :type 'boolean)
3789 (defcustom org-completion-fallback-command 'hippie-expand
3790 "The expansion command called by \\[pcomplete] in normal context.
3791 Normal means, no org-mode-specific context."
3792 :group 'org-completion
3793 :type 'function)
3795 ;;; Functions and variables from their packages
3796 ;; Declared here to avoid compiler warnings
3798 ;; XEmacs only
3799 (defvar outline-mode-menu-heading)
3800 (defvar outline-mode-menu-show)
3801 (defvar outline-mode-menu-hide)
3802 (defvar zmacs-regions) ; XEmacs regions
3804 ;; Emacs only
3805 (defvar mark-active)
3807 ;; Various packages
3808 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3809 (declare-function calendar-forward-day "cal-move" (arg))
3810 (declare-function calendar-goto-date "cal-move" (date))
3811 (declare-function calendar-goto-today "cal-move" ())
3812 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3813 (defvar calc-embedded-close-formula)
3814 (defvar calc-embedded-open-formula)
3815 (declare-function cdlatex-tab "ext:cdlatex" ())
3816 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3817 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3818 (defvar font-lock-unfontify-region-function)
3819 (declare-function iswitchb-read-buffer "iswitchb"
3820 (prompt &optional default require-match start matches-set))
3821 (defvar iswitchb-temp-buflist)
3822 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3823 (defvar org-agenda-tags-todo-honor-ignore-options)
3824 (declare-function org-agenda-skip "org-agenda" ())
3825 (declare-function
3826 org-agenda-format-item "org-agenda"
3827 (extra txt &optional category tags dotime noprefix remove-re habitp))
3828 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3829 (declare-function org-agenda-change-all-lines "org-agenda"
3830 (newhead hdmarker &optional fixface just-this))
3831 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3832 (declare-function org-agenda-maybe-redo "org-agenda" ())
3833 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3834 (beg end))
3835 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3836 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3837 "org-agenda" (&optional end))
3838 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3839 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3840 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3841 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3842 (declare-function org-indent-mode "org-indent" (&optional arg))
3843 (declare-function parse-time-string "parse-time" (string))
3844 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3845 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3846 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3847 (defvar remember-data-file)
3848 (defvar texmathp-why)
3849 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3850 (declare-function table--at-cell-p "table" (position &optional object at-column))
3852 (defvar w3m-current-url)
3853 (defvar w3m-current-title)
3855 (defvar org-latex-regexps)
3857 ;;; Autoload and prepare some org modules
3859 ;; Some table stuff that needs to be defined here, because it is used
3860 ;; by the functions setting up org-mode or checking for table context.
3862 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3863 "Detect an org-type or table-type table.")
3864 (defconst org-table-line-regexp "^[ \t]*|"
3865 "Detect an org-type table line.")
3866 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3867 "Detect an org-type table line.")
3868 (defconst org-table-hline-regexp "^[ \t]*|-"
3869 "Detect an org-type table hline.")
3870 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3871 "Detect a table-type table hline.")
3872 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3873 "Detect the first line outside a table when searching from within it.
3874 This works for both table types.")
3876 ;; Autoload the functions in org-table.el that are needed by functions here.
3878 (eval-and-compile
3879 (org-autoload "org-table"
3880 '(org-table-align org-table-begin org-table-blank-field
3881 org-table-convert org-table-convert-region org-table-copy-down
3882 org-table-copy-region org-table-create
3883 org-table-create-or-convert-from-region
3884 org-table-create-with-table.el org-table-current-dline
3885 org-table-cut-region org-table-delete-column org-table-edit-field
3886 org-table-edit-formulas org-table-end org-table-eval-formula
3887 org-table-export org-table-field-info
3888 org-table-get-stored-formulas org-table-goto-column
3889 org-table-hline-and-move org-table-import org-table-insert-column
3890 org-table-insert-hline org-table-insert-row org-table-iterate
3891 org-table-justify-field-maybe org-table-kill-row
3892 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3893 org-table-move-column org-table-move-column-left
3894 org-table-move-column-right org-table-move-row
3895 org-table-move-row-down org-table-move-row-up
3896 org-table-next-field org-table-next-row org-table-paste-rectangle
3897 org-table-previous-field org-table-recalculate
3898 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3899 org-table-toggle-coordinate-overlays
3900 org-table-toggle-formula-debugger org-table-wrap-region
3901 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3902 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3903 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3905 (defun org-at-table-p (&optional table-type)
3906 "Return t if the cursor is inside an org-type table.
3907 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3908 (if org-enable-table-editor
3909 (save-excursion
3910 (beginning-of-line 1)
3911 (looking-at (if table-type org-table-any-line-regexp
3912 org-table-line-regexp)))
3913 nil))
3914 (defsubst org-table-p () (org-at-table-p))
3916 (defun org-at-table.el-p ()
3917 "Return t if and only if we are at a table.el table."
3918 (and (org-at-table-p 'any)
3919 (save-excursion
3920 (goto-char (org-table-begin 'any))
3921 (looking-at org-table1-hline-regexp))))
3922 (defun org-table-recognize-table.el ()
3923 "If there is a table.el table nearby, recognize it and move into it."
3924 (if org-table-tab-recognizes-table.el
3925 (if (org-at-table.el-p)
3926 (progn
3927 (beginning-of-line 1)
3928 (if (looking-at org-table-dataline-regexp)
3930 (if (looking-at org-table1-hline-regexp)
3931 (progn
3932 (beginning-of-line 2)
3933 (if (looking-at org-table-any-border-regexp)
3934 (beginning-of-line -1)))))
3935 (if (re-search-forward "|" (org-table-end t) t)
3936 (progn
3937 (require 'table)
3938 (if (table--at-cell-p (point))
3940 (message "recognizing table.el table...")
3941 (table-recognize-table)
3942 (message "recognizing table.el table...done")))
3943 (error "This should not happen"))
3945 nil)
3946 nil))
3948 (defun org-at-table-hline-p ()
3949 "Return t if the cursor is inside a hline in a table."
3950 (if org-enable-table-editor
3951 (save-excursion
3952 (beginning-of-line 1)
3953 (looking-at org-table-hline-regexp))
3954 nil))
3956 (defvar org-table-clean-did-remove-column nil)
3958 (defun org-table-map-tables (function &optional quietly)
3959 "Apply FUNCTION to the start of all tables in the buffer."
3960 (save-excursion
3961 (save-restriction
3962 (widen)
3963 (goto-char (point-min))
3964 (while (re-search-forward org-table-any-line-regexp nil t)
3965 (unless quietly
3966 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3967 (beginning-of-line 1)
3968 (when (and (looking-at org-table-line-regexp)
3969 ;; Exclude tables in src/example/verbatim/clocktable blocks
3970 (not (org-in-block-p '("src" "example"))))
3971 (save-excursion (funcall function))
3972 (or (looking-at org-table-line-regexp)
3973 (forward-char 1)))
3974 (re-search-forward org-table-any-border-regexp nil 1))))
3975 (unless quietly (message "Mapping tables: done")))
3977 ;; Declare and autoload functions from org-exp.el & Co
3979 (declare-function org-default-export-plist "org-exp")
3980 (declare-function org-infile-export-plist "org-exp")
3981 (declare-function org-get-current-options "org-exp")
3982 (eval-and-compile
3983 (org-autoload "org-exp"
3984 '(org-export org-export-visible
3985 org-insert-export-options-template
3986 org-table-clean-before-export))
3987 (org-autoload "org-ascii"
3988 '(org-export-as-ascii org-export-ascii-preprocess
3989 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3990 org-export-region-as-ascii))
3991 (org-autoload "org-latex"
3992 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3993 org-replace-region-by-latex org-export-region-as-latex
3994 org-export-as-latex org-export-as-pdf
3995 org-export-as-pdf-and-open))
3996 (org-autoload "org-html"
3997 '(org-export-as-html-and-open
3998 org-export-as-html-batch org-export-as-html-to-buffer
3999 org-replace-region-by-html org-export-region-as-html
4000 org-export-as-html))
4001 (org-autoload "org-docbook"
4002 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4003 org-replace-region-by-docbook org-export-region-as-docbook
4004 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4005 org-export-as-docbook))
4006 (org-autoload "org-icalendar"
4007 '(org-export-icalendar-this-file
4008 org-export-icalendar-all-agenda-files
4009 org-export-icalendar-combine-agenda-files))
4010 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4011 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4013 ;; Declare and autoload functions from org-agenda.el
4015 (eval-and-compile
4016 (org-autoload "org-agenda"
4017 '(org-agenda org-agenda-list org-search-view
4018 org-todo-list org-tags-view org-agenda-list-stuck-projects
4019 org-diary org-agenda-to-appt
4020 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4022 ;; Autoload org-remember
4024 (eval-and-compile
4025 (org-autoload "org-remember"
4026 '(org-remember-insinuate org-remember-annotation
4027 org-remember-apply-template org-remember org-remember-handler)))
4029 (eval-and-compile
4030 (org-autoload "org-capture"
4031 '(org-capture org-capture-insert-template-here
4032 org-capture-import-remember-templates)))
4034 ;; Autoload org-clock.el
4036 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4037 (beg end))
4038 (declare-function org-clock-update-mode-line "org-clock" ())
4039 (declare-function org-resolve-clocks "org-clock"
4040 (&optional also-non-dangling-p prompt last-valid))
4041 (defvar org-clock-start-time)
4042 (defvar org-clock-marker (make-marker)
4043 "Marker recording the last clock-in.")
4044 (defvar org-clock-hd-marker (make-marker)
4045 "Marker recording the last clock-in, but the headline position.")
4046 (defvar org-clock-heading ""
4047 "The heading of the current clock entry.")
4048 (defun org-clock-is-active ()
4049 "Return non-nil if clock is currently running.
4050 The return value is actually the clock marker."
4051 (marker-buffer org-clock-marker))
4053 (eval-and-compile
4054 (org-autoload
4055 "org-clock"
4056 '(org-clock-in org-clock-out org-clock-cancel
4057 org-clock-goto org-clock-sum org-clock-display
4058 org-clock-remove-overlays org-clock-report
4059 org-clocktable-shift org-dblock-write:clocktable
4060 org-get-clocktable org-resolve-clocks)))
4062 (defun org-clock-update-time-maybe ()
4063 "If this is a CLOCK line, update it and return t.
4064 Otherwise, return nil."
4065 (interactive)
4066 (save-excursion
4067 (beginning-of-line 1)
4068 (skip-chars-forward " \t")
4069 (when (looking-at org-clock-string)
4070 (let ((re (concat "[ \t]*" org-clock-string
4071 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4072 "\\([ \t]*=>.*\\)?\\)?"))
4073 ts te h m s neg)
4074 (cond
4075 ((not (looking-at re))
4076 nil)
4077 ((not (match-end 2))
4078 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4079 (> org-clock-marker (point))
4080 (<= org-clock-marker (point-at-eol)))
4081 ;; The clock is running here
4082 (setq org-clock-start-time
4083 (apply 'encode-time
4084 (org-parse-time-string (match-string 1))))
4085 (org-clock-update-mode-line)))
4087 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4088 (end-of-line 1)
4089 (setq ts (match-string 1)
4090 te (match-string 3))
4091 (setq s (- (org-float-time
4092 (apply 'encode-time (org-parse-time-string te)))
4093 (org-float-time
4094 (apply 'encode-time (org-parse-time-string ts))))
4095 neg (< s 0)
4096 s (abs s)
4097 h (floor (/ s 3600))
4098 s (- s (* 3600 h))
4099 m (floor (/ s 60))
4100 s (- s (* 60 s)))
4101 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4102 t))))))
4104 (defun org-check-running-clock ()
4105 "Check if the current buffer contains the running clock.
4106 If yes, offer to stop it and to save the buffer with the changes."
4107 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4108 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4109 (buffer-name))))
4110 (org-clock-out)
4111 (when (y-or-n-p "Save changed buffer?")
4112 (save-buffer))))
4114 (defun org-clocktable-try-shift (dir n)
4115 "Check if this line starts a clock table, if yes, shift the time block."
4116 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4117 (org-clocktable-shift dir n)))
4119 ;; Autoload org-timer.el
4121 (eval-and-compile
4122 (org-autoload
4123 "org-timer"
4124 '(org-timer-start org-timer org-timer-item
4125 org-timer-change-times-in-region
4126 org-timer-set-timer
4127 org-timer-reset-timers
4128 org-timer-show-remaining-time)))
4130 ;; Autoload org-feed.el
4132 (eval-and-compile
4133 (org-autoload
4134 "org-feed"
4135 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4138 ;; Autoload org-indent.el
4140 ;; Define the variable already here, to make sure we have it.
4141 (defvar org-indent-mode nil
4142 "Non-nil if Org-Indent mode is enabled.
4143 Use the command `org-indent-mode' to change this variable.")
4145 (eval-and-compile
4146 (org-autoload
4147 "org-indent"
4148 '(org-indent-mode)))
4150 ;; Autoload org-mobile.el
4152 (eval-and-compile
4153 (org-autoload
4154 "org-mobile"
4155 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4157 ;; Autoload archiving code
4158 ;; The stuff that is needed for cycling and tags has to be defined here.
4160 (defgroup org-archive nil
4161 "Options concerning archiving in Org-mode."
4162 :tag "Org Archive"
4163 :group 'org-structure)
4165 (defcustom org-archive-location "%s_archive::"
4166 "The location where subtrees should be archived.
4168 The value of this variable is a string, consisting of two parts,
4169 separated by a double-colon. The first part is a filename and
4170 the second part is a headline.
4172 When the filename is omitted, archiving happens in the same file.
4173 %s in the filename will be replaced by the current file
4174 name (without the directory part). Archiving to a different file
4175 is useful to keep archived entries from contributing to the
4176 Org-mode Agenda.
4178 The archived entries will be filed as subtrees of the specified
4179 headline. When the headline is omitted, the subtrees are simply
4180 filed away at the end of the file, as top-level entries. Also in
4181 the heading you can use %s to represent the file name, this can be
4182 useful when using the same archive for a number of different files.
4184 Here are a few examples:
4185 \"%s_archive::\"
4186 If the current file is Projects.org, archive in file
4187 Projects.org_archive, as top-level trees. This is the default.
4189 \"::* Archived Tasks\"
4190 Archive in the current file, under the top-level headline
4191 \"* Archived Tasks\".
4193 \"~/org/archive.org::\"
4194 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4196 \"~/org/archive.org::* From %s\"
4197 Archive in file ~/org/archive.org (absolute path), under headlines
4198 \"From FILENAME\" where file name is the current file name.
4200 \"~/org/datetree.org::datetree/* Finished Tasks\"
4201 The \"datetree/\" string is special, signifying to archive
4202 items to the datetree. Items are placed in either the CLOSED
4203 date of the item, or the current date if there is no CLOSED date.
4204 The heading will be a subentry to the current date. There doesn't
4205 need to be a heading, but there always needs to be a slash after
4206 datetree. For example, to store archived items directly in the
4207 datetree, use \"~/org/datetree.org::datetree/\".
4209 \"basement::** Finished Tasks\"
4210 Archive in file ./basement (relative path), as level 3 trees
4211 below the level 2 heading \"** Finished Tasks\".
4213 You may set this option on a per-file basis by adding to the buffer a
4214 line like
4216 #+ARCHIVE: basement::** Finished Tasks
4218 You may also define it locally for a subtree by setting an ARCHIVE property
4219 in the entry. If such a property is found in an entry, or anywhere up
4220 the hierarchy, it will be used."
4221 :group 'org-archive
4222 :type 'string)
4224 (defcustom org-archive-tag "ARCHIVE"
4225 "The tag that marks a subtree as archived.
4226 An archived subtree does not open during visibility cycling, and does
4227 not contribute to the agenda listings.
4228 After changing this, font-lock must be restarted in the relevant buffers to
4229 get the proper fontification."
4230 :group 'org-archive
4231 :group 'org-keywords
4232 :type 'string)
4234 (defcustom org-agenda-skip-archived-trees t
4235 "Non-nil means the agenda will skip any items located in archived trees.
4236 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4237 variable is no longer recommended, you should leave it at the value t.
4238 Instead, use the key `v' to cycle the archives-mode in the agenda."
4239 :group 'org-archive
4240 :group 'org-agenda-skip
4241 :type 'boolean)
4243 (defcustom org-columns-skip-archived-trees t
4244 "Non-nil means ignore archived trees when creating column view."
4245 :group 'org-archive
4246 :group 'org-properties
4247 :type 'boolean)
4249 (defcustom org-cycle-open-archived-trees nil
4250 "Non-nil means `org-cycle' will open archived trees.
4251 An archived tree is a tree marked with the tag ARCHIVE.
4252 When nil, archived trees will stay folded. You can still open them with
4253 normal outline commands like `show-all', but not with the cycling commands."
4254 :group 'org-archive
4255 :group 'org-cycle
4256 :type 'boolean)
4258 (defcustom org-sparse-tree-open-archived-trees nil
4259 "Non-nil means sparse tree construction shows matches in archived trees.
4260 When nil, matches in these trees are highlighted, but the trees are kept in
4261 collapsed state."
4262 :group 'org-archive
4263 :group 'org-sparse-trees
4264 :type 'boolean)
4266 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4267 "The default date type when building a sparse tree.
4268 When this is nil, a date is a scheduled or a deadline timestamp.
4269 Otherwise, these types are allowed:
4271 all: all timestamps
4272 active: only active timestamps (<...>)
4273 inactive: only inactive timestamps (<...)
4274 scheduled: only scheduled timestamps
4275 deadline: only deadline timestamps"
4276 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4277 (const :tag "All timestamps" all)
4278 (const :tag "Only active timestamps" active)
4279 (const :tag "Only inactive timestamps" inactive)
4280 (const :tag "Only scheduled timestamps" scheduled)
4281 (const :tag "Only deadline timestamps" deadline))
4282 :group 'org-sparse-trees
4283 :version "24.2")
4285 (defun org-cycle-hide-archived-subtrees (state)
4286 "Re-hide all archived subtrees after a visibility state change."
4287 (when (and (not org-cycle-open-archived-trees)
4288 (not (memq state '(overview folded))))
4289 (save-excursion
4290 (let* ((globalp (memq state '(contents all)))
4291 (beg (if globalp (point-min) (point)))
4292 (end (if globalp (point-max) (org-end-of-subtree t))))
4293 (org-hide-archived-subtrees beg end)
4294 (goto-char beg)
4295 (if (looking-at (concat ".*:" org-archive-tag ":"))
4296 (message "%s" (substitute-command-keys
4297 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4299 (defun org-force-cycle-archived ()
4300 "Cycle subtree even if it is archived."
4301 (interactive)
4302 (setq this-command 'org-cycle)
4303 (let ((org-cycle-open-archived-trees t))
4304 (call-interactively 'org-cycle)))
4306 (defun org-hide-archived-subtrees (beg end)
4307 "Re-hide all archived subtrees after a visibility state change."
4308 (save-excursion
4309 (let* ((re (concat ":" org-archive-tag ":")))
4310 (goto-char beg)
4311 (while (re-search-forward re end t)
4312 (when (org-at-heading-p)
4313 (org-flag-subtree t)
4314 (org-end-of-subtree t))))))
4316 (defun org-flag-subtree (flag)
4317 (save-excursion
4318 (org-back-to-heading t)
4319 (outline-end-of-heading)
4320 (outline-flag-region (point)
4321 (progn (org-end-of-subtree t) (point))
4322 flag)))
4324 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4326 (eval-and-compile
4327 (org-autoload "org-archive"
4328 '(org-add-archive-files org-archive-subtree
4329 org-archive-to-archive-sibling org-toggle-archive-tag
4330 org-archive-subtree-default
4331 org-archive-subtree-default-with-confirmation)))
4333 ;; Autoload Column View Code
4335 (declare-function org-columns-number-to-string "org-colview")
4336 (declare-function org-columns-get-format-and-top-level "org-colview")
4337 (declare-function org-columns-compute "org-colview")
4339 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4340 '(org-columns-number-to-string org-columns-get-format-and-top-level
4341 org-columns-compute org-agenda-columns org-columns-remove-overlays
4342 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4344 ;; Autoload ID code
4346 (declare-function org-id-store-link "org-id")
4347 (declare-function org-id-locations-load "org-id")
4348 (declare-function org-id-locations-save "org-id")
4349 (defvar org-id-track-globally)
4350 (org-autoload "org-id"
4351 '(org-id-get-create org-id-new org-id-copy org-id-get
4352 org-id-get-with-outline-path-completion
4353 org-id-get-with-outline-drilling org-id-store-link
4354 org-id-goto org-id-find org-id-store-link))
4356 ;; Autoload Plotting Code
4358 (org-autoload "org-plot"
4359 '(org-plot/gnuplot))
4361 ;;; Variables for pre-computed regular expressions, all buffer local
4363 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4364 "Matches first line of a hidden block.")
4365 (make-variable-buffer-local 'org-drawer-regexp)
4366 (defvar org-todo-regexp nil
4367 "Matches any of the TODO state keywords.")
4368 (make-variable-buffer-local 'org-todo-regexp)
4369 (defvar org-not-done-regexp nil
4370 "Matches any of the TODO state keywords except the last one.")
4371 (make-variable-buffer-local 'org-not-done-regexp)
4372 (defvar org-not-done-heading-regexp nil
4373 "Matches a TODO headline that is not done.")
4374 (make-variable-buffer-local 'org-not-done-regexp)
4375 (defvar org-todo-line-regexp nil
4376 "Matches a headline and puts TODO state into group 2 if present.")
4377 (make-variable-buffer-local 'org-todo-line-regexp)
4378 (defvar org-complex-heading-regexp nil
4379 "Matches a headline and puts everything into groups:
4380 group 1: the stars
4381 group 2: The todo keyword, maybe
4382 group 3: Priority cookie
4383 group 4: True headline
4384 group 5: Tags")
4385 (make-variable-buffer-local 'org-complex-heading-regexp)
4386 (defvar org-complex-heading-regexp-format nil
4387 "Printf format to make regexp to match an exact headline.
4388 This regexp will match the headline of any node which has the
4389 exact headline text that is put into the format, but may have any
4390 TODO state, priority and tags.")
4391 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4392 (defvar org-todo-line-tags-regexp nil
4393 "Matches a headline and puts TODO state into group 2 if present.
4394 Also put tags into group 4 if tags are present.")
4395 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4396 (defvar org-ds-keyword-length 12
4397 "Maximum length of the Deadline and SCHEDULED keywords.")
4398 (make-variable-buffer-local 'org-ds-keyword-length)
4399 (defvar org-deadline-regexp nil
4400 "Matches the DEADLINE keyword.")
4401 (make-variable-buffer-local 'org-deadline-regexp)
4402 (defvar org-deadline-time-regexp nil
4403 "Matches the DEADLINE keyword together with a time stamp.")
4404 (make-variable-buffer-local 'org-deadline-time-regexp)
4405 (defvar org-deadline-line-regexp nil
4406 "Matches the DEADLINE keyword and the rest of the line.")
4407 (make-variable-buffer-local 'org-deadline-line-regexp)
4408 (defvar org-scheduled-regexp nil
4409 "Matches the SCHEDULED keyword.")
4410 (make-variable-buffer-local 'org-scheduled-regexp)
4411 (defvar org-scheduled-time-regexp nil
4412 "Matches the SCHEDULED keyword together with a time stamp.")
4413 (make-variable-buffer-local 'org-scheduled-time-regexp)
4414 (defvar org-closed-time-regexp nil
4415 "Matches the CLOSED keyword together with a time stamp.")
4416 (make-variable-buffer-local 'org-closed-time-regexp)
4418 (defvar org-keyword-time-regexp nil
4419 "Matches any of the 4 keywords, together with the time stamp.")
4420 (make-variable-buffer-local 'org-keyword-time-regexp)
4421 (defvar org-keyword-time-not-clock-regexp nil
4422 "Matches any of the 3 keywords, together with the time stamp.")
4423 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4424 (defvar org-maybe-keyword-time-regexp nil
4425 "Matches a timestamp, possibly preceded by a keyword.")
4426 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4427 (defvar org-all-time-keywords nil
4428 "List of time keywords.")
4429 (make-variable-buffer-local 'org-all-time-keywords)
4431 (defconst org-plain-time-of-day-regexp
4432 (concat
4433 "\\(\\<[012]?[0-9]"
4434 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4435 "\\(--?"
4436 "\\(\\<[012]?[0-9]"
4437 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4438 "\\)?")
4439 "Regular expression to match a plain time or time range.
4440 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4441 groups carry important information:
4442 0 the full match
4443 1 the first time, range or not
4444 8 the second time, if it is a range.")
4446 (defconst org-plain-time-extension-regexp
4447 (concat
4448 "\\(\\<[012]?[0-9]"
4449 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4450 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4451 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4452 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4453 groups carry important information:
4454 0 the full match
4455 7 hours of duration
4456 9 minutes of duration")
4458 (defconst org-stamp-time-of-day-regexp
4459 (concat
4460 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4461 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4462 "\\(--?"
4463 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4464 "Regular expression to match a timestamp time or time range.
4465 After a match, the following groups carry important information:
4466 0 the full match
4467 1 date plus weekday, for back referencing to make sure both times are on the same day
4468 2 the first time, range or not
4469 4 the second time, if it is a range.")
4471 (defconst org-startup-options
4472 '(("fold" org-startup-folded t)
4473 ("overview" org-startup-folded t)
4474 ("nofold" org-startup-folded nil)
4475 ("showall" org-startup-folded nil)
4476 ("showeverything" org-startup-folded showeverything)
4477 ("content" org-startup-folded content)
4478 ("indent" org-startup-indented t)
4479 ("noindent" org-startup-indented nil)
4480 ("hidestars" org-hide-leading-stars t)
4481 ("showstars" org-hide-leading-stars nil)
4482 ("odd" org-odd-levels-only t)
4483 ("oddeven" org-odd-levels-only nil)
4484 ("align" org-startup-align-all-tables t)
4485 ("noalign" org-startup-align-all-tables nil)
4486 ("inlineimages" org-startup-with-inline-images t)
4487 ("noinlineimages" org-startup-with-inline-images nil)
4488 ("customtime" org-display-custom-times t)
4489 ("logdone" org-log-done time)
4490 ("lognotedone" org-log-done note)
4491 ("nologdone" org-log-done nil)
4492 ("lognoteclock-out" org-log-note-clock-out t)
4493 ("nolognoteclock-out" org-log-note-clock-out nil)
4494 ("logrepeat" org-log-repeat state)
4495 ("lognoterepeat" org-log-repeat note)
4496 ("nologrepeat" org-log-repeat nil)
4497 ("logreschedule" org-log-reschedule time)
4498 ("lognotereschedule" org-log-reschedule note)
4499 ("nologreschedule" org-log-reschedule nil)
4500 ("logredeadline" org-log-redeadline time)
4501 ("lognoteredeadline" org-log-redeadline note)
4502 ("nologredeadline" org-log-redeadline nil)
4503 ("logrefile" org-log-refile time)
4504 ("lognoterefile" org-log-refile note)
4505 ("nologrefile" org-log-refile nil)
4506 ("fninline" org-footnote-define-inline t)
4507 ("nofninline" org-footnote-define-inline nil)
4508 ("fnlocal" org-footnote-section nil)
4509 ("fnauto" org-footnote-auto-label t)
4510 ("fnprompt" org-footnote-auto-label nil)
4511 ("fnconfirm" org-footnote-auto-label confirm)
4512 ("fnplain" org-footnote-auto-label plain)
4513 ("fnadjust" org-footnote-auto-adjust t)
4514 ("nofnadjust" org-footnote-auto-adjust nil)
4515 ("constcgs" constants-unit-system cgs)
4516 ("constSI" constants-unit-system SI)
4517 ("noptag" org-tag-persistent-alist nil)
4518 ("hideblocks" org-hide-block-startup t)
4519 ("nohideblocks" org-hide-block-startup nil)
4520 ("beamer" org-startup-with-beamer-mode t)
4521 ("entitiespretty" org-pretty-entities t)
4522 ("entitiesplain" org-pretty-entities nil))
4523 "Variable associated with STARTUP options for org-mode.
4524 Each element is a list of three items: the startup options (as written
4525 in the #+STARTUP line), the corresponding variable, and the value to set
4526 this variable to if the option is found. An optional forth element PUSH
4527 means to push this value onto the list in the variable.")
4529 (defun org-update-property-plist (key val props)
4530 "Update PROPS with KEY and VAL."
4531 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4532 (key (if appending (substring key 0 (- (length key) 1)) key))
4533 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4534 (previous (cdr (assoc key props))))
4535 (if appending
4536 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4537 (cons (cons key val) remainder))))
4539 (defconst org-block-regexp
4540 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4541 "Regular expression for hiding blocks.")
4542 (defconst org-heading-keyword-regexp-format
4543 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4544 "Printf format for a regexp matching an headline with some keyword.
4545 This regexp will match the headline of any node which has the
4546 exact keyword that is put into the format. The keyword isn't in
4547 any group by default, but the stars and the body are.")
4548 (defconst org-heading-keyword-maybe-regexp-format
4549 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4550 "Printf format for a regexp matching an headline, possibly with some keyword.
4551 This regexp can match any headline with the specified keyword, or
4552 without a keyword. The keyword isn't in any group by default,
4553 but the stars and the body are.")
4555 (defun org-set-regexps-and-options ()
4556 "Precompute regular expressions for current buffer."
4557 (when (derived-mode-p 'org-mode)
4558 (org-set-local 'org-todo-kwd-alist nil)
4559 (org-set-local 'org-todo-key-alist nil)
4560 (org-set-local 'org-todo-key-trigger nil)
4561 (org-set-local 'org-todo-keywords-1 nil)
4562 (org-set-local 'org-done-keywords nil)
4563 (org-set-local 'org-todo-heads nil)
4564 (org-set-local 'org-todo-sets nil)
4565 (org-set-local 'org-todo-log-states nil)
4566 (org-set-local 'org-file-properties nil)
4567 (org-set-local 'org-file-tags nil)
4568 (let ((re (org-make-options-regexp
4569 '("CATEGORY" "TODO" "COLUMNS"
4570 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4571 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4572 "OPTIONS")
4573 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4574 (splitre "[ \t]+")
4575 (scripts org-use-sub-superscripts)
4576 kwds kws0 kwsa key log value cat arch tags const links hw dws
4577 tail sep kws1 prio props ftags drawers beamer-p
4578 ext-setup-or-nil setup-contents (start 0))
4579 (save-excursion
4580 (save-restriction
4581 (widen)
4582 (goto-char (point-min))
4583 (while (or (and ext-setup-or-nil
4584 (string-match re ext-setup-or-nil start)
4585 (setq start (match-end 0)))
4586 (and (setq ext-setup-or-nil nil start 0)
4587 (re-search-forward re nil t)))
4588 (setq key (upcase (match-string 1 ext-setup-or-nil))
4589 value (org-match-string-no-properties 2 ext-setup-or-nil))
4590 (if (stringp value) (setq value (org-trim value)))
4591 (cond
4592 ((equal key "CATEGORY")
4593 (setq cat value))
4594 ((member key '("SEQ_TODO" "TODO"))
4595 (push (cons 'sequence (org-split-string value splitre)) kwds))
4596 ((equal key "TYP_TODO")
4597 (push (cons 'type (org-split-string value splitre)) kwds))
4598 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4599 ;; general TODO-like setup
4600 (push (cons (intern (downcase (match-string 1 key)))
4601 (org-split-string value splitre)) kwds))
4602 ((equal key "TAGS")
4603 (setq tags (append tags (if tags '("\\n") nil)
4604 (org-split-string value splitre))))
4605 ((equal key "COLUMNS")
4606 (org-set-local 'org-columns-default-format value))
4607 ((equal key "LINK")
4608 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4609 (push (cons (match-string 1 value)
4610 (org-trim (match-string 2 value)))
4611 links)))
4612 ((equal key "PRIORITIES")
4613 (setq prio (org-split-string value " +")))
4614 ((equal key "PROPERTY")
4615 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4616 (setq props (org-update-property-plist (match-string 1 value)
4617 (match-string 2 value)
4618 props))))
4619 ((equal key "FILETAGS")
4620 (when (string-match "\\S-" value)
4621 (setq ftags
4622 (append
4623 ftags
4624 (apply 'append
4625 (mapcar (lambda (x) (org-split-string x ":"))
4626 (org-split-string value)))))))
4627 ((equal key "DRAWERS")
4628 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4629 ((equal key "CONSTANTS")
4630 (setq const (append const (org-split-string value splitre))))
4631 ((equal key "STARTUP")
4632 (let ((opts (org-split-string value splitre))
4633 l var val)
4634 (while (setq l (pop opts))
4635 (when (setq l (assoc l org-startup-options))
4636 (setq var (nth 1 l) val (nth 2 l))
4637 (if (not (nth 3 l))
4638 (set (make-local-variable var) val)
4639 (if (not (listp (symbol-value var)))
4640 (set (make-local-variable var) nil))
4641 (set (make-local-variable var) (symbol-value var))
4642 (add-to-list var val))))))
4643 ((equal key "ARCHIVE")
4644 (setq arch value)
4645 (remove-text-properties 0 (length arch)
4646 '(face t fontified t) arch))
4647 ((equal key "LATEX_CLASS")
4648 (setq beamer-p (equal value "beamer")))
4649 ((equal key "OPTIONS")
4650 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4651 (setq scripts (read (match-string 2 value)))))
4652 ((equal key "SETUPFILE")
4653 (setq setup-contents (org-file-contents
4654 (expand-file-name
4655 (org-remove-double-quotes value))
4656 'noerror))
4657 (if (not ext-setup-or-nil)
4658 (setq ext-setup-or-nil setup-contents start 0)
4659 (setq ext-setup-or-nil
4660 (concat (substring ext-setup-or-nil 0 start)
4661 "\n" setup-contents "\n"
4662 (substring ext-setup-or-nil start)))))))
4663 ;; search for property blocks
4664 (goto-char (point-min))
4665 (while (re-search-forward org-block-regexp nil t)
4666 (when (equal "PROPERTY" (upcase (match-string 1)))
4667 (setq value (replace-regexp-in-string
4668 "[\n\r]" " " (match-string 4)))
4669 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4670 (setq props (org-update-property-plist (match-string 1 value)
4671 (match-string 2 value)
4672 props)))))))
4673 (org-set-local 'org-use-sub-superscripts scripts)
4674 (when cat
4675 (org-set-local 'org-category (intern cat))
4676 (push (cons "CATEGORY" cat) props))
4677 (when prio
4678 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4679 (setq prio (mapcar 'string-to-char prio))
4680 (org-set-local 'org-highest-priority (nth 0 prio))
4681 (org-set-local 'org-lowest-priority (nth 1 prio))
4682 (org-set-local 'org-default-priority (nth 2 prio)))
4683 (and props (org-set-local 'org-file-properties (nreverse props)))
4684 (and ftags (org-set-local 'org-file-tags
4685 (mapcar 'org-add-prop-inherited ftags)))
4686 (and drawers (org-set-local 'org-drawers drawers))
4687 (and arch (org-set-local 'org-archive-location arch))
4688 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4689 ;; Process the TODO keywords
4690 (unless kwds
4691 ;; Use the global values as if they had been given locally.
4692 (setq kwds (default-value 'org-todo-keywords))
4693 (if (stringp (car kwds))
4694 (setq kwds (list (cons org-todo-interpretation
4695 (default-value 'org-todo-keywords)))))
4696 (setq kwds (reverse kwds)))
4697 (setq kwds (nreverse kwds))
4698 (let (inter kws kw)
4699 (while (setq kws (pop kwds))
4700 (let ((kws (or
4701 (run-hook-with-args-until-success
4702 'org-todo-setup-filter-hook kws)
4703 kws)))
4704 (setq inter (pop kws) sep (member "|" kws)
4705 kws0 (delete "|" (copy-sequence kws))
4706 kwsa nil
4707 kws1 (mapcar
4708 (lambda (x)
4709 ;; 1 2
4710 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4711 (progn
4712 (setq kw (match-string 1 x)
4713 key (and (match-end 2) (match-string 2 x))
4714 log (org-extract-log-state-settings x))
4715 (push (cons kw (and key (string-to-char key))) kwsa)
4716 (and log (push log org-todo-log-states))
4718 (error "Invalid TODO keyword %s" x)))
4719 kws0)
4720 kwsa (if kwsa (append '((:startgroup))
4721 (nreverse kwsa)
4722 '((:endgroup))))
4723 hw (car kws1)
4724 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4725 tail (list inter hw (car dws) (org-last dws))))
4726 (add-to-list 'org-todo-heads hw 'append)
4727 (push kws1 org-todo-sets)
4728 (setq org-done-keywords (append org-done-keywords dws nil))
4729 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4730 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4731 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4732 (setq org-todo-sets (nreverse org-todo-sets)
4733 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4734 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4735 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4736 ;; Process the constants
4737 (when const
4738 (let (e cst)
4739 (while (setq e (pop const))
4740 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4741 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4742 (setq org-table-formula-constants-local cst)))
4744 ;; Process the tags.
4745 (when tags
4746 (let (e tgs)
4747 (while (setq e (pop tags))
4748 (cond
4749 ((equal e "{") (push '(:startgroup) tgs))
4750 ((equal e "}") (push '(:endgroup) tgs))
4751 ((equal e "\\n") (push '(:newline) tgs))
4752 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4753 (push (cons (match-string 1 e)
4754 (string-to-char (match-string 2 e)))
4755 tgs))
4756 (t (push (list e) tgs))))
4757 (org-set-local 'org-tag-alist nil)
4758 (while (setq e (pop tgs))
4759 (or (and (stringp (car e))
4760 (assoc (car e) org-tag-alist))
4761 (push e org-tag-alist)))))
4763 ;; Compute the regular expressions and other local variables.
4764 ;; Using `org-outline-regexp-bol' would complicate them much,
4765 ;; because of the fixed white space at the end of that string.
4766 (if (not org-done-keywords)
4767 (setq org-done-keywords (and org-todo-keywords-1
4768 (list (org-last org-todo-keywords-1)))))
4769 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4770 (length org-scheduled-string)
4771 (length org-clock-string)
4772 (length org-closed-string)))
4773 org-drawer-regexp
4774 (concat "^[ \t]*:\\("
4775 (mapconcat 'regexp-quote org-drawers "\\|")
4776 "\\):[ \t]*$")
4777 org-not-done-keywords
4778 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4779 org-todo-regexp
4780 (concat "\\("
4781 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4782 "\\)")
4783 org-not-done-regexp
4784 (concat "\\("
4785 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4786 "\\)")
4787 org-not-done-heading-regexp
4788 (format org-heading-keyword-regexp-format org-not-done-regexp)
4789 org-todo-line-regexp
4790 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4791 org-complex-heading-regexp
4792 (concat "^\\(\\*+\\)"
4793 "\\(?: +" org-todo-regexp "\\)?"
4794 "\\(?: +\\(\\[#.\\]\\)\\)?"
4795 "\\(?: +\\(.*?\\)\\)?"
4796 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4797 "[ \t]*$")
4798 org-complex-heading-regexp-format
4799 (concat "^\\(\\*+\\)"
4800 "\\(?: +" org-todo-regexp "\\)?"
4801 "\\(?: +\\(\\[#.\\]\\)\\)?"
4802 "\\(?: +"
4803 ;; Stats cookies can be stuck to body.
4804 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4805 "\\(%s\\)"
4806 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4807 "\\)"
4808 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4809 "[ \t]*$")
4810 org-todo-line-tags-regexp
4811 (concat "^\\(\\*+\\)"
4812 "\\(?: +" org-todo-regexp "\\)?"
4813 "\\(?: +\\(.*?\\)\\)?"
4814 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4815 "[ \t]*$")
4816 org-deadline-regexp (concat "\\<" org-deadline-string)
4817 org-deadline-time-regexp
4818 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4819 org-deadline-line-regexp
4820 (concat "\\<\\(" org-deadline-string "\\).*")
4821 org-scheduled-regexp
4822 (concat "\\<" org-scheduled-string)
4823 org-scheduled-time-regexp
4824 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4825 org-closed-time-regexp
4826 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4827 org-keyword-time-regexp
4828 (concat "\\<\\(" org-scheduled-string
4829 "\\|" org-deadline-string
4830 "\\|" org-closed-string
4831 "\\|" org-clock-string "\\)"
4832 " *[[<]\\([^]>]+\\)[]>]")
4833 org-keyword-time-not-clock-regexp
4834 (concat "\\<\\(" org-scheduled-string
4835 "\\|" org-deadline-string
4836 "\\|" org-closed-string
4837 "\\)"
4838 " *[[<]\\([^]>]+\\)[]>]")
4839 org-maybe-keyword-time-regexp
4840 (concat "\\(\\<\\(" org-scheduled-string
4841 "\\|" org-deadline-string
4842 "\\|" org-closed-string
4843 "\\|" org-clock-string "\\)\\)?"
4844 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4845 org-all-time-keywords
4846 (mapcar (lambda (w) (substring w 0 -1))
4847 (list org-scheduled-string org-deadline-string
4848 org-clock-string org-closed-string))
4850 (org-compute-latex-and-specials-regexp)
4851 (org-set-font-lock-defaults))))
4853 (defun org-file-contents (file &optional noerror)
4854 "Return the contents of FILE, as a string."
4855 (if (or (not file)
4856 (not (file-readable-p file)))
4857 (if noerror
4858 (progn
4859 (message "Cannot read file \"%s\"" file)
4860 (ding) (sit-for 2)
4862 (error "Cannot read file \"%s\"" file))
4863 (with-temp-buffer
4864 (insert-file-contents file)
4865 (buffer-string))))
4867 (defun org-extract-log-state-settings (x)
4868 "Extract the log state setting from a TODO keyword string.
4869 This will extract info from a string like \"WAIT(w@/!)\"."
4870 (let (kw key log1 log2)
4871 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4872 (setq kw (match-string 1 x)
4873 key (and (match-end 2) (match-string 2 x))
4874 log1 (and (match-end 3) (match-string 3 x))
4875 log2 (and (match-end 4) (match-string 4 x)))
4876 (and (or log1 log2)
4877 (list kw
4878 (and log1 (if (equal log1 "!") 'time 'note))
4879 (and log2 (if (equal log2 "!") 'time 'note)))))))
4881 (defun org-remove-keyword-keys (list)
4882 "Remove a pair of parenthesis at the end of each string in LIST."
4883 (mapcar (lambda (x)
4884 (if (string-match "(.*)$" x)
4885 (substring x 0 (match-beginning 0))
4887 list))
4889 (defun org-assign-fast-keys (alist)
4890 "Assign fast keys to a keyword-key alist.
4891 Respect keys that are already there."
4892 (let (new e (alt ?0))
4893 (while (setq e (pop alist))
4894 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4895 (cdr e)) ;; Key already assigned.
4896 (push e new)
4897 (let ((clist (string-to-list (downcase (car e))))
4898 (used (append new alist)))
4899 (when (= (car clist) ?@)
4900 (pop clist))
4901 (while (and clist (rassoc (car clist) used))
4902 (pop clist))
4903 (unless clist
4904 (while (rassoc alt used)
4905 (incf alt)))
4906 (push (cons (car e) (or (car clist) alt)) new))))
4907 (nreverse new)))
4909 ;;; Some variables used in various places
4911 (defvar org-window-configuration nil
4912 "Used in various places to store a window configuration.")
4913 (defvar org-selected-window nil
4914 "Used in various places to store a window configuration.")
4915 (defvar org-finish-function nil
4916 "Function to be called when `C-c C-c' is used.
4917 This is for getting out of special buffers like remember.")
4920 ;; FIXME: Occasionally check by commenting these, to make sure
4921 ;; no other functions uses these, forgetting to let-bind them.
4922 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4923 (defvar org-last-state)
4924 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4926 ;; Defined somewhere in this file, but used before definition.
4927 (defvar org-entities) ;; defined in org-entities.el
4928 (defvar org-struct-menu)
4929 (defvar org-org-menu)
4930 (defvar org-tbl-menu)
4932 ;;;; Define the Org-mode
4934 ;; We use a before-change function to check if a table might need
4935 ;; an update.
4936 (defvar org-table-may-need-update t
4937 "Indicates that a table might need an update.
4938 This variable is set by `org-before-change-function'.
4939 `org-table-align' sets it back to nil.")
4940 (defun org-before-change-function (beg end)
4941 "Every change indicates that a table might need an update."
4942 (setq org-table-may-need-update t))
4943 (defvar org-mode-map)
4944 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4945 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4946 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4947 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4948 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4949 (defvar org-table-buffer-is-an nil)
4951 (defvar bidi-paragraph-direction)
4952 (defvar buffer-face-mode-face)
4954 (require 'outline)
4955 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4956 (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"))
4957 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4959 ;; Other stuff we need.
4960 (require 'time-date)
4961 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4962 (require 'easymenu)
4963 (require 'overlay)
4965 (require 'org-macs)
4966 (require 'org-entities)
4967 (require 'org-compat)
4968 (require 'org-faces)
4969 (require 'org-list)
4970 (require 'org-pcomplete)
4971 (require 'org-src)
4972 (require 'org-footnote)
4973 (require 'org-element)
4975 ;; babel
4976 (require 'ob)
4977 (require 'ob-table)
4978 (require 'ob-lob)
4979 (require 'ob-ref)
4980 (require 'ob-tangle)
4981 (require 'ob-comint)
4982 (require 'ob-keys)
4984 ;;;###autoload
4985 (define-derived-mode org-mode outline-mode "Org"
4986 "Outline-based notes management and organizer, alias
4987 \"Carsten's outline-mode for keeping track of everything.\"
4989 Org-mode develops organizational tasks around a NOTES file which
4990 contains information about projects as plain text. Org-mode is
4991 implemented on top of outline-mode, which is ideal to keep the content
4992 of large files well structured. It supports ToDo items, deadlines and
4993 time stamps, which magically appear in the diary listing of the Emacs
4994 calendar. Tables are easily created with a built-in table editor.
4995 Plain text URL-like links connect to websites, emails (VM), Usenet
4996 messages (Gnus), BBDB entries, and any files related to the project.
4997 For printing and sharing of notes, an Org-mode file (or a part of it)
4998 can be exported as a structured ASCII or HTML file.
5000 The following commands are available:
5002 \\{org-mode-map}"
5004 ;; Get rid of Outline menus, they are not needed
5005 ;; Need to do this here because define-derived-mode sets up
5006 ;; the keymap so late. Still, it is a waste to call this each time
5007 ;; we switch another buffer into org-mode.
5008 (if (featurep 'xemacs)
5009 (when (boundp 'outline-mode-menu-heading)
5010 ;; Assume this is Greg's port, it uses easymenu
5011 (easy-menu-remove outline-mode-menu-heading)
5012 (easy-menu-remove outline-mode-menu-show)
5013 (easy-menu-remove outline-mode-menu-hide))
5014 (define-key org-mode-map [menu-bar headings] 'undefined)
5015 (define-key org-mode-map [menu-bar hide] 'undefined)
5016 (define-key org-mode-map [menu-bar show] 'undefined))
5018 (org-load-modules-maybe)
5019 (easy-menu-add org-org-menu)
5020 (easy-menu-add org-tbl-menu)
5021 (org-install-agenda-files-menu)
5022 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5023 (add-to-invisibility-spec '(org-cwidth))
5024 (add-to-invisibility-spec '(org-hide-block . t))
5025 (when (featurep 'xemacs)
5026 (org-set-local 'line-move-ignore-invisible t))
5027 (org-set-local 'outline-regexp org-outline-regexp)
5028 (org-set-local 'outline-level 'org-outline-level)
5029 (setq bidi-paragraph-direction 'left-to-right)
5030 (when (and org-ellipsis
5031 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5032 (fboundp 'make-glyph-code))
5033 (unless org-display-table
5034 (setq org-display-table (make-display-table)))
5035 (set-display-table-slot
5036 org-display-table 4
5037 (vconcat (mapcar
5038 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5039 org-ellipsis)))
5040 (if (stringp org-ellipsis) org-ellipsis "..."))))
5041 (setq buffer-display-table org-display-table))
5042 (org-set-regexps-and-options)
5043 (when (and org-tag-faces (not org-tags-special-faces-re))
5044 ;; tag faces set outside customize.... force initialization.
5045 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5046 ;; Calc embedded
5047 (org-set-local 'calc-embedded-open-mode "# ")
5048 (modify-syntax-entry ?@ "w")
5049 (if org-startup-truncated (setq truncate-lines t))
5050 (org-set-local 'font-lock-unfontify-region-function
5051 'org-unfontify-region)
5052 ;; Activate before-change-function
5053 (org-set-local 'org-table-may-need-update t)
5054 (org-add-hook 'before-change-functions 'org-before-change-function nil
5055 'local)
5056 ;; Check for running clock before killing a buffer
5057 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5058 ;; Paragraphs and auto-filling
5059 (org-set-autofill-regexps)
5060 (org-set-local 'indent-line-function 'org-indent-line)
5061 (org-set-local 'indent-region-function 'org-indent-region)
5062 (org-update-radio-target-regexp)
5063 ;; Comments
5064 (org-set-local 'comment-use-syntax nil)
5065 (org-set-local 'comment-start "#+")
5066 (org-set-local 'comment-start-skip "\\(?:^#\\|#\\+\\)\\(?: \\|$\\)")
5067 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
5068 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
5069 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region)
5070 ;; Beginning/end of defun
5071 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5072 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5073 ;; Next error for sparse trees
5074 (org-set-local 'next-error-function 'org-occur-next-match)
5075 ;; Make sure dependence stuff works reliably, even for users who set it
5076 ;; too late :-(
5077 (if org-enforce-todo-dependencies
5078 (add-hook 'org-blocker-hook
5079 'org-block-todo-from-children-or-siblings-or-parent)
5080 (remove-hook 'org-blocker-hook
5081 'org-block-todo-from-children-or-siblings-or-parent))
5082 (if org-enforce-todo-checkbox-dependencies
5083 (add-hook 'org-blocker-hook
5084 'org-block-todo-from-checkboxes)
5085 (remove-hook 'org-blocker-hook
5086 'org-block-todo-from-checkboxes))
5088 ;; Align options lines
5089 (org-set-local
5090 'align-mode-rules-list
5091 '((org-in-buffer-settings
5092 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5093 (modes . '(org-mode)))))
5095 ;; Imenu
5096 (org-set-local 'imenu-create-index-function
5097 'org-imenu-get-tree)
5099 ;; Make isearch reveal context
5100 (if (or (featurep 'xemacs)
5101 (not (boundp 'outline-isearch-open-invisible-function)))
5102 ;; Emacs 21 and XEmacs make use of the hook
5103 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5104 ;; Emacs 22 deals with this through a special variable
5105 (org-set-local 'outline-isearch-open-invisible-function
5106 (lambda (&rest ignore) (org-show-context 'isearch))))
5108 ;; Turn on org-beamer-mode?
5109 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5111 ;; Setup the pcomplete hooks
5112 (set (make-local-variable 'pcomplete-command-completion-function)
5113 'org-pcomplete-initial)
5114 (set (make-local-variable 'pcomplete-command-name-function)
5115 'org-command-at-point)
5116 (set (make-local-variable 'pcomplete-default-completion-function)
5117 'ignore)
5118 (set (make-local-variable 'pcomplete-parse-arguments-function)
5119 'org-parse-arguments)
5120 (set (make-local-variable 'pcomplete-termination-string) "")
5121 (when (>= emacs-major-version 23)
5122 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5124 ;; If empty file that did not turn on org-mode automatically, make it to.
5125 (if (and org-insert-mode-line-in-empty-file
5126 (org-called-interactively-p 'any)
5127 (= (point-min) (point-max)))
5128 (insert "# -*- mode: org -*-\n\n"))
5129 (unless org-inhibit-startup
5130 (when org-startup-align-all-tables
5131 (let ((bmp (buffer-modified-p)))
5132 (org-table-map-tables 'org-table-align 'quietly)
5133 (set-buffer-modified-p bmp)))
5134 (when org-startup-with-inline-images
5135 (org-display-inline-images))
5136 (when org-startup-indented
5137 (require 'org-indent)
5138 (org-indent-mode 1))
5139 (unless org-inhibit-startup-visibility-stuff
5140 (org-set-startup-visibility))))
5142 (when (fboundp 'abbrev-table-put)
5143 (abbrev-table-put org-mode-abbrev-table
5144 :parents (list text-mode-abbrev-table)))
5146 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5148 (defun org-current-time ()
5149 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5150 (if (> (car org-time-stamp-rounding-minutes) 1)
5151 (let ((r (car org-time-stamp-rounding-minutes))
5152 (time (decode-time)))
5153 (apply 'encode-time
5154 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5155 (nthcdr 2 time))))
5156 (current-time)))
5158 (defun org-today ()
5159 "Return today date, considering `org-extend-today-until'."
5160 (time-to-days
5161 (time-subtract (current-time)
5162 (list 0 (* 3600 org-extend-today-until) 0))))
5164 ;;;; Font-Lock stuff, including the activators
5166 (defvar org-mouse-map (make-sparse-keymap))
5167 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5168 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5169 (when org-mouse-1-follows-link
5170 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5171 (when org-tab-follows-link
5172 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5173 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5175 (require 'font-lock)
5177 (defconst org-non-link-chars "]\t\n\r<>")
5178 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5179 "shell" "elisp" "doi" "message"))
5180 (defvar org-link-types-re nil
5181 "Matches a link that has a url-like prefix like \"http:\"")
5182 (defvar org-link-re-with-space nil
5183 "Matches a link with spaces, optional angular brackets around it.")
5184 (defvar org-link-re-with-space2 nil
5185 "Matches a link with spaces, optional angular brackets around it.")
5186 (defvar org-link-re-with-space3 nil
5187 "Matches a link with spaces, only for internal part in bracket links.")
5188 (defvar org-angle-link-re nil
5189 "Matches link with angular brackets, spaces are allowed.")
5190 (defvar org-plain-link-re nil
5191 "Matches plain link, without spaces.")
5192 (defvar org-bracket-link-regexp nil
5193 "Matches a link in double brackets.")
5194 (defvar org-bracket-link-analytic-regexp nil
5195 "Regular expression used to analyze links.
5196 Here is what the match groups contain after a match:
5197 1: http:
5198 2: http
5199 3: path
5200 4: [desc]
5201 5: desc")
5202 (defvar org-bracket-link-analytic-regexp++ nil
5203 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5204 (defvar org-any-link-re nil
5205 "Regular expression matching any link.")
5207 (defcustom org-match-sexp-depth 3
5208 "Number of stacked braces for sub/superscript matching.
5209 This has to be set before loading org.el to be effective."
5210 :group 'org-export-translation ; ??????????????????????????/
5211 :type 'integer)
5213 (defun org-create-multibrace-regexp (left right n)
5214 "Create a regular expression which will match a balanced sexp.
5215 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5216 as single character strings.
5217 The regexp returned will match the entire expression including the
5218 delimiters. It will also define a single group which contains the
5219 match except for the outermost delimiters. The maximum depth of
5220 stacked delimiters is N. Escaping delimiters is not possible."
5221 (let* ((nothing (concat "[^" left right "]*?"))
5222 (or "\\|")
5223 (re nothing)
5224 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5225 (while (> n 1)
5226 (setq n (1- n)
5227 re (concat re or next)
5228 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5229 (concat left "\\(" re "\\)" right)))
5231 (defvar org-match-substring-regexp
5232 (concat
5233 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5234 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5235 "\\|"
5236 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5237 "\\|"
5238 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5239 "The regular expression matching a sub- or superscript.")
5241 (defvar org-match-substring-with-braces-regexp
5242 (concat
5243 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5244 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5245 "\\)")
5246 "The regular expression matching a sub- or superscript, forcing braces.")
5248 (defun org-make-link-regexps ()
5249 "Update the link regular expressions.
5250 This should be called after the variable `org-link-types' has changed."
5251 (setq org-link-types-re
5252 (concat
5253 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5254 org-link-re-with-space
5255 (concat
5256 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5257 "\\([^" org-non-link-chars " ]"
5258 "[^" org-non-link-chars "]*"
5259 "[^" org-non-link-chars " ]\\)>?")
5260 org-link-re-with-space2
5261 (concat
5262 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5263 "\\([^" org-non-link-chars " ]"
5264 "[^\t\n\r]*"
5265 "[^" org-non-link-chars " ]\\)>?")
5266 org-link-re-with-space3
5267 (concat
5268 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5269 "\\([^" org-non-link-chars " ]"
5270 "[^\t\n\r]*\\)")
5271 org-angle-link-re
5272 (concat
5273 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5274 "\\([^" org-non-link-chars " ]"
5275 "[^" org-non-link-chars "]*"
5276 "\\)>")
5277 org-plain-link-re
5278 (concat
5279 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5280 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5281 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5282 org-bracket-link-regexp
5283 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5284 org-bracket-link-analytic-regexp
5285 (concat
5286 "\\[\\["
5287 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5288 "\\([^]]+\\)"
5289 "\\]"
5290 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5291 "\\]")
5292 org-bracket-link-analytic-regexp++
5293 (concat
5294 "\\[\\["
5295 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5296 "\\([^]]+\\)"
5297 "\\]"
5298 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5299 "\\]")
5300 org-any-link-re
5301 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5302 org-angle-link-re "\\)\\|\\("
5303 org-plain-link-re "\\)")))
5305 (org-make-link-regexps)
5307 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5308 "Regular expression for fast time stamp matching.")
5309 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5310 "Regular expression for fast time stamp matching.")
5311 (defconst org-ts-regexp0
5312 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5313 "Regular expression matching time strings for analysis.
5314 This one does not require the space after the date, so it can be used
5315 on a string that terminates immediately after the date.")
5316 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5317 "Regular expression matching time strings for analysis.")
5318 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5319 "Regular expression matching time stamps, with groups.")
5320 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5321 "Regular expression matching time stamps (also [..]), with groups.")
5322 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5323 "Regular expression matching a time stamp range.")
5324 (defconst org-tr-regexp-both
5325 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5326 "Regular expression matching a time stamp range.")
5327 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5328 org-ts-regexp "\\)?")
5329 "Regular expression matching a time stamp or time stamp range.")
5330 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5331 org-ts-regexp-both "\\)?")
5332 "Regular expression matching a time stamp or time stamp range.
5333 The time stamps may be either active or inactive.")
5335 (defvar org-emph-face nil)
5337 (defun org-do-emphasis-faces (limit)
5338 "Run through the buffer and add overlays to emphasized strings."
5339 (let (rtn a)
5340 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5341 (if (not (= (char-after (match-beginning 3))
5342 (char-after (match-beginning 4))))
5343 (progn
5344 (setq rtn t)
5345 (setq a (assoc (match-string 3) org-emphasis-alist))
5346 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5347 'face
5348 (nth 1 a))
5349 (and (nth 4 a)
5350 (org-remove-flyspell-overlays-in
5351 (match-beginning 0) (match-end 0)))
5352 (add-text-properties (match-beginning 2) (match-end 2)
5353 '(font-lock-multiline t org-emphasis t))
5354 (when org-hide-emphasis-markers
5355 (add-text-properties (match-end 4) (match-beginning 5)
5356 '(invisible org-link))
5357 (add-text-properties (match-beginning 3) (match-end 3)
5358 '(invisible org-link)))))
5359 (backward-char 1))
5360 rtn))
5362 (defun org-emphasize (&optional char)
5363 "Insert or change an emphasis, i.e. a font like bold or italic.
5364 If there is an active region, change that region to a new emphasis.
5365 If there is no region, just insert the marker characters and position
5366 the cursor between them.
5367 CHAR should be either the marker character, or the first character of the
5368 HTML tag associated with that emphasis. If CHAR is a space, the means
5369 to remove the emphasis of the selected region.
5370 If char is not given (for example in an interactive call) it
5371 will be prompted for."
5372 (interactive)
5373 (let ((eal org-emphasis-alist) e det
5374 (erc org-emphasis-regexp-components)
5375 (prompt "")
5376 (string "") beg end move tag c s)
5377 (if (org-region-active-p)
5378 (setq beg (region-beginning) end (region-end)
5379 string (buffer-substring beg end))
5380 (setq move t))
5382 (while (setq e (pop eal))
5383 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5384 c (aref tag 0))
5385 (push (cons c (string-to-char (car e))) det)
5386 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5387 (substring tag 1)))))
5388 (setq det (nreverse det))
5389 (unless char
5390 (message "%s" (concat "Emphasis marker or tag:" prompt))
5391 (setq char (read-char-exclusive)))
5392 (setq char (or (cdr (assoc char det)) char))
5393 (if (equal char ?\ )
5394 (setq s "" move nil)
5395 (unless (assoc (char-to-string char) org-emphasis-alist)
5396 (error "No such emphasis marker: \"%c\"" char))
5397 (setq s (char-to-string char)))
5398 (while (and (> (length string) 1)
5399 (equal (substring string 0 1) (substring string -1))
5400 (assoc (substring string 0 1) org-emphasis-alist))
5401 (setq string (substring string 1 -1)))
5402 (setq string (concat s string s))
5403 (if beg (delete-region beg end))
5404 (unless (or (bolp)
5405 (string-match (concat "[" (nth 0 erc) "\n]")
5406 (char-to-string (char-before (point)))))
5407 (insert " "))
5408 (unless (or (eobp)
5409 (string-match (concat "[" (nth 1 erc) "\n]")
5410 (char-to-string (char-after (point)))))
5411 (insert " ") (backward-char 1))
5412 (insert string)
5413 (and move (backward-char 1))))
5415 (defconst org-nonsticky-props
5416 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5418 (defsubst org-rear-nonsticky-at (pos)
5419 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5421 (defun org-activate-plain-links (limit)
5422 "Run through the buffer and add overlays to links."
5423 (catch 'exit
5424 (let (f)
5425 (if (re-search-forward org-plain-link-re limit t)
5426 (progn
5427 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5428 (setq f (get-text-property (match-beginning 0) 'face))
5429 (if (or (eq f 'org-tag)
5430 (and (listp f) (memq 'org-tag f)))
5432 (add-text-properties (match-beginning 0) (match-end 0)
5433 (list 'mouse-face 'highlight
5434 'face 'org-link
5435 'keymap org-mouse-map))
5436 (org-rear-nonsticky-at (match-end 0)))
5437 t)))))
5439 (defun org-activate-code (limit)
5440 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5441 (progn
5442 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5443 (remove-text-properties (match-beginning 0) (match-end 0)
5444 '(display t invisible t intangible t))
5445 t)))
5447 (defcustom org-src-fontify-natively nil
5448 "When non-nil, fontify code in code blocks."
5449 :type 'boolean
5450 :version "24.1"
5451 :group 'org-appearance
5452 :group 'org-babel)
5454 (defcustom org-src-prevent-auto-filling nil
5455 "When non-nil, prevent auto-filling in src blocks."
5456 :type 'boolean
5457 :version "24.1"
5458 :group 'org-appearance
5459 :group 'org-babel)
5461 (defcustom org-allow-promoting-top-level-subtree nil
5462 "When non-nil, allow promoting a top level subtree.
5463 The leading star of the top level headline will be replaced
5464 by a #."
5465 :type 'boolean
5466 :version "24.1"
5467 :group 'org-appearance)
5469 (defun org-fontify-meta-lines-and-blocks (limit)
5470 (condition-case nil
5471 (org-fontify-meta-lines-and-blocks-1 limit)
5472 (error (message "org-mode fontification error"))))
5474 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5475 "Fontify #+ lines and blocks, in the correct ways."
5476 (let ((case-fold-search t))
5477 (if (re-search-forward
5478 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5479 limit t)
5480 (let ((beg (match-beginning 0))
5481 (block-start (match-end 0))
5482 (block-end nil)
5483 (lang (match-string 7))
5484 (beg1 (line-beginning-position 2))
5485 (dc1 (downcase (match-string 2)))
5486 (dc3 (downcase (match-string 3)))
5487 end end1 quoting block-type ovl)
5488 (cond
5489 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5490 ;; a single line of backend-specific content
5491 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5492 (remove-text-properties (match-beginning 0) (match-end 0)
5493 '(display t invisible t intangible t))
5494 (add-text-properties (match-beginning 1) (match-end 3)
5495 '(font-lock-fontified t face org-meta-line))
5496 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5497 '(font-lock-fontified t face org-block))
5498 ; for backend-specific code
5500 ((and (match-end 4) (equal dc3 "begin"))
5501 ;; Truly a block
5502 (setq block-type (downcase (match-string 5))
5503 quoting (member block-type org-protecting-blocks))
5504 (when (re-search-forward
5505 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5506 nil t) ;; on purpose, we look further than LIMIT
5507 (setq end (min (point-max) (match-end 0))
5508 end1 (min (point-max) (1- (match-beginning 0))))
5509 (setq block-end (match-beginning 0))
5510 (when quoting
5511 (remove-text-properties beg end
5512 '(display t invisible t intangible t)))
5513 (add-text-properties
5514 beg end
5515 '(font-lock-fontified t font-lock-multiline t))
5516 (add-text-properties beg beg1 '(face org-meta-line))
5517 (add-text-properties end1 (min (point-max) (1+ end))
5518 '(face org-meta-line)) ; for end_src
5519 (cond
5520 ((and lang (not (string= lang "")) org-src-fontify-natively)
5521 (org-src-font-lock-fontify-block lang block-start block-end)
5522 ;; remove old background overlays
5523 (mapc (lambda (ov)
5524 (if (eq (overlay-get ov 'face) 'org-block-background)
5525 (delete-overlay ov)))
5526 (overlays-at (/ (+ beg1 block-end) 2)))
5527 ;; add a background overlay
5528 (setq ovl (make-overlay beg1 block-end))
5529 (overlay-put ovl 'face 'org-block-background)
5530 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5531 (quoting
5532 (add-text-properties beg1 (min (point-max) (1+ end1))
5533 '(face org-block))) ; end of source block
5534 ((not org-fontify-quote-and-verse-blocks))
5535 ((string= block-type "quote")
5536 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5537 ((string= block-type "verse")
5538 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5539 (add-text-properties beg beg1 '(face org-block-begin-line))
5540 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5541 '(face org-block-end-line))
5543 ((member dc1 '("title:" "author:" "email:" "date:"))
5544 (add-text-properties
5545 beg (match-end 3)
5546 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5547 '(font-lock-fontified t invisible t)
5548 '(font-lock-fontified t face org-document-info-keyword)))
5549 (add-text-properties
5550 (match-beginning 6) (match-end 6)
5551 (if (string-equal dc1 "title:")
5552 '(font-lock-fontified t face org-document-title)
5553 '(font-lock-fontified t face org-document-info))))
5554 ((not (member (char-after beg) '(?\ ?\t)))
5555 ;; just any other in-buffer setting, but not indented
5556 (add-text-properties
5557 beg (match-end 0)
5558 '(font-lock-fontified t face org-meta-line))
5560 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5561 "orgtbl:" "tblfm:" "tblname:" "results:"
5562 "call:" "header:" "headers:" "name:"))
5563 (and (match-end 4) (equal dc3 "attr")))
5564 (add-text-properties
5565 beg (match-end 0)
5566 '(font-lock-fontified t face org-meta-line))
5568 ((member dc3 '(" " ""))
5569 (add-text-properties
5570 beg (match-end 0)
5571 '(font-lock-fontified t face font-lock-comment-face)))
5572 (t nil))))))
5574 (defun org-strip-protective-commas (beg end)
5575 "Strip protective commas between BEG and END in the current buffer."
5576 (interactive "r")
5577 (save-excursion
5578 (save-match-data
5579 (goto-char beg)
5580 (let ((front-line (save-excursion
5581 (re-search-forward
5582 "[^[:space:]]" end t)
5583 (goto-char (match-beginning 0))
5584 (current-column))))
5585 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5586 (goto-char (match-beginning 1))
5587 (when (= (current-column) front-line)
5588 (replace-match "" nil nil nil 1)))))))
5590 (defun org-activate-angle-links (limit)
5591 "Run through the buffer and add overlays to links."
5592 (if (re-search-forward org-angle-link-re limit t)
5593 (progn
5594 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5595 (add-text-properties (match-beginning 0) (match-end 0)
5596 (list 'mouse-face 'highlight
5597 'keymap org-mouse-map))
5598 (org-rear-nonsticky-at (match-end 0))
5599 t)))
5601 (defun org-activate-footnote-links (limit)
5602 "Run through the buffer and add overlays to footnotes."
5603 (let ((fn (org-footnote-next-reference-or-definition limit)))
5604 (when fn
5605 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5606 (org-remove-flyspell-overlays-in beg end)
5607 (add-text-properties beg end
5608 (list 'mouse-face 'highlight
5609 'keymap org-mouse-map
5610 'help-echo
5611 (if (= (point-at-bol) beg)
5612 "Footnote definition"
5613 "Footnote reference")
5614 'font-lock-fontified t
5615 'font-lock-multiline t
5616 'face 'org-footnote))))))
5618 (defun org-activate-bracket-links (limit)
5619 "Run through the buffer and add overlays to bracketed links."
5620 (if (re-search-forward org-bracket-link-regexp limit t)
5621 (let* ((help (concat "LINK: "
5622 (org-match-string-no-properties 1)))
5623 ;; FIXME: above we should remove the escapes.
5624 ;; but that requires another match, protecting match data,
5625 ;; a lot of overhead for font-lock.
5626 (ip (org-maybe-intangible
5627 (list 'invisible 'org-link
5628 'keymap org-mouse-map 'mouse-face 'highlight
5629 'font-lock-multiline t 'help-echo help)))
5630 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5631 'font-lock-multiline t 'help-echo help)))
5632 ;; We need to remove the invisible property here. Table narrowing
5633 ;; may have made some of this invisible.
5634 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5635 (remove-text-properties (match-beginning 0) (match-end 0)
5636 '(invisible nil))
5637 (if (match-end 3)
5638 (progn
5639 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5640 (org-rear-nonsticky-at (match-beginning 3))
5641 (add-text-properties (match-beginning 3) (match-end 3) vp)
5642 (org-rear-nonsticky-at (match-end 3))
5643 (add-text-properties (match-end 3) (match-end 0) ip)
5644 (org-rear-nonsticky-at (match-end 0)))
5645 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5646 (org-rear-nonsticky-at (match-beginning 1))
5647 (add-text-properties (match-beginning 1) (match-end 1) vp)
5648 (org-rear-nonsticky-at (match-end 1))
5649 (add-text-properties (match-end 1) (match-end 0) ip)
5650 (org-rear-nonsticky-at (match-end 0)))
5651 t)))
5653 (defun org-activate-dates (limit)
5654 "Run through the buffer and add overlays to dates."
5655 (if (re-search-forward org-tsr-regexp-both limit t)
5656 (progn
5657 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5658 (add-text-properties (match-beginning 0) (match-end 0)
5659 (list 'mouse-face 'highlight
5660 'keymap org-mouse-map))
5661 (org-rear-nonsticky-at (match-end 0))
5662 (when org-display-custom-times
5663 (if (match-end 3)
5664 (org-display-custom-time (match-beginning 3) (match-end 3)))
5665 (org-display-custom-time (match-beginning 1) (match-end 1)))
5666 t)))
5668 (defvar org-target-link-regexp nil
5669 "Regular expression matching radio targets in plain text.")
5670 (make-variable-buffer-local 'org-target-link-regexp)
5671 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5672 "Regular expression matching a link target.")
5673 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5674 "Regular expression matching a radio target.")
5675 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5676 "Regular expression matching any target.")
5678 (defun org-activate-target-links (limit)
5679 "Run through the buffer and add overlays to target matches."
5680 (when org-target-link-regexp
5681 (let ((case-fold-search t))
5682 (if (re-search-forward org-target-link-regexp limit t)
5683 (progn
5684 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5685 (add-text-properties (match-beginning 0) (match-end 0)
5686 (list 'mouse-face 'highlight
5687 'keymap org-mouse-map
5688 'help-echo "Radio target link"
5689 'org-linked-text t))
5690 (org-rear-nonsticky-at (match-end 0))
5691 t)))))
5693 (defun org-update-radio-target-regexp ()
5694 "Find all radio targets in this file and update the regular expression."
5695 (interactive)
5696 (when (memq 'radio org-activate-links)
5697 (setq org-target-link-regexp
5698 (org-make-target-link-regexp (org-all-targets 'radio)))
5699 (org-restart-font-lock)))
5701 (defun org-hide-wide-columns (limit)
5702 (let (s e)
5703 (setq s (text-property-any (point) (or limit (point-max))
5704 'org-cwidth t))
5705 (when s
5706 (setq e (next-single-property-change s 'org-cwidth))
5707 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5708 (goto-char e)
5709 t)))
5711 (defvar org-latex-and-specials-regexp nil
5712 "Regular expression for highlighting export special stuff.")
5713 (defvar org-match-substring-regexp)
5714 (defvar org-match-substring-with-braces-regexp)
5716 ;; This should be with the exporter code, but we also use if for font-locking
5717 (defconst org-export-html-special-string-regexps
5718 '(("\\\\-" . "&shy;")
5719 ("---\\([^-]\\)" . "&mdash;\\1")
5720 ("--\\([^-]\\)" . "&ndash;\\1")
5721 ("\\.\\.\\." . "&hellip;"))
5722 "Regular expressions for special string conversion.")
5725 (defun org-compute-latex-and-specials-regexp ()
5726 "Compute regular expression for stuff treated specially by exporters."
5727 (if (not org-highlight-latex-fragments-and-specials)
5728 (org-set-local 'org-latex-and-specials-regexp nil)
5729 (require 'org-exp)
5730 (let*
5731 ((matchers (plist-get org-format-latex-options :matchers))
5732 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5733 org-latex-regexps)))
5734 (org-export-allow-BIND nil)
5735 (options (org-combine-plists (org-default-export-plist)
5736 (org-infile-export-plist)))
5737 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5738 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5739 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5740 (org-export-html-expand (plist-get options :expand-quoted-html))
5741 (org-export-with-special-strings (plist-get options :special-strings))
5742 (re-sub
5743 (cond
5744 ((equal org-export-with-sub-superscripts '{})
5745 (list org-match-substring-with-braces-regexp))
5746 (org-export-with-sub-superscripts
5747 (list org-match-substring-regexp))
5748 (t nil)))
5749 (re-latex
5750 (if org-export-with-LaTeX-fragments
5751 (mapcar (lambda (x) (nth 1 x)) latexs)))
5752 (re-macros
5753 (if org-export-with-TeX-macros
5754 (list (concat "\\\\"
5755 (regexp-opt
5756 (append
5758 (delq nil
5759 (mapcar 'car-safe
5760 (append org-entities-user
5761 org-entities)))
5762 (if (boundp 'org-latex-entities)
5763 (mapcar (lambda (x)
5764 (or (car-safe x) x))
5765 org-latex-entities)
5766 nil))
5767 'words))) ; FIXME
5769 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5770 (re-special (if org-export-with-special-strings
5771 (mapcar (lambda (x) (car x))
5772 org-export-html-special-string-regexps)))
5773 (re-rest
5774 (delq nil
5775 (list
5776 (if org-export-html-expand "@<[^>\n]+>")
5777 ))))
5778 (org-set-local
5779 'org-latex-and-specials-regexp
5780 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5781 re-rest) "\\|")))))
5783 (defun org-do-latex-and-special-faces (limit)
5784 "Run through the buffer and add overlays to links."
5785 (when org-latex-and-specials-regexp
5786 (let (rtn d)
5787 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5788 limit t))
5789 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5790 'face))
5791 '(org-code org-verbatim underline)))
5792 (progn
5793 (setq rtn t
5794 d (cond ((member (char-after (1+ (match-beginning 0)))
5795 '(?_ ?^)) 1)
5796 (t 0)))
5797 (font-lock-prepend-text-property
5798 (+ d (match-beginning 0)) (match-end 0)
5799 'face 'org-latex-and-export-specials)
5800 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5801 '(font-lock-multiline t)))))
5802 rtn)))
5804 (defun org-restart-font-lock ()
5805 "Restart `font-lock-mode', to force refontification."
5806 (when (and (boundp 'font-lock-mode) font-lock-mode)
5807 (font-lock-mode -1)
5808 (font-lock-mode 1)))
5810 (defun org-all-targets (&optional radio)
5811 "Return a list of all targets in this file.
5812 With optional argument RADIO, only find radio targets."
5813 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5814 rtn)
5815 (save-excursion
5816 (goto-char (point-min))
5817 (while (re-search-forward re nil t)
5818 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5819 rtn)))
5821 (defun org-make-target-link-regexp (targets)
5822 "Make regular expression matching all strings in TARGETS.
5823 The regular expression finds the targets also if there is a line break
5824 between words."
5825 (and targets
5826 (concat
5827 "\\<\\("
5828 (mapconcat
5829 (lambda (x)
5830 (setq x (regexp-quote x))
5831 (while (string-match " +" x)
5832 (setq x (replace-match "\\s-+" t t x)))
5834 targets
5835 "\\|")
5836 "\\)\\>")))
5838 (defun org-activate-tags (limit)
5839 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5840 (progn
5841 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5842 (add-text-properties (match-beginning 1) (match-end 1)
5843 (list 'mouse-face 'highlight
5844 'keymap org-mouse-map))
5845 (org-rear-nonsticky-at (match-end 1))
5846 t)))
5848 (defun org-outline-level ()
5849 "Compute the outline level of the heading at point.
5850 This function assumes that the cursor is at the beginning of a line matched
5851 by `outline-regexp'. Otherwise it returns garbage.
5852 If this is called at a normal headline, the level is the number of stars.
5853 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5854 (save-excursion
5855 (looking-at org-outline-regexp)
5856 (1- (- (match-end 0) (match-beginning 0)))))
5858 (defvar org-font-lock-keywords nil)
5860 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5861 "Regular expression matching a property line.")
5863 (defvar org-font-lock-hook nil
5864 "Functions to be called for special font lock stuff.")
5866 (defvar org-font-lock-set-keywords-hook nil
5867 "Functions that can manipulate `org-font-lock-extra-keywords'.
5868 This is called after `org-font-lock-extra-keywords' is defined, but before
5869 it is installed to be used by font lock. This can be useful if something
5870 needs to be inserted at a specific position in the font-lock sequence.")
5872 (defun org-font-lock-hook (limit)
5873 (run-hook-with-args 'org-font-lock-hook limit))
5875 (defun org-set-font-lock-defaults ()
5876 (let* ((em org-fontify-emphasized-text)
5877 (lk org-activate-links)
5878 (org-font-lock-extra-keywords
5879 (list
5880 ;; Call the hook
5881 '(org-font-lock-hook)
5882 ;; Headlines
5883 `(,(if org-fontify-whole-heading-line
5884 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5885 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5886 (1 (org-get-level-face 1))
5887 (2 (org-get-level-face 2))
5888 (3 (org-get-level-face 3)))
5889 ;; Table lines
5890 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5891 (1 'org-table t))
5892 ;; Table internals
5893 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5894 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5895 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5896 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5897 ;; Drawers
5898 (list org-drawer-regexp '(0 'org-special-keyword t))
5899 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5900 ;; Properties
5901 (list org-property-re
5902 '(1 'org-special-keyword t)
5903 '(3 'org-property-value t))
5904 ;; Links
5905 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5906 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5907 (if (memq 'plain lk) '(org-activate-plain-links))
5908 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5909 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5910 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5911 (if (memq 'footnote lk) '(org-activate-footnote-links))
5912 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5913 '(org-hide-wide-columns (0 nil append))
5914 ;; TODO keyword
5915 (list (format org-heading-keyword-regexp-format
5916 org-todo-regexp)
5917 '(2 (org-get-todo-face 2) t))
5918 ;; DONE
5919 (if org-fontify-done-headline
5920 (list (format org-heading-keyword-regexp-format
5921 (concat
5922 "\\(?:"
5923 (mapconcat 'regexp-quote org-done-keywords "\\|")
5924 "\\)"))
5925 '(2 'org-headline-done t))
5926 nil)
5927 ;; Priorities
5928 '(org-font-lock-add-priority-faces)
5929 ;; Tags
5930 '(org-font-lock-add-tag-faces)
5931 ;; Special keywords
5932 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5933 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5934 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5935 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5936 ;; Emphasis
5937 (if em
5938 (if (featurep 'xemacs)
5939 '(org-do-emphasis-faces (0 nil append))
5940 '(org-do-emphasis-faces)))
5941 ;; Checkboxes
5942 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5943 1 'org-checkbox prepend)
5944 (if (cdr (assq 'checkbox org-list-automatic-rules))
5945 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5946 (0 (org-get-checkbox-statistics-face) t)))
5947 ;; Description list items
5948 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5949 1 'org-list-dt prepend)
5950 ;; ARCHIVEd headings
5951 (list (concat
5952 org-outline-regexp-bol
5953 "\\(.*:" org-archive-tag ":.*\\)")
5954 '(1 'org-archived prepend))
5955 ;; Specials
5956 '(org-do-latex-and-special-faces)
5957 '(org-fontify-entities)
5958 '(org-raise-scripts)
5959 ;; Code
5960 '(org-activate-code (1 'org-code t))
5961 ;; COMMENT
5962 (list (format org-heading-keyword-regexp-format
5963 (concat "\\("
5964 org-comment-string "\\|" org-quote-string
5965 "\\)"))
5966 '(2 'org-special-keyword t))
5967 '("^#.*" (0 'font-lock-comment-face t))
5968 ;; Blocks and meta lines
5969 '(org-fontify-meta-lines-and-blocks)
5971 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5972 (run-hooks 'org-font-lock-set-keywords-hook)
5973 ;; Now set the full font-lock-keywords
5974 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5975 (org-set-local 'font-lock-defaults
5976 '(org-font-lock-keywords t nil nil backward-paragraph))
5977 (kill-local-variable 'font-lock-keywords) nil))
5979 (defun org-toggle-pretty-entities ()
5980 "Toggle the composition display of entities as UTF8 characters."
5981 (interactive)
5982 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5983 (org-restart-font-lock)
5984 (if org-pretty-entities
5985 (message "Entities are displayed as UTF8 characters")
5986 (save-restriction
5987 (widen)
5988 (org-decompose-region (point-min) (point-max))
5989 (message "Entities are displayed plain"))))
5991 (defun org-fontify-entities (limit)
5992 "Find an entity to fontify."
5993 (let (ee)
5994 (when org-pretty-entities
5995 (catch 'match
5996 (while (re-search-forward
5997 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5998 limit t)
5999 (if (and (not (org-in-indented-comment-line))
6000 (setq ee (org-entity-get (match-string 1)))
6001 (= (length (nth 6 ee)) 1))
6002 (let*
6003 ((end (if (equal (match-string 2) "{}")
6004 (match-end 2)
6005 (match-end 1))))
6006 (add-text-properties
6007 (match-beginning 0) end
6008 (list 'font-lock-fontified t))
6009 (compose-region (match-beginning 0) end
6010 (nth 6 ee) nil)
6011 (backward-char 1)
6012 (throw 'match t))))
6013 nil))))
6015 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6016 "Fontify string S like in Org-mode."
6017 (with-temp-buffer
6018 (insert s)
6019 (let ((org-odd-levels-only odd-levels))
6020 (org-mode)
6021 (font-lock-fontify-buffer)
6022 (buffer-string))))
6024 (defvar org-m nil)
6025 (defvar org-l nil)
6026 (defvar org-f nil)
6027 (defun org-get-level-face (n)
6028 "Get the right face for match N in font-lock matching of headlines."
6029 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6030 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6031 (if org-cycle-level-faces
6032 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6033 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6034 (cond
6035 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6036 ((eq n 2) org-f)
6037 (t (if org-level-color-stars-only nil org-f))))
6040 (defun org-get-todo-face (kwd)
6041 "Get the right face for a TODO keyword KWD.
6042 If KWD is a number, get the corresponding match group."
6043 (if (numberp kwd) (setq kwd (match-string kwd)))
6044 (or (org-face-from-face-or-color
6045 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6046 (and (member kwd org-done-keywords) 'org-done)
6047 'org-todo))
6049 (defun org-face-from-face-or-color (context inherit face-or-color)
6050 "Create a face list that inherits INHERIT, but sets the foreground color.
6051 When FACE-OR-COLOR is not a string, just return it."
6052 (if (stringp face-or-color)
6053 (list :inherit inherit
6054 (cdr (assoc context org-faces-easy-properties))
6055 face-or-color)
6056 face-or-color))
6058 (defun org-font-lock-add-tag-faces (limit)
6059 "Add the special tag faces."
6060 (when (and org-tag-faces org-tags-special-faces-re)
6061 (while (re-search-forward org-tags-special-faces-re limit t)
6062 (add-text-properties (match-beginning 1) (match-end 1)
6063 (list 'face (org-get-tag-face 1)
6064 'font-lock-fontified t))
6065 (backward-char 1))))
6067 (defun org-font-lock-add-priority-faces (limit)
6068 "Add the special priority faces."
6069 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6070 (when (save-match-data (org-at-heading-p))
6071 (add-text-properties
6072 (match-beginning 0) (match-end 0)
6073 (list 'face (or (org-face-from-face-or-color
6074 'priority 'org-special-keyword
6075 (cdr (assoc (char-after (match-beginning 1))
6076 org-priority-faces)))
6077 'org-special-keyword)
6078 'font-lock-fontified t)))))
6080 (defun org-get-tag-face (kwd)
6081 "Get the right face for a TODO keyword KWD.
6082 If KWD is a number, get the corresponding match group."
6083 (if (numberp kwd) (setq kwd (match-string kwd)))
6084 (or (org-face-from-face-or-color
6085 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6086 'org-tag))
6088 (defun org-unfontify-region (beg end &optional maybe_loudly)
6089 "Remove fontification and activation overlays from links."
6090 (font-lock-default-unfontify-region beg end)
6091 (let* ((buffer-undo-list t)
6092 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6093 (inhibit-modification-hooks t)
6094 deactivate-mark buffer-file-name buffer-file-truename)
6095 (org-decompose-region beg end)
6096 (remove-text-properties beg end
6097 '(mouse-face t keymap t org-linked-text t
6098 invisible t intangible t
6099 org-no-flyspell t org-emphasis t))
6100 (org-remove-font-lock-display-properties beg end)))
6102 (defconst org-script-display '(((raise -0.3) (height 0.7))
6103 ((raise 0.3) (height 0.7))
6104 ((raise -0.5))
6105 ((raise 0.5)))
6106 "Display properties for showing superscripts and subscripts.")
6108 (defun org-remove-font-lock-display-properties (beg end)
6109 "Remove specific display properties that have been added by font lock.
6110 The will remove the raise properties that are used to show superscripts
6111 and subscripts."
6112 (let (next prop)
6113 (while (< beg end)
6114 (setq next (next-single-property-change beg 'display nil end)
6115 prop (get-text-property beg 'display))
6116 (if (member prop org-script-display)
6117 (put-text-property beg next 'display nil))
6118 (setq beg next))))
6120 (defun org-raise-scripts (limit)
6121 "Add raise properties to sub/superscripts."
6122 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6123 (if (re-search-forward
6124 (if (eq org-use-sub-superscripts t)
6125 org-match-substring-regexp
6126 org-match-substring-with-braces-regexp)
6127 limit t)
6128 (let* ((pos (point)) table-p comment-p
6129 (mpos (match-beginning 3))
6130 (emph-p (get-text-property mpos 'org-emphasis))
6131 (link-p (get-text-property mpos 'mouse-face))
6132 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6133 (goto-char (point-at-bol))
6134 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6135 comment-p (org-looking-at-p "[ \t]*#"))
6136 (goto-char pos)
6137 ;; FIXME: Should we go back one character here, for a_b^c
6138 ;; (goto-char (1- pos)) ;????????????????????
6139 (if (or comment-p emph-p link-p keyw-p)
6141 (put-text-property (match-beginning 3) (match-end 0)
6142 'display
6143 (if (equal (char-after (match-beginning 2)) ?^)
6144 (nth (if table-p 3 1) org-script-display)
6145 (nth (if table-p 2 0) org-script-display)))
6146 (add-text-properties (match-beginning 2) (match-end 2)
6147 (list 'invisible t
6148 'org-dwidth t 'org-dwidth-n 1))
6149 (if (and (eq (char-after (match-beginning 3)) ?{)
6150 (eq (char-before (match-end 3)) ?}))
6151 (progn
6152 (add-text-properties
6153 (match-beginning 3) (1+ (match-beginning 3))
6154 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6155 (add-text-properties
6156 (1- (match-end 3)) (match-end 3)
6157 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6158 t)))))
6160 ;;;; Visibility cycling, including org-goto and indirect buffer
6162 ;;; Cycling
6164 (defvar org-cycle-global-status nil)
6165 (make-variable-buffer-local 'org-cycle-global-status)
6166 (defvar org-cycle-subtree-status nil)
6167 (make-variable-buffer-local 'org-cycle-subtree-status)
6169 ;;;###autoload
6171 (defvar org-inlinetask-min-level)
6173 (defun org-cycle (&optional arg)
6174 "TAB-action and visibility cycling for Org-mode.
6176 This is the command invoked in Org-mode by the TAB key. Its main purpose
6177 is outline visibility cycling, but it also invokes other actions
6178 in special contexts.
6180 - When this function is called with a prefix argument, rotate the entire
6181 buffer through 3 states (global cycling)
6182 1. OVERVIEW: Show only top-level headlines.
6183 2. CONTENTS: Show all headlines of all levels, but no body text.
6184 3. SHOW ALL: Show everything.
6185 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6186 determined by the variable `org-startup-folded', and by any VISIBILITY
6187 properties in the buffer.
6188 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6189 including any drawers.
6191 - When inside a table, re-align the table and move to the next field.
6193 - When point is at the beginning of a headline, rotate the subtree started
6194 by this line through 3 different states (local cycling)
6195 1. FOLDED: Only the main headline is shown.
6196 2. CHILDREN: The main headline and the direct children are shown.
6197 From this state, you can move to one of the children
6198 and zoom in further.
6199 3. SUBTREE: Show the entire subtree, including body text.
6200 If there is no subtree, switch directly from CHILDREN to FOLDED.
6202 - When point is at the beginning of an empty headline and the variable
6203 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6204 of the headline by demoting and promoting it to likely levels. This
6205 speeds up creation document structure by pressing TAB once or several
6206 times right after creating a new headline.
6208 - When there is a numeric prefix, go up to a heading with level ARG, do
6209 a `show-subtree' and return to the previous cursor position. If ARG
6210 is negative, go up that many levels.
6212 - When point is not at the beginning of a headline, execute the global
6213 binding for TAB, which is re-indenting the line. See the option
6214 `org-cycle-emulate-tab' for details.
6216 - Special case: if point is at the beginning of the buffer and there is
6217 no headline in line 1, this function will act as if called with prefix arg
6218 (C-u TAB, same as S-TAB) also when called without prefix arg.
6219 But only if also the variable `org-cycle-global-at-bob' is t."
6220 (interactive "P")
6221 (org-load-modules-maybe)
6222 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6223 (and org-cycle-level-after-item/entry-creation
6224 (or (org-cycle-level)
6225 (org-cycle-item-indentation))))
6226 (let* ((limit-level
6227 (or org-cycle-max-level
6228 (and (boundp 'org-inlinetask-min-level)
6229 org-inlinetask-min-level
6230 (1- org-inlinetask-min-level))))
6231 (nstars (and limit-level
6232 (if org-odd-levels-only
6233 (and limit-level (1- (* limit-level 2)))
6234 limit-level)))
6235 (org-outline-regexp
6236 (if (not (derived-mode-p 'org-mode))
6237 outline-regexp
6238 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6239 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6240 (not (looking-at org-outline-regexp))))
6241 (org-cycle-hook
6242 (if bob-special
6243 (delq 'org-optimize-window-after-visibility-change
6244 (copy-sequence org-cycle-hook))
6245 org-cycle-hook))
6246 (pos (point)))
6248 (if (or bob-special (equal arg '(4)))
6249 ;; special case: use global cycling
6250 (setq arg t))
6252 (cond
6254 ((equal arg '(16))
6255 (setq last-command 'dummy)
6256 (org-set-startup-visibility)
6257 (message "Startup visibility, plus VISIBILITY properties"))
6259 ((equal arg '(64))
6260 (show-all)
6261 (message "Entire buffer visible, including drawers"))
6263 ;; Table: enter it or move to the next field.
6264 ((org-at-table-p 'any)
6265 (if (org-at-table.el-p)
6266 (message "Use C-c ' to edit table.el tables")
6267 (if arg (org-table-edit-field t)
6268 (org-table-justify-field-maybe)
6269 (call-interactively 'org-table-next-field))))
6271 ((run-hook-with-args-until-success
6272 'org-tab-after-check-for-table-hook))
6274 ;; Global cycling: delegate to `org-cycle-internal-global'.
6275 ((eq arg t) (org-cycle-internal-global))
6277 ;; Drawers: delegate to `org-flag-drawer'.
6278 ((and org-drawers org-drawer-regexp
6279 (save-excursion
6280 (beginning-of-line 1)
6281 (looking-at org-drawer-regexp)))
6282 (org-flag-drawer ; toggle block visibility
6283 (not (get-char-property (match-end 0) 'invisible))))
6285 ;; Show-subtree, ARG levels up from here.
6286 ((integerp arg)
6287 (save-excursion
6288 (org-back-to-heading)
6289 (outline-up-heading (if (< arg 0) (- arg)
6290 (- (funcall outline-level) arg)))
6291 (org-show-subtree)))
6293 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6294 ((and (featurep 'org-inlinetask)
6295 (org-inlinetask-at-task-p)
6296 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6297 (org-inlinetask-toggle-visibility))
6299 ((org-try-cdlatex-tab))
6301 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6302 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6303 (save-excursion (beginning-of-line 1)
6304 (looking-at org-outline-regexp)))
6305 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6306 (org-cycle-internal-local))
6308 ;; From there: TAB emulation and template completion.
6309 (buffer-read-only (org-back-to-heading))
6311 ((run-hook-with-args-until-success
6312 'org-tab-after-check-for-cycling-hook))
6314 ((org-try-structure-completion))
6316 ((run-hook-with-args-until-success
6317 'org-tab-before-tab-emulation-hook))
6319 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6320 (or (not (bolp))
6321 (not (looking-at org-outline-regexp))))
6322 (call-interactively (global-key-binding "\t")))
6324 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6325 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6326 (or (and (eq org-cycle-emulate-tab 'white)
6327 (= (match-end 0) (point-at-eol)))
6328 (and (eq org-cycle-emulate-tab 'whitestart)
6329 (>= (match-end 0) pos))))
6331 (eq org-cycle-emulate-tab t))
6332 (call-interactively (global-key-binding "\t")))
6334 (t (save-excursion
6335 (org-back-to-heading)
6336 (org-cycle)))))))
6338 (defun org-cycle-internal-global ()
6339 "Do the global cycling action."
6340 ;; Hack to avoid display of messages for .org attachments in Gnus
6341 (let ((ga (string-match "\\*fontification" (buffer-name))))
6342 (cond
6343 ((and (eq last-command this-command)
6344 (eq org-cycle-global-status 'overview))
6345 ;; We just created the overview - now do table of contents
6346 ;; This can be slow in very large buffers, so indicate action
6347 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6348 (unless ga (message "CONTENTS..."))
6349 (org-content)
6350 (unless ga (message "CONTENTS...done"))
6351 (setq org-cycle-global-status 'contents)
6352 (run-hook-with-args 'org-cycle-hook 'contents))
6354 ((and (eq last-command this-command)
6355 (eq org-cycle-global-status 'contents))
6356 ;; We just showed the table of contents - now show everything
6357 (run-hook-with-args 'org-pre-cycle-hook 'all)
6358 (show-all)
6359 (unless ga (message "SHOW ALL"))
6360 (setq org-cycle-global-status 'all)
6361 (run-hook-with-args 'org-cycle-hook 'all))
6364 ;; Default action: go to overview
6365 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6366 (org-overview)
6367 (unless ga (message "OVERVIEW"))
6368 (setq org-cycle-global-status 'overview)
6369 (run-hook-with-args 'org-cycle-hook 'overview)))))
6371 (defun org-cycle-internal-local ()
6372 "Do the local cycling action."
6373 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6374 ;; First, determine end of headline (EOH), end of subtree or item
6375 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6376 (save-excursion
6377 (if (org-at-item-p)
6378 (progn
6379 (beginning-of-line)
6380 (setq struct (org-list-struct))
6381 (setq eoh (point-at-eol))
6382 (setq eos (org-list-get-item-end-before-blank (point) struct))
6383 (setq has-children (org-list-has-child-p (point) struct)))
6384 (org-back-to-heading)
6385 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6386 (setq eos (save-excursion
6387 (org-end-of-subtree t)
6388 (unless (eobp)
6389 (skip-chars-forward " \t\n"))
6390 (if (eobp) (point) (1- (point)))))
6391 (setq has-children
6392 (or (save-excursion
6393 (let ((level (funcall outline-level)))
6394 (outline-next-heading)
6395 (and (org-at-heading-p t)
6396 (> (funcall outline-level) level))))
6397 (save-excursion
6398 (org-list-search-forward (org-item-beginning-re) eos t)))))
6399 ;; Determine end invisible part of buffer (EOL)
6400 (beginning-of-line 2)
6401 ;; XEmacs doesn't have `next-single-char-property-change'
6402 (if (featurep 'xemacs)
6403 (while (and (not (eobp)) ;; this is like `next-line'
6404 (get-char-property (1- (point)) 'invisible))
6405 (beginning-of-line 2))
6406 (while (and (not (eobp)) ;; this is like `next-line'
6407 (get-char-property (1- (point)) 'invisible))
6408 (goto-char (next-single-char-property-change (point) 'invisible))
6409 (and (eolp) (beginning-of-line 2))))
6410 (setq eol (point)))
6411 ;; Find out what to do next and set `this-command'
6412 (cond
6413 ((= eos eoh)
6414 ;; Nothing is hidden behind this heading
6415 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6416 (message "EMPTY ENTRY")
6417 (setq org-cycle-subtree-status nil)
6418 (save-excursion
6419 (goto-char eos)
6420 (outline-next-heading)
6421 (if (outline-invisible-p) (org-flag-heading nil))))
6422 ((and (or (>= eol eos)
6423 (not (string-match "\\S-" (buffer-substring eol eos))))
6424 (or has-children
6425 (not (setq children-skipped
6426 org-cycle-skip-children-state-if-no-children))))
6427 ;; Entire subtree is hidden in one line: children view
6428 (run-hook-with-args 'org-pre-cycle-hook 'children)
6429 (if (org-at-item-p)
6430 (org-list-set-item-visibility (point-at-bol) struct 'children)
6431 (org-show-entry)
6432 (org-with-limited-levels (show-children))
6433 ;; FIXME: This slows down the func way too much.
6434 ;; How keep drawers hidden in subtree anyway?
6435 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6436 ;; (org-cycle-hide-drawers 'subtree))
6438 ;; Fold every list in subtree to top-level items.
6439 (when (eq org-cycle-include-plain-lists 'integrate)
6440 (save-excursion
6441 (org-back-to-heading)
6442 (while (org-list-search-forward (org-item-beginning-re) eos t)
6443 (beginning-of-line 1)
6444 (let* ((struct (org-list-struct))
6445 (prevs (org-list-prevs-alist struct))
6446 (end (org-list-get-bottom-point struct)))
6447 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6448 (org-list-get-all-items (point) struct prevs))
6449 (goto-char end))))))
6450 (message "CHILDREN")
6451 (save-excursion
6452 (goto-char eos)
6453 (outline-next-heading)
6454 (if (outline-invisible-p) (org-flag-heading nil)))
6455 (setq org-cycle-subtree-status 'children)
6456 (run-hook-with-args 'org-cycle-hook 'children))
6457 ((or children-skipped
6458 (and (eq last-command this-command)
6459 (eq org-cycle-subtree-status 'children)))
6460 ;; We just showed the children, or no children are there,
6461 ;; now show everything.
6462 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6463 (outline-flag-region eoh eos nil)
6464 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6465 (setq org-cycle-subtree-status 'subtree)
6466 (run-hook-with-args 'org-cycle-hook 'subtree))
6468 ;; Default action: hide the subtree.
6469 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6470 (outline-flag-region eoh eos t)
6471 (message "FOLDED")
6472 (setq org-cycle-subtree-status 'folded)
6473 (run-hook-with-args 'org-cycle-hook 'folded)))))
6475 ;;;###autoload
6476 (defun org-global-cycle (&optional arg)
6477 "Cycle the global visibility. For details see `org-cycle'.
6478 With \\[universal-argument] prefix arg, switch to startup visibility.
6479 With a numeric prefix, show all headlines up to that level."
6480 (interactive "P")
6481 (let ((org-cycle-include-plain-lists
6482 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6483 (cond
6484 ((integerp arg)
6485 (show-all)
6486 (hide-sublevels arg)
6487 (setq org-cycle-global-status 'contents))
6488 ((equal arg '(4))
6489 (org-set-startup-visibility)
6490 (message "Startup visibility, plus VISIBILITY properties."))
6492 (org-cycle '(4))))))
6494 (defun org-set-startup-visibility ()
6495 "Set the visibility required by startup options and properties."
6496 (cond
6497 ((eq org-startup-folded t)
6498 (org-cycle '(4)))
6499 ((eq org-startup-folded 'content)
6500 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6501 (org-cycle '(4)) (org-cycle '(4)))))
6502 (unless (eq org-startup-folded 'showeverything)
6503 (if org-hide-block-startup (org-hide-block-all))
6504 (org-set-visibility-according-to-property 'no-cleanup)
6505 (org-cycle-hide-archived-subtrees 'all)
6506 (org-cycle-hide-drawers 'all)
6507 (org-cycle-show-empty-lines t)))
6509 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6510 "Switch subtree visibilities according to :VISIBILITY: property."
6511 (interactive)
6512 (let (org-show-entry-below state)
6513 (save-excursion
6514 (goto-char (point-min))
6515 (while (re-search-forward
6516 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6517 nil t)
6518 (setq state (match-string 1))
6519 (save-excursion
6520 (org-back-to-heading t)
6521 (hide-subtree)
6522 (org-reveal)
6523 (cond
6524 ((equal state '("fold" "folded"))
6525 (hide-subtree))
6526 ((equal state "children")
6527 (org-show-hidden-entry)
6528 (show-children))
6529 ((equal state "content")
6530 (save-excursion
6531 (save-restriction
6532 (org-narrow-to-subtree)
6533 (org-content))))
6534 ((member state '("all" "showall"))
6535 (show-subtree)))))
6536 (unless no-cleanup
6537 (org-cycle-hide-archived-subtrees 'all)
6538 (org-cycle-hide-drawers 'all)
6539 (org-cycle-show-empty-lines 'all)))))
6541 ;; This function uses outline-regexp instead of the more fundamental
6542 ;; org-outline-regexp so that org-cycle-global works outside of Org
6543 ;; buffers, where outline-regexp is needed.
6544 (defun org-overview ()
6545 "Switch to overview mode, showing only top-level headlines.
6546 Really, this shows all headlines with level equal or greater than the level
6547 of the first headline in the buffer. This is important, because if the
6548 first headline is not level one, then (hide-sublevels 1) gives confusing
6549 results."
6550 (interactive)
6551 (let ((level (save-excursion
6552 (goto-char (point-min))
6553 (if (re-search-forward (concat "^" outline-regexp) nil t)
6554 (progn
6555 (goto-char (match-beginning 0))
6556 (funcall outline-level))))))
6557 (and level (hide-sublevels level))))
6559 (defun org-content (&optional arg)
6560 "Show all headlines in the buffer, like a table of contents.
6561 With numerical argument N, show content up to level N."
6562 (interactive "P")
6563 (save-excursion
6564 ;; Visit all headings and show their offspring
6565 (and (integerp arg) (org-overview))
6566 (goto-char (point-max))
6567 (catch 'exit
6568 (while (and (progn (condition-case nil
6569 (outline-previous-visible-heading 1)
6570 (error (goto-char (point-min))))
6572 (looking-at org-outline-regexp))
6573 (if (integerp arg)
6574 (show-children (1- arg))
6575 (show-branches))
6576 (if (bobp) (throw 'exit nil))))))
6579 (defun org-optimize-window-after-visibility-change (state)
6580 "Adjust the window after a change in outline visibility.
6581 This function is the default value of the hook `org-cycle-hook'."
6582 (when (get-buffer-window (current-buffer))
6583 (cond
6584 ((eq state 'content) nil)
6585 ((eq state 'all) nil)
6586 ((eq state 'folded) nil)
6587 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6588 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6590 (defun org-remove-empty-overlays-at (pos)
6591 "Remove outline overlays that do not contain non-white stuff."
6592 (mapc
6593 (lambda (o)
6594 (and (eq 'outline (overlay-get o 'invisible))
6595 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6596 (overlay-end o))))
6597 (delete-overlay o)))
6598 (overlays-at pos)))
6600 (defun org-clean-visibility-after-subtree-move ()
6601 "Fix visibility issues after moving a subtree."
6602 ;; First, find a reasonable region to look at:
6603 ;; Start two siblings above, end three below
6604 (let* ((beg (save-excursion
6605 (and (org-get-last-sibling)
6606 (org-get-last-sibling))
6607 (point)))
6608 (end (save-excursion
6609 (and (org-get-next-sibling)
6610 (org-get-next-sibling)
6611 (org-get-next-sibling))
6612 (if (org-at-heading-p)
6613 (point-at-eol)
6614 (point))))
6615 (level (looking-at "\\*+"))
6616 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6617 (save-excursion
6618 (save-restriction
6619 (narrow-to-region beg end)
6620 (when re
6621 ;; Properly fold already folded siblings
6622 (goto-char (point-min))
6623 (while (re-search-forward re nil t)
6624 (if (and (not (outline-invisible-p))
6625 (save-excursion
6626 (goto-char (point-at-eol)) (outline-invisible-p)))
6627 (hide-entry))))
6628 (org-cycle-show-empty-lines 'overview)
6629 (org-cycle-hide-drawers 'overview)))))
6631 (defun org-cycle-show-empty-lines (state)
6632 "Show empty lines above all visible headlines.
6633 The region to be covered depends on STATE when called through
6634 `org-cycle-hook'. Lisp program can use t for STATE to get the
6635 entire buffer covered. Note that an empty line is only shown if there
6636 are at least `org-cycle-separator-lines' empty lines before the headline."
6637 (when (not (= org-cycle-separator-lines 0))
6638 (save-excursion
6639 (let* ((n (abs org-cycle-separator-lines))
6640 (re (cond
6641 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6642 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6643 (t (let ((ns (number-to-string (- n 2))))
6644 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6645 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6646 beg end b e)
6647 (cond
6648 ((memq state '(overview contents t))
6649 (setq beg (point-min) end (point-max)))
6650 ((memq state '(children folded))
6651 (setq beg (point) end (progn (org-end-of-subtree t t)
6652 (beginning-of-line 2)
6653 (point)))))
6654 (when beg
6655 (goto-char beg)
6656 (while (re-search-forward re end t)
6657 (unless (get-char-property (match-end 1) 'invisible)
6658 (setq e (match-end 1))
6659 (if (< org-cycle-separator-lines 0)
6660 (setq b (save-excursion
6661 (goto-char (match-beginning 0))
6662 (org-back-over-empty-lines)
6663 (if (save-excursion
6664 (goto-char (max (point-min) (1- (point))))
6665 (org-at-heading-p))
6666 (1- (point))
6667 (point))))
6668 (setq b (match-beginning 1)))
6669 (outline-flag-region b e nil)))))))
6670 ;; Never hide empty lines at the end of the file.
6671 (save-excursion
6672 (goto-char (point-max))
6673 (outline-previous-heading)
6674 (outline-end-of-heading)
6675 (if (and (looking-at "[ \t\n]+")
6676 (= (match-end 0) (point-max)))
6677 (outline-flag-region (point) (match-end 0) nil))))
6679 (defun org-show-empty-lines-in-parent ()
6680 "Move to the parent and re-show empty lines before visible headlines."
6681 (save-excursion
6682 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6683 (org-cycle-show-empty-lines context))))
6685 (defun org-files-list ()
6686 "Return `org-agenda-files' list, plus all open org-mode files.
6687 This is useful for operations that need to scan all of a user's
6688 open and agenda-wise Org files."
6689 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6690 (dolist (buf (buffer-list))
6691 (with-current-buffer buf
6692 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6693 (let ((file (expand-file-name (buffer-file-name))))
6694 (unless (member file files)
6695 (push file files))))))
6696 files))
6698 (defsubst org-entry-beginning-position ()
6699 "Return the beginning position of the current entry."
6700 (save-excursion (outline-back-to-heading t) (point)))
6702 (defsubst org-entry-end-position ()
6703 "Return the end position of the current entry."
6704 (save-excursion (outline-next-heading) (point)))
6706 (defun org-cycle-hide-drawers (state)
6707 "Re-hide all drawers after a visibility state change."
6708 (when (and (derived-mode-p 'org-mode)
6709 (not (memq state '(overview folded contents))))
6710 (save-excursion
6711 (let* ((globalp (memq state '(contents all)))
6712 (beg (if globalp (point-min) (point)))
6713 (end (if globalp (point-max)
6714 (if (eq state 'children)
6715 (save-excursion (outline-next-heading) (point))
6716 (org-end-of-subtree t)))))
6717 (goto-char beg)
6718 (while (re-search-forward org-drawer-regexp end t)
6719 (org-flag-drawer t))))))
6721 (defun org-flag-drawer (flag)
6722 "When FLAG is non-nil, hide the drawer we are within.
6723 Otherwise make it visible."
6724 (save-excursion
6725 (beginning-of-line 1)
6726 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6727 (let ((b (match-end 0)))
6728 (if (re-search-forward
6729 "^[ \t]*:END:"
6730 (save-excursion (outline-next-heading) (point)) t)
6731 (outline-flag-region b (point-at-eol) flag)
6732 (error ":END: line missing at position %s" b))))))
6734 (defun org-subtree-end-visible-p ()
6735 "Is the end of the current subtree visible?"
6736 (pos-visible-in-window-p
6737 (save-excursion (org-end-of-subtree t) (point))))
6739 (defun org-first-headline-recenter (&optional N)
6740 "Move cursor to the first headline and recenter the headline.
6741 Optional argument N means put the headline into the Nth line of the window."
6742 (goto-char (point-min))
6743 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6744 (beginning-of-line)
6745 (recenter (prefix-numeric-value N))))
6747 ;;; Saving and restoring visibility
6749 (defun org-outline-overlay-data (&optional use-markers)
6750 "Return a list of the locations of all outline overlays.
6751 These are overlays with the `invisible' property value `outline'.
6752 The return value is a list of cons cells, with start and stop
6753 positions for each overlay.
6754 If USE-MARKERS is set, return the positions as markers."
6755 (let (beg end)
6756 (save-excursion
6757 (save-restriction
6758 (widen)
6759 (delq nil
6760 (mapcar (lambda (o)
6761 (when (eq (overlay-get o 'invisible) 'outline)
6762 (setq beg (overlay-start o)
6763 end (overlay-end o))
6764 (and beg end (> end beg)
6765 (if use-markers
6766 (cons (move-marker (make-marker) beg)
6767 (move-marker (make-marker) end))
6768 (cons beg end)))))
6769 (overlays-in (point-min) (point-max))))))))
6771 (defun org-set-outline-overlay-data (data)
6772 "Create visibility overlays for all positions in DATA.
6773 DATA should have been made by `org-outline-overlay-data'."
6774 (let (o)
6775 (save-excursion
6776 (save-restriction
6777 (widen)
6778 (show-all)
6779 (mapc (lambda (c)
6780 (outline-flag-region (car c) (cdr c) t))
6781 data)))))
6783 ;;; Folding of blocks
6785 (defvar org-hide-block-overlays nil
6786 "Overlays hiding blocks.")
6787 (make-variable-buffer-local 'org-hide-block-overlays)
6789 (defun org-block-map (function &optional start end)
6790 "Call FUNCTION at the head of all source blocks in the current buffer.
6791 Optional arguments START and END can be used to limit the range."
6792 (let ((start (or start (point-min)))
6793 (end (or end (point-max))))
6794 (save-excursion
6795 (goto-char start)
6796 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6797 (save-excursion
6798 (save-match-data
6799 (goto-char (match-beginning 0))
6800 (funcall function)))))))
6802 (defun org-hide-block-toggle-all ()
6803 "Toggle the visibility of all blocks in the current buffer."
6804 (org-block-map #'org-hide-block-toggle))
6806 (defun org-hide-block-all ()
6807 "Fold all blocks in the current buffer."
6808 (interactive)
6809 (org-show-block-all)
6810 (org-block-map #'org-hide-block-toggle-maybe))
6812 (defun org-show-block-all ()
6813 "Unfold all blocks in the current buffer."
6814 (interactive)
6815 (mapc 'delete-overlay org-hide-block-overlays)
6816 (setq org-hide-block-overlays nil))
6818 (defun org-hide-block-toggle-maybe ()
6819 "Toggle visibility of block at point."
6820 (interactive)
6821 (let ((case-fold-search t))
6822 (if (save-excursion
6823 (beginning-of-line 1)
6824 (looking-at org-block-regexp))
6825 (progn (org-hide-block-toggle)
6826 t) ;; to signal that we took action
6827 nil))) ;; to signal that we did not
6829 (defun org-hide-block-toggle (&optional force)
6830 "Toggle the visibility of the current block."
6831 (interactive)
6832 (save-excursion
6833 (beginning-of-line)
6834 (if (re-search-forward org-block-regexp nil t)
6835 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6836 (end (match-end 0)) ;; end of entire body
6838 (if (memq t (mapcar (lambda (overlay)
6839 (eq (overlay-get overlay 'invisible)
6840 'org-hide-block))
6841 (overlays-at start)))
6842 (if (or (not force) (eq force 'off))
6843 (mapc (lambda (ov)
6844 (when (member ov org-hide-block-overlays)
6845 (setq org-hide-block-overlays
6846 (delq ov org-hide-block-overlays)))
6847 (when (eq (overlay-get ov 'invisible)
6848 'org-hide-block)
6849 (delete-overlay ov)))
6850 (overlays-at start)))
6851 (setq ov (make-overlay start end))
6852 (overlay-put ov 'invisible 'org-hide-block)
6853 ;; make the block accessible to isearch
6854 (overlay-put
6855 ov 'isearch-open-invisible
6856 (lambda (ov)
6857 (when (member ov org-hide-block-overlays)
6858 (setq org-hide-block-overlays
6859 (delq ov org-hide-block-overlays)))
6860 (when (eq (overlay-get ov 'invisible)
6861 'org-hide-block)
6862 (delete-overlay ov))))
6863 (push ov org-hide-block-overlays)))
6864 (error "Not looking at a source block"))))
6866 ;; org-tab-after-check-for-cycling-hook
6867 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6868 ;; Remove overlays when changing major mode
6869 (add-hook 'org-mode-hook
6870 (lambda () (org-add-hook 'change-major-mode-hook
6871 'org-show-block-all 'append 'local)))
6873 ;;; Org-goto
6875 (defvar org-goto-window-configuration nil)
6876 (defvar org-goto-marker nil)
6877 (defvar org-goto-map
6878 (let ((map (make-sparse-keymap)))
6879 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6880 (while (setq cmd (pop cmds))
6881 (substitute-key-definition cmd cmd map global-map)))
6882 (suppress-keymap map)
6883 (org-defkey map "\C-m" 'org-goto-ret)
6884 (org-defkey map [(return)] 'org-goto-ret)
6885 (org-defkey map [(left)] 'org-goto-left)
6886 (org-defkey map [(right)] 'org-goto-right)
6887 (org-defkey map [(control ?g)] 'org-goto-quit)
6888 (org-defkey map "\C-i" 'org-cycle)
6889 (org-defkey map [(tab)] 'org-cycle)
6890 (org-defkey map [(down)] 'outline-next-visible-heading)
6891 (org-defkey map [(up)] 'outline-previous-visible-heading)
6892 (if org-goto-auto-isearch
6893 (if (fboundp 'define-key-after)
6894 (define-key-after map [t] 'org-goto-local-auto-isearch)
6895 nil)
6896 (org-defkey map "q" 'org-goto-quit)
6897 (org-defkey map "n" 'outline-next-visible-heading)
6898 (org-defkey map "p" 'outline-previous-visible-heading)
6899 (org-defkey map "f" 'outline-forward-same-level)
6900 (org-defkey map "b" 'outline-backward-same-level)
6901 (org-defkey map "u" 'outline-up-heading))
6902 (org-defkey map "/" 'org-occur)
6903 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6904 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6905 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6906 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6907 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6908 map))
6910 (defconst org-goto-help
6911 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6912 RET=jump to location [Q]uit and return to previous location
6913 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6915 (defvar org-goto-start-pos) ; dynamically scoped parameter
6917 ;; FIXME: Docstring does not mention both interfaces
6918 (defun org-goto (&optional alternative-interface)
6919 "Look up a different location in the current file, keeping current visibility.
6921 When you want look-up or go to a different location in a
6922 document, the fastest way is often to fold the entire buffer and
6923 then dive into the tree. This method has the disadvantage, that
6924 the previous location will be folded, which may not be what you
6925 want.
6927 This command works around this by showing a copy of the current
6928 buffer in an indirect buffer, in overview mode. You can dive
6929 into the tree in that copy, use org-occur and incremental search
6930 to find a location. When pressing RET or `Q', the command
6931 returns to the original buffer in which the visibility is still
6932 unchanged. After RET it will also jump to the location selected
6933 in the indirect buffer and expose the headline hierarchy above.
6935 With a prefix argument, use the alternative interface: e.g. if
6936 `org-goto-interface' is 'outline use 'outline-path-completion."
6937 (interactive "P")
6938 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6939 (org-refile-use-outline-path t)
6940 (org-refile-target-verify-function nil)
6941 (interface
6942 (if (not alternative-interface)
6943 org-goto-interface
6944 (if (eq org-goto-interface 'outline)
6945 'outline-path-completion
6946 'outline)))
6947 (org-goto-start-pos (point))
6948 (selected-point
6949 (if (eq interface 'outline)
6950 (car (org-get-location (current-buffer) org-goto-help))
6951 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6952 (org-refile-check-position pa)
6953 (nth 3 pa)))))
6954 (if selected-point
6955 (progn
6956 (org-mark-ring-push org-goto-start-pos)
6957 (goto-char selected-point)
6958 (if (or (outline-invisible-p) (org-invisible-p2))
6959 (org-show-context 'org-goto)))
6960 (message "Quit"))))
6962 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6963 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6964 (defvar org-goto-local-auto-isearch-map) ; defined below
6966 (defun org-get-location (buf help)
6967 "Let the user select a location in the Org-mode buffer BUF.
6968 This function uses a recursive edit. It returns the selected position
6969 or nil."
6970 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6971 (isearch-hide-immediately nil)
6972 (isearch-search-fun-function
6973 (lambda () 'org-goto-local-search-headings))
6974 (org-goto-selected-point org-goto-exit-command)
6975 (pop-up-frames nil)
6976 (special-display-buffer-names nil)
6977 (special-display-regexps nil)
6978 (special-display-function nil))
6979 (save-excursion
6980 (save-window-excursion
6981 (delete-other-windows)
6982 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6983 (org-pop-to-buffer-same-window
6984 (condition-case nil
6985 (make-indirect-buffer (current-buffer) "*org-goto*")
6986 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6987 (with-output-to-temp-buffer "*Help*"
6988 (princ help))
6989 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6990 (setq buffer-read-only nil)
6991 (let ((org-startup-truncated t)
6992 (org-startup-folded nil)
6993 (org-startup-align-all-tables nil))
6994 (org-mode)
6995 (org-overview))
6996 (setq buffer-read-only t)
6997 (if (and (boundp 'org-goto-start-pos)
6998 (integer-or-marker-p org-goto-start-pos))
6999 (let ((org-show-hierarchy-above t)
7000 (org-show-siblings t)
7001 (org-show-following-heading t))
7002 (goto-char org-goto-start-pos)
7003 (and (outline-invisible-p) (org-show-context)))
7004 (goto-char (point-min)))
7005 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7006 (message "Select location and press RET")
7007 (use-local-map org-goto-map)
7008 (recursive-edit)
7010 (kill-buffer "*org-goto*")
7011 (cons org-goto-selected-point org-goto-exit-command)))
7013 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7014 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7015 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7016 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7018 (defun org-goto-local-search-headings (string bound noerror)
7019 "Search and make sure that any matches are in headlines."
7020 (catch 'return
7021 (while (if isearch-forward
7022 (search-forward string bound noerror)
7023 (search-backward string bound noerror))
7024 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7025 (and (member :headline context)
7026 (not (member :tags context))))
7027 (throw 'return (point))))))
7029 (defun org-goto-local-auto-isearch ()
7030 "Start isearch."
7031 (interactive)
7032 (goto-char (point-min))
7033 (let ((keys (this-command-keys)))
7034 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7035 (isearch-mode t)
7036 (isearch-process-search-char (string-to-char keys)))))
7038 (defun org-goto-ret (&optional arg)
7039 "Finish `org-goto' by going to the new location."
7040 (interactive "P")
7041 (setq org-goto-selected-point (point)
7042 org-goto-exit-command 'return)
7043 (throw 'exit nil))
7045 (defun org-goto-left ()
7046 "Finish `org-goto' by going to the new location."
7047 (interactive)
7048 (if (org-at-heading-p)
7049 (progn
7050 (beginning-of-line 1)
7051 (setq org-goto-selected-point (point)
7052 org-goto-exit-command 'left)
7053 (throw 'exit nil))
7054 (error "Not on a heading")))
7056 (defun org-goto-right ()
7057 "Finish `org-goto' by going to the new location."
7058 (interactive)
7059 (if (org-at-heading-p)
7060 (progn
7061 (setq org-goto-selected-point (point)
7062 org-goto-exit-command 'right)
7063 (throw 'exit nil))
7064 (error "Not on a heading")))
7066 (defun org-goto-quit ()
7067 "Finish `org-goto' without cursor motion."
7068 (interactive)
7069 (setq org-goto-selected-point nil)
7070 (setq org-goto-exit-command 'quit)
7071 (throw 'exit nil))
7073 ;;; Indirect buffer display of subtrees
7075 (defvar org-indirect-dedicated-frame nil
7076 "This is the frame being used for indirect tree display.")
7077 (defvar org-last-indirect-buffer nil)
7079 (defun org-tree-to-indirect-buffer (&optional arg)
7080 "Create indirect buffer and narrow it to current subtree.
7081 With numerical prefix ARG, go up to this level and then take that tree.
7082 If ARG is negative, go up that many levels.
7083 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7084 indirect buffer previously made with this command, to avoid proliferation of
7085 indirect buffers. However, when you call the command with a \
7086 \\[universal-argument] prefix, or
7087 when `org-indirect-buffer-display' is `new-frame', the last buffer
7088 is kept so that you can work with several indirect buffers at the same time.
7089 If `org-indirect-buffer-display' is `dedicated-frame', the \
7090 \\[universal-argument] prefix also
7091 requests that a new frame be made for the new buffer, so that the dedicated
7092 frame is not changed."
7093 (interactive "P")
7094 (let ((cbuf (current-buffer))
7095 (cwin (selected-window))
7096 (pos (point))
7097 beg end level heading ibuf)
7098 (save-excursion
7099 (org-back-to-heading t)
7100 (when (numberp arg)
7101 (setq level (org-outline-level))
7102 (if (< arg 0) (setq arg (+ level arg)))
7103 (while (> (setq level (org-outline-level)) arg)
7104 (outline-up-heading 1 t)))
7105 (setq beg (point)
7106 heading (org-get-heading))
7107 (org-end-of-subtree t t)
7108 (if (org-at-heading-p) (backward-char 1))
7109 (setq end (point)))
7110 (if (and (buffer-live-p org-last-indirect-buffer)
7111 (not (eq org-indirect-buffer-display 'new-frame))
7112 (not arg))
7113 (kill-buffer org-last-indirect-buffer))
7114 (setq ibuf (org-get-indirect-buffer cbuf)
7115 org-last-indirect-buffer ibuf)
7116 (cond
7117 ((or (eq org-indirect-buffer-display 'new-frame)
7118 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7119 (select-frame (make-frame))
7120 (delete-other-windows)
7121 (org-pop-to-buffer-same-window ibuf)
7122 (org-set-frame-title heading))
7123 ((eq org-indirect-buffer-display 'dedicated-frame)
7124 (raise-frame
7125 (select-frame (or (and org-indirect-dedicated-frame
7126 (frame-live-p org-indirect-dedicated-frame)
7127 org-indirect-dedicated-frame)
7128 (setq org-indirect-dedicated-frame (make-frame)))))
7129 (delete-other-windows)
7130 (org-pop-to-buffer-same-window ibuf)
7131 (org-set-frame-title (concat "Indirect: " heading)))
7132 ((eq org-indirect-buffer-display 'current-window)
7133 (org-pop-to-buffer-same-window ibuf))
7134 ((eq org-indirect-buffer-display 'other-window)
7135 (pop-to-buffer ibuf))
7136 (t (error "Invalid value")))
7137 (if (featurep 'xemacs)
7138 (save-excursion (org-mode) (turn-on-font-lock)))
7139 (narrow-to-region beg end)
7140 (show-all)
7141 (goto-char pos)
7142 (run-hook-with-args 'org-cycle-hook 'all)
7143 (and (window-live-p cwin) (select-window cwin))))
7145 (defun org-get-indirect-buffer (&optional buffer)
7146 (setq buffer (or buffer (current-buffer)))
7147 (let ((n 1) (base (buffer-name buffer)) bname)
7148 (while (buffer-live-p
7149 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7150 (setq n (1+ n)))
7151 (condition-case nil
7152 (make-indirect-buffer buffer bname 'clone)
7153 (error (make-indirect-buffer buffer bname)))))
7155 (defun org-set-frame-title (title)
7156 "Set the title of the current frame to the string TITLE."
7157 ;; FIXME: how to name a single frame in XEmacs???
7158 (unless (featurep 'xemacs)
7159 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7161 ;;;; Structure editing
7163 ;;; Inserting headlines
7165 (defun org-previous-line-empty-p ()
7166 (save-excursion
7167 (and (not (bobp))
7168 (or (beginning-of-line 0) t)
7169 (save-match-data
7170 (looking-at "[ \t]*$")))))
7172 (defun org-insert-heading (&optional force-heading invisible-ok)
7173 "Insert a new heading or item with same depth at point.
7174 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7175 If point is at the beginning of a headline, insert a sibling before the
7176 current headline. If point is not at the beginning, split the line,
7177 create the new headline with the text in the current line after point
7178 \(but see also the variable `org-M-RET-may-split-line').
7180 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7181 This is important for non-interactive uses of the command."
7182 (interactive "P")
7183 (if (or (= (buffer-size) 0)
7184 (and (not (save-excursion
7185 (and (ignore-errors (org-back-to-heading invisible-ok))
7186 (org-at-heading-p))))
7187 (or force-heading (not (org-in-item-p)))))
7188 (progn
7189 (insert "\n* ")
7190 (run-hooks 'org-insert-heading-hook))
7191 (when (or force-heading (not (org-insert-item)))
7192 (let* ((empty-line-p nil)
7193 (level nil)
7194 (on-heading (org-at-heading-p))
7195 (head (save-excursion
7196 (condition-case nil
7197 (progn
7198 (org-back-to-heading invisible-ok)
7199 (when (and (not on-heading)
7200 (featurep 'org-inlinetask)
7201 (integerp org-inlinetask-min-level)
7202 (>= (length (match-string 0))
7203 org-inlinetask-min-level))
7204 ;; Find a heading level before the inline task
7205 (while (and (setq level (org-up-heading-safe))
7206 (>= level org-inlinetask-min-level)))
7207 (if (org-at-heading-p)
7208 (org-back-to-heading invisible-ok)
7209 (error "This should not happen")))
7210 (setq empty-line-p (org-previous-line-empty-p))
7211 (match-string 0))
7212 (error "*"))))
7213 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7214 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7215 pos hide-previous previous-pos)
7216 (cond
7217 ((and (org-at-heading-p) (bolp)
7218 (or (bobp)
7219 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7220 ;; insert before the current line
7221 (open-line (if blank 2 1)))
7222 ((and (bolp)
7223 (not org-insert-heading-respect-content)
7224 (or (bobp)
7225 (save-excursion
7226 (backward-char 1) (not (outline-invisible-p)))))
7227 ;; insert right here
7228 nil)
7230 ;; somewhere in the line
7231 (save-excursion
7232 (setq previous-pos (point-at-bol))
7233 (end-of-line)
7234 (setq hide-previous (outline-invisible-p)))
7235 (and org-insert-heading-respect-content (org-show-subtree))
7236 (let ((split
7237 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7238 (save-excursion
7239 (let ((p (point)))
7240 (goto-char (point-at-bol))
7241 (and (looking-at org-complex-heading-regexp)
7242 (match-beginning 4)
7243 (> p (match-beginning 4)))))))
7244 tags pos)
7245 (cond
7246 (org-insert-heading-respect-content
7247 (org-end-of-subtree nil t)
7248 (when (featurep 'org-inlinetask)
7249 (while (and (not (eobp))
7250 (looking-at "\\(\\*+\\)[ \t]+")
7251 (>= (length (match-string 1))
7252 org-inlinetask-min-level))
7253 (org-end-of-subtree nil t)))
7254 (or (bolp) (newline))
7255 (or (org-previous-line-empty-p)
7256 (and blank (newline)))
7257 (open-line 1))
7258 ((org-at-heading-p)
7259 (when hide-previous
7260 (show-children)
7261 (org-show-entry))
7262 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7263 (setq tags (and (match-end 2) (match-string 2)))
7264 (and (match-end 1)
7265 (delete-region (match-beginning 1) (match-end 1)))
7266 (setq pos (point-at-bol))
7267 (or split (end-of-line 1))
7268 (delete-horizontal-space)
7269 (if (string-match "\\`\\*+\\'"
7270 (buffer-substring (point-at-bol) (point)))
7271 (insert " "))
7272 (newline (if blank 2 1))
7273 (when tags
7274 (save-excursion
7275 (goto-char pos)
7276 (end-of-line 1)
7277 (insert " " tags)
7278 (org-set-tags nil 'align))))
7280 (or split (end-of-line 1))
7281 (newline (if blank 2 1)))))))
7282 (insert head) (just-one-space)
7283 (setq pos (point))
7284 (end-of-line 1)
7285 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7286 (when (and org-insert-heading-respect-content hide-previous)
7287 (save-excursion
7288 (goto-char previous-pos)
7289 (hide-subtree)))
7290 (run-hooks 'org-insert-heading-hook)))))
7292 (defun org-get-heading (&optional no-tags no-todo)
7293 "Return the heading of the current entry, without the stars.
7294 When NO-TAGS is non-nil, don't include tags.
7295 When NO-TODO is non-nil, don't include TODO keywords."
7296 (save-excursion
7297 (org-back-to-heading t)
7298 (cond
7299 ((and no-tags no-todo)
7300 (looking-at org-complex-heading-regexp)
7301 (match-string 4))
7302 (no-tags
7303 (looking-at (concat org-outline-regexp
7304 "\\(.*?\\)"
7305 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7306 (match-string 1))
7307 (no-todo
7308 (looking-at org-todo-line-regexp)
7309 (match-string 3))
7310 (t (looking-at org-heading-regexp)
7311 (match-string 2)))))
7313 (defun org-heading-components ()
7314 "Return the components of the current heading.
7315 This is a list with the following elements:
7316 - the level as an integer
7317 - the reduced level, different if `org-odd-levels-only' is set.
7318 - the TODO keyword, or nil
7319 - the priority character, like ?A, or nil if no priority is given
7320 - the headline text itself, or the tags string if no headline text
7321 - the tags string, or nil."
7322 (save-excursion
7323 (org-back-to-heading t)
7324 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7325 (list (length (match-string 1))
7326 (org-reduced-level (length (match-string 1)))
7327 (org-match-string-no-properties 2)
7328 (and (match-end 3) (aref (match-string 3) 2))
7329 (org-match-string-no-properties 4)
7330 (org-match-string-no-properties 5)))))
7332 (defun org-get-entry ()
7333 "Get the entry text, after heading, entire subtree."
7334 (save-excursion
7335 (org-back-to-heading t)
7336 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7338 (defun org-insert-heading-after-current ()
7339 "Insert a new heading with same level as current, after current subtree."
7340 (interactive)
7341 (org-back-to-heading)
7342 (org-insert-heading)
7343 (org-move-subtree-down)
7344 (end-of-line 1))
7346 (defun org-insert-heading-respect-content ()
7347 (interactive)
7348 (let ((org-insert-heading-respect-content t))
7349 (org-insert-heading t)))
7351 (defun org-insert-todo-heading-respect-content (&optional force-state)
7352 (interactive "P")
7353 (let ((org-insert-heading-respect-content t))
7354 (org-insert-todo-heading force-state t)))
7356 (defun org-insert-todo-heading (arg &optional force-heading)
7357 "Insert a new heading with the same level and TODO state as current heading.
7358 If the heading has no TODO state, or if the state is DONE, use the first
7359 state (TODO by default). Also with prefix arg, force first state."
7360 (interactive "P")
7361 (when (or force-heading (not (org-insert-item 'checkbox)))
7362 (org-insert-heading force-heading)
7363 (save-excursion
7364 (org-back-to-heading)
7365 (outline-previous-heading)
7366 (looking-at org-todo-line-regexp))
7367 (let*
7368 ((new-mark-x
7369 (if (or arg
7370 (not (match-beginning 2))
7371 (member (match-string 2) org-done-keywords))
7372 (car org-todo-keywords-1)
7373 (match-string 2)))
7374 (new-mark
7376 (run-hook-with-args-until-success
7377 'org-todo-get-default-hook new-mark-x nil)
7378 new-mark-x)))
7379 (beginning-of-line 1)
7380 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7381 (if org-treat-insert-todo-heading-as-state-change
7382 (org-todo new-mark)
7383 (insert new-mark " "))))
7384 (when org-provide-todo-statistics
7385 (org-update-parent-todo-statistics))))
7387 (defun org-insert-subheading (arg)
7388 "Insert a new subheading and demote it.
7389 Works for outline headings and for plain lists alike."
7390 (interactive "P")
7391 (org-insert-heading arg)
7392 (cond
7393 ((org-at-heading-p) (org-do-demote))
7394 ((org-at-item-p) (org-indent-item))))
7396 (defun org-insert-todo-subheading (arg)
7397 "Insert a new subheading with TODO keyword or checkbox and demote it.
7398 Works for outline headings and for plain lists alike."
7399 (interactive "P")
7400 (org-insert-todo-heading arg)
7401 (cond
7402 ((org-at-heading-p) (org-do-demote))
7403 ((org-at-item-p) (org-indent-item))))
7405 ;;; Promotion and Demotion
7407 (defvar org-after-demote-entry-hook nil
7408 "Hook run after an entry has been demoted.
7409 The cursor will be at the beginning of the entry.
7410 When a subtree is being demoted, the hook will be called for each node.")
7412 (defvar org-after-promote-entry-hook nil
7413 "Hook run after an entry has been promoted.
7414 The cursor will be at the beginning of the entry.
7415 When a subtree is being promoted, the hook will be called for each node.")
7417 (defun org-promote-subtree ()
7418 "Promote the entire subtree.
7419 See also `org-promote'."
7420 (interactive)
7421 (save-excursion
7422 (org-with-limited-levels (org-map-tree 'org-promote)))
7423 (org-fix-position-after-promote))
7425 (defun org-demote-subtree ()
7426 "Demote the entire subtree. See `org-demote'.
7427 See also `org-promote'."
7428 (interactive)
7429 (save-excursion
7430 (org-with-limited-levels (org-map-tree 'org-demote)))
7431 (org-fix-position-after-promote))
7434 (defun org-do-promote ()
7435 "Promote the current heading higher up the tree.
7436 If the region is active in `transient-mark-mode', promote all headings
7437 in the region."
7438 (interactive)
7439 (save-excursion
7440 (if (org-region-active-p)
7441 (org-map-region 'org-promote (region-beginning) (region-end))
7442 (org-promote)))
7443 (org-fix-position-after-promote))
7445 (defun org-do-demote ()
7446 "Demote the current heading lower down the tree.
7447 If the region is active in `transient-mark-mode', demote all headings
7448 in the region."
7449 (interactive)
7450 (save-excursion
7451 (if (org-region-active-p)
7452 (org-map-region 'org-demote (region-beginning) (region-end))
7453 (org-demote)))
7454 (org-fix-position-after-promote))
7456 (defun org-fix-position-after-promote ()
7457 "Make sure that after pro/demotion cursor position is right."
7458 (let ((pos (point)))
7459 (when (save-excursion
7460 (beginning-of-line 1)
7461 (looking-at org-todo-line-regexp)
7462 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7463 (cond ((eobp) (insert " "))
7464 ((eolp) (insert " "))
7465 ((equal (char-after) ?\ ) (forward-char 1))))))
7467 (defun org-current-level ()
7468 "Return the level of the current entry, or nil if before the first headline.
7469 The level is the number of stars at the beginning of the headline."
7470 (save-excursion
7471 (org-with-limited-levels
7472 (if (ignore-errors (org-back-to-heading t))
7473 (funcall outline-level)))))
7475 (defun org-get-previous-line-level ()
7476 "Return the outline depth of the last headline before the current line.
7477 Returns 0 for the first headline in the buffer, and nil if before the
7478 first headline."
7479 (let ((current-level (org-current-level))
7480 (prev-level (when (> (line-number-at-pos) 1)
7481 (save-excursion
7482 (beginning-of-line 0)
7483 (org-current-level)))))
7484 (cond ((null current-level) nil) ; Before first headline
7485 ((null prev-level) 0) ; At first headline
7486 (prev-level))))
7488 (defun org-reduced-level (l)
7489 "Compute the effective level of a heading.
7490 This takes into account the setting of `org-odd-levels-only'."
7491 (cond
7492 ((zerop l) 0)
7493 (org-odd-levels-only (1+ (floor (/ l 2))))
7494 (t l)))
7496 (defun org-level-increment ()
7497 "Return the number of stars that will be added or removed at a
7498 time to headlines when structure editing, based on the value of
7499 `org-odd-levels-only'."
7500 (if org-odd-levels-only 2 1))
7502 (defun org-get-valid-level (level &optional change)
7503 "Rectify a level change under the influence of `org-odd-levels-only'
7504 LEVEL is a current level, CHANGE is by how much the level should be
7505 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7506 even level numbers will become the next higher odd number."
7507 (if org-odd-levels-only
7508 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7509 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7510 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7511 (max 1 (+ level (or change 0)))))
7513 (if (boundp 'define-obsolete-function-alias)
7514 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7515 (define-obsolete-function-alias 'org-get-legal-level
7516 'org-get-valid-level)
7517 (define-obsolete-function-alias 'org-get-legal-level
7518 'org-get-valid-level "23.1")))
7520 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7521 ;; ̀org-with-limited-levels'
7522 (defun org-promote ()
7523 "Promote the current heading higher up the tree.
7524 If the region is active in `transient-mark-mode', promote all headings
7525 in the region."
7526 (org-back-to-heading t)
7527 (let* ((level (save-match-data (funcall outline-level)))
7528 (after-change-functions (remove 'flyspell-after-change-function
7529 after-change-functions))
7530 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7531 (diff (abs (- level (length up-head) -1))))
7532 (cond ((and (= level 1) org-called-with-limited-levels
7533 org-allow-promoting-top-level-subtree)
7534 (replace-match "# " nil t))
7535 ((= level 1)
7536 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7537 (t (replace-match up-head nil t)))
7538 ;; Fixup tag positioning
7539 (unless (= level 1)
7540 (and org-auto-align-tags (org-set-tags nil t))
7541 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7542 (run-hooks 'org-after-promote-entry-hook)))
7544 (defun org-demote ()
7545 "Demote the current heading lower down the tree.
7546 If the region is active in `transient-mark-mode', demote all headings
7547 in the region."
7548 (org-back-to-heading t)
7549 (let* ((level (save-match-data (funcall outline-level)))
7550 (after-change-functions (remove 'flyspell-after-change-function
7551 after-change-functions))
7552 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7553 (diff (abs (- level (length down-head) -1))))
7554 (replace-match down-head nil t)
7555 ;; Fixup tag positioning
7556 (and org-auto-align-tags (org-set-tags nil t))
7557 (if org-adapt-indentation (org-fixup-indentation diff))
7558 (run-hooks 'org-after-demote-entry-hook)))
7560 (defun org-cycle-level ()
7561 "Cycle the level of an empty headline through possible states.
7562 This goes first to child, then to parent, level, then up the hierarchy.
7563 After top level, it switches back to sibling level."
7564 (interactive)
7565 (let ((org-adapt-indentation nil))
7566 (when (org-point-at-end-of-empty-headline)
7567 (setq this-command 'org-cycle-level) ; Only needed for caching
7568 (let ((cur-level (org-current-level))
7569 (prev-level (org-get-previous-line-level)))
7570 (cond
7571 ;; If first headline in file, promote to top-level.
7572 ((= prev-level 0)
7573 (loop repeat (/ (- cur-level 1) (org-level-increment))
7574 do (org-do-promote)))
7575 ;; If same level as prev, demote one.
7576 ((= prev-level cur-level)
7577 (org-do-demote))
7578 ;; If parent is top-level, promote to top level if not already.
7579 ((= prev-level 1)
7580 (loop repeat (/ (- cur-level 1) (org-level-increment))
7581 do (org-do-promote)))
7582 ;; If top-level, return to prev-level.
7583 ((= cur-level 1)
7584 (loop repeat (/ (- prev-level 1) (org-level-increment))
7585 do (org-do-demote)))
7586 ;; If less than prev-level, promote one.
7587 ((< cur-level prev-level)
7588 (org-do-promote))
7589 ;; If deeper than prev-level, promote until higher than
7590 ;; prev-level.
7591 ((> cur-level prev-level)
7592 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7593 do (org-do-promote))))
7594 t))))
7596 (defun org-map-tree (fun)
7597 "Call FUN for every heading underneath the current one."
7598 (org-back-to-heading)
7599 (let ((level (funcall outline-level)))
7600 (save-excursion
7601 (funcall fun)
7602 (while (and (progn
7603 (outline-next-heading)
7604 (> (funcall outline-level) level))
7605 (not (eobp)))
7606 (funcall fun)))))
7608 (defun org-map-region (fun beg end)
7609 "Call FUN for every heading between BEG and END."
7610 (let ((org-ignore-region t))
7611 (save-excursion
7612 (setq end (copy-marker end))
7613 (goto-char beg)
7614 (if (and (re-search-forward org-outline-regexp-bol nil t)
7615 (< (point) end))
7616 (funcall fun))
7617 (while (and (progn
7618 (outline-next-heading)
7619 (< (point) end))
7620 (not (eobp)))
7621 (funcall fun)))))
7623 (defvar org-property-end-re) ; silence byte-compiler
7624 (defun org-fixup-indentation (diff)
7625 "Change the indentation in the current entry by DIFF.
7626 However, if any line in the current entry has no indentation, or if it
7627 would end up with no indentation after the change, nothing at all is done."
7628 (save-excursion
7629 (let ((end (save-excursion (outline-next-heading)
7630 (point-marker)))
7631 (prohibit (if (> diff 0)
7632 "^\\S-"
7633 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7634 col)
7635 (unless (save-excursion (end-of-line 1)
7636 (re-search-forward prohibit end t))
7637 (while (and (< (point) end)
7638 (re-search-forward "^[ \t]+" end t))
7639 (goto-char (match-end 0))
7640 (setq col (current-column))
7641 (if (< diff 0) (replace-match ""))
7642 (org-indent-to-column (+ diff col))))
7643 (move-marker end nil))))
7645 (defun org-convert-to-odd-levels ()
7646 "Convert an org-mode file with all levels allowed to one with odd levels.
7647 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7648 level 5 etc."
7649 (interactive)
7650 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7651 (let ((outline-level 'org-outline-level)
7652 (org-odd-levels-only nil) n)
7653 (save-excursion
7654 (goto-char (point-min))
7655 (while (re-search-forward "^\\*\\*+ " nil t)
7656 (setq n (- (length (match-string 0)) 2))
7657 (while (>= (setq n (1- n)) 0)
7658 (org-demote))
7659 (end-of-line 1))))))
7661 (defun org-convert-to-oddeven-levels ()
7662 "Convert an org-mode file with only odd levels to one with odd/even levels.
7663 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7664 file contains a section with an even level, conversion would
7665 destroy the structure of the file. An error is signaled in this
7666 case."
7667 (interactive)
7668 (goto-char (point-min))
7669 ;; First check if there are no even levels
7670 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7671 (org-show-context t)
7672 (error "Not all levels are odd in this file. Conversion not possible"))
7673 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7674 (let ((outline-regexp org-outline-regexp)
7675 (outline-level 'org-outline-level)
7676 (org-odd-levels-only nil) n)
7677 (save-excursion
7678 (goto-char (point-min))
7679 (while (re-search-forward "^\\*\\*+ " nil t)
7680 (setq n (/ (1- (length (match-string 0))) 2))
7681 (while (>= (setq n (1- n)) 0)
7682 (org-promote))
7683 (end-of-line 1))))))
7685 (defun org-tr-level (n)
7686 "Make N odd if required."
7687 (if org-odd-levels-only (1+ (/ n 2)) n))
7689 ;;; Vertical tree motion, cutting and pasting of subtrees
7691 (defun org-move-subtree-up (&optional arg)
7692 "Move the current subtree up past ARG headlines of the same level."
7693 (interactive "p")
7694 (org-move-subtree-down (- (prefix-numeric-value arg))))
7696 (defun org-move-subtree-down (&optional arg)
7697 "Move the current subtree down past ARG headlines of the same level."
7698 (interactive "p")
7699 (setq arg (prefix-numeric-value arg))
7700 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7701 'org-get-last-sibling))
7702 (ins-point (make-marker))
7703 (cnt (abs arg))
7704 (col (current-column))
7705 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7706 ;; Select the tree
7707 (org-back-to-heading)
7708 (setq beg0 (point))
7709 (save-excursion
7710 (setq ne-beg (org-back-over-empty-lines))
7711 (setq beg (point)))
7712 (save-match-data
7713 (save-excursion (outline-end-of-heading)
7714 (setq folded (outline-invisible-p)))
7715 (outline-end-of-subtree))
7716 (outline-next-heading)
7717 (setq ne-end (org-back-over-empty-lines))
7718 (setq end (point))
7719 (goto-char beg0)
7720 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7721 ;; include less whitespace
7722 (save-excursion
7723 (goto-char beg)
7724 (forward-line (- ne-beg ne-end))
7725 (setq beg (point))))
7726 ;; Find insertion point, with error handling
7727 (while (> cnt 0)
7728 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7729 (progn (goto-char beg0)
7730 (error "Cannot move past superior level or buffer limit")))
7731 (setq cnt (1- cnt)))
7732 (if (> arg 0)
7733 ;; Moving forward - still need to move over subtree
7734 (progn (org-end-of-subtree t t)
7735 (save-excursion
7736 (org-back-over-empty-lines)
7737 (or (bolp) (newline)))))
7738 (setq ne-ins (org-back-over-empty-lines))
7739 (move-marker ins-point (point))
7740 (setq txt (buffer-substring beg end))
7741 (org-save-markers-in-region beg end)
7742 (delete-region beg end)
7743 (org-remove-empty-overlays-at beg)
7744 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7745 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7746 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7747 (let ((bbb (point)))
7748 (insert-before-markers txt)
7749 (org-reinstall-markers-in-region bbb)
7750 (move-marker ins-point bbb))
7751 (or (bolp) (insert "\n"))
7752 (setq ins-end (point))
7753 (goto-char ins-point)
7754 (org-skip-whitespace)
7755 (when (and (< arg 0)
7756 (org-first-sibling-p)
7757 (> ne-ins ne-beg))
7758 ;; Move whitespace back to beginning
7759 (save-excursion
7760 (goto-char ins-end)
7761 (let ((kill-whole-line t))
7762 (kill-line (- ne-ins ne-beg)) (point)))
7763 (insert (make-string (- ne-ins ne-beg) ?\n)))
7764 (move-marker ins-point nil)
7765 (if folded
7766 (hide-subtree)
7767 (org-show-entry)
7768 (show-children)
7769 (org-cycle-hide-drawers 'children))
7770 (org-clean-visibility-after-subtree-move)
7771 ;; move back to the initial column we were at
7772 (move-to-column col)))
7774 (defvar org-subtree-clip ""
7775 "Clipboard for cut and paste of subtrees.
7776 This is actually only a copy of the kill, because we use the normal kill
7777 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7779 (defvar org-subtree-clip-folded nil
7780 "Was the last copied subtree folded?
7781 This is used to fold the tree back after pasting.")
7783 (defun org-cut-subtree (&optional n)
7784 "Cut the current subtree into the clipboard.
7785 With prefix arg N, cut this many sequential subtrees.
7786 This is a short-hand for marking the subtree and then cutting it."
7787 (interactive "p")
7788 (org-copy-subtree n 'cut))
7790 (defun org-copy-subtree (&optional n cut force-store-markers)
7791 "Cut the current subtree into the clipboard.
7792 With prefix arg N, cut this many sequential subtrees.
7793 This is a short-hand for marking the subtree and then copying it.
7794 If CUT is non-nil, actually cut the subtree.
7795 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7796 of some markers in the region, even if CUT is non-nil. This is
7797 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7798 (interactive "p")
7799 (let (beg end folded (beg0 (point)))
7800 (if (org-called-interactively-p 'any)
7801 (org-back-to-heading nil) ; take what looks like a subtree
7802 (org-back-to-heading t)) ; take what is really there
7803 (org-back-over-empty-lines)
7804 (setq beg (point))
7805 (skip-chars-forward " \t\r\n")
7806 (save-match-data
7807 (save-excursion (outline-end-of-heading)
7808 (setq folded (outline-invisible-p)))
7809 (condition-case nil
7810 (org-forward-same-level (1- n) t)
7811 (error nil))
7812 (org-end-of-subtree t t))
7813 (org-back-over-empty-lines)
7814 (setq end (point))
7815 (goto-char beg0)
7816 (when (> end beg)
7817 (setq org-subtree-clip-folded folded)
7818 (when (or cut force-store-markers)
7819 (org-save-markers-in-region beg end))
7820 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7821 (setq org-subtree-clip (current-kill 0))
7822 (message "%s: Subtree(s) with %d characters"
7823 (if cut "Cut" "Copied")
7824 (length org-subtree-clip)))))
7826 (defun org-paste-subtree (&optional level tree for-yank)
7827 "Paste the clipboard as a subtree, with modification of headline level.
7828 The entire subtree is promoted or demoted in order to match a new headline
7829 level.
7831 If the cursor is at the beginning of a headline, the same level as
7832 that headline is used to paste the tree
7834 If not, the new level is derived from the *visible* headings
7835 before and after the insertion point, and taken to be the inferior headline
7836 level of the two. So if the previous visible heading is level 3 and the
7837 next is level 4 (or vice versa), level 4 will be used for insertion.
7838 This makes sure that the subtree remains an independent subtree and does
7839 not swallow low level entries.
7841 You can also force a different level, either by using a numeric prefix
7842 argument, or by inserting the heading marker by hand. For example, if the
7843 cursor is after \"*****\", then the tree will be shifted to level 5.
7845 If optional TREE is given, use this text instead of the kill ring.
7847 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7848 move back over whitespace before inserting, and move point to the end of
7849 the inserted text when done."
7850 (interactive "P")
7851 (setq tree (or tree (and kill-ring (current-kill 0))))
7852 (unless (org-kill-is-subtree-p tree)
7853 (error "%s"
7854 (substitute-command-keys
7855 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7856 (org-with-limited-levels
7857 (let* ((visp (not (outline-invisible-p)))
7858 (txt tree)
7859 (^re_ "\\(\\*+\\)[ \t]*")
7860 (old-level (if (string-match org-outline-regexp-bol txt)
7861 (- (match-end 0) (match-beginning 0) 1)
7862 -1))
7863 (force-level (cond (level (prefix-numeric-value level))
7864 ((and (looking-at "[ \t]*$")
7865 (string-match
7866 "^\\*+$" (buffer-substring
7867 (point-at-bol) (point))))
7868 (- (match-end 1) (match-beginning 1)))
7869 ((and (bolp)
7870 (looking-at org-outline-regexp))
7871 (- (match-end 0) (point) 1))
7872 (t nil)))
7873 (previous-level (save-excursion
7874 (condition-case nil
7875 (progn
7876 (outline-previous-visible-heading 1)
7877 (if (looking-at ^re_)
7878 (- (match-end 0) (match-beginning 0) 1)
7880 (error 1))))
7881 (next-level (save-excursion
7882 (condition-case nil
7883 (progn
7884 (or (looking-at org-outline-regexp)
7885 (outline-next-visible-heading 1))
7886 (if (looking-at ^re_)
7887 (- (match-end 0) (match-beginning 0) 1)
7889 (error 1))))
7890 (new-level (or force-level (max previous-level next-level)))
7891 (shift (if (or (= old-level -1)
7892 (= new-level -1)
7893 (= old-level new-level))
7895 (- new-level old-level)))
7896 (delta (if (> shift 0) -1 1))
7897 (func (if (> shift 0) 'org-demote 'org-promote))
7898 (org-odd-levels-only nil)
7899 beg end newend)
7900 ;; Remove the forced level indicator
7901 (if force-level
7902 (delete-region (point-at-bol) (point)))
7903 ;; Paste
7904 (beginning-of-line (if (bolp) 1 2))
7905 (unless for-yank (org-back-over-empty-lines))
7906 (setq beg (point))
7907 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7908 (insert-before-markers txt)
7909 (unless (string-match "\n\\'" txt) (insert "\n"))
7910 (setq newend (point))
7911 (org-reinstall-markers-in-region beg)
7912 (setq end (point))
7913 (goto-char beg)
7914 (skip-chars-forward " \t\n\r")
7915 (setq beg (point))
7916 (if (and (outline-invisible-p) visp)
7917 (save-excursion (outline-show-heading)))
7918 ;; Shift if necessary
7919 (unless (= shift 0)
7920 (save-restriction
7921 (narrow-to-region beg end)
7922 (while (not (= shift 0))
7923 (org-map-region func (point-min) (point-max))
7924 (setq shift (+ delta shift)))
7925 (goto-char (point-min))
7926 (setq newend (point-max))))
7927 (when (or (org-called-interactively-p 'interactive) for-yank)
7928 (message "Clipboard pasted as level %d subtree" new-level))
7929 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7930 kill-ring
7931 (eq org-subtree-clip (current-kill 0))
7932 org-subtree-clip-folded)
7933 ;; The tree was folded before it was killed/copied
7934 (hide-subtree))
7935 (and for-yank (goto-char newend)))))
7937 (defun org-kill-is-subtree-p (&optional txt)
7938 "Check if the current kill is an outline subtree, or a set of trees.
7939 Returns nil if kill does not start with a headline, or if the first
7940 headline level is not the largest headline level in the tree.
7941 So this will actually accept several entries of equal levels as well,
7942 which is OK for `org-paste-subtree'.
7943 If optional TXT is given, check this string instead of the current kill."
7944 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7945 (re (org-get-limited-outline-regexp))
7946 (^re (concat "^" re))
7947 (start-level (and kill
7948 (string-match
7949 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7950 kill)
7951 (- (match-end 2) (match-beginning 2) 1)))
7952 (start (1+ (or (match-beginning 2) -1))))
7953 (if (not start-level)
7954 (progn
7955 nil) ;; does not even start with a heading
7956 (catch 'exit
7957 (while (setq start (string-match ^re kill (1+ start)))
7958 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7959 (throw 'exit nil)))
7960 t))))
7962 (defvar org-markers-to-move nil
7963 "Markers that should be moved with a cut-and-paste operation.
7964 Those markers are stored together with their positions relative to
7965 the start of the region.")
7967 (defun org-save-markers-in-region (beg end)
7968 "Check markers in region.
7969 If these markers are between BEG and END, record their position relative
7970 to BEG, so that after moving the block of text, we can put the markers back
7971 into place.
7972 This function gets called just before an entry or tree gets cut from the
7973 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7974 called immediately, to move the markers with the entries."
7975 (setq org-markers-to-move nil)
7976 (when (featurep 'org-clock)
7977 (org-clock-save-markers-for-cut-and-paste beg end))
7978 (when (featurep 'org-agenda)
7979 (org-agenda-save-markers-for-cut-and-paste beg end)))
7981 (defun org-check-and-save-marker (marker beg end)
7982 "Check if MARKER is between BEG and END.
7983 If yes, remember the marker and the distance to BEG."
7984 (when (and (marker-buffer marker)
7985 (equal (marker-buffer marker) (current-buffer)))
7986 (if (and (>= marker beg) (< marker end))
7987 (push (cons marker (- marker beg)) org-markers-to-move))))
7989 (defun org-reinstall-markers-in-region (beg)
7990 "Move all remembered markers to their position relative to BEG."
7991 (mapc (lambda (x)
7992 (move-marker (car x) (+ beg (cdr x))))
7993 org-markers-to-move)
7994 (setq org-markers-to-move nil))
7996 (defun org-narrow-to-subtree ()
7997 "Narrow buffer to the current subtree."
7998 (interactive)
7999 (save-excursion
8000 (save-match-data
8001 (org-with-limited-levels
8002 (narrow-to-region
8003 (progn (org-back-to-heading t) (point))
8004 (progn (org-end-of-subtree t t)
8005 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8006 (point)))))))
8008 (defun org-narrow-to-block ()
8009 "Narrow buffer to the current block."
8010 (interactive)
8011 (let* ((case-fold-search t)
8012 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8013 "^[ \t]*#\\+end_.*")))
8014 (if blockp
8015 (narrow-to-region (car blockp) (cdr blockp))
8016 (error "Not in a block"))))
8018 (eval-when-compile
8019 (defvar org-property-drawer-re))
8021 (defvar org-property-start-re) ;; defined below
8022 (defun org-clone-subtree-with-time-shift (n &optional shift)
8023 "Clone the task (subtree) at point N times.
8024 The clones will be inserted as siblings.
8026 In interactive use, the user will be prompted for the number of
8027 clones to be produced, and for a time SHIFT, which may be a
8028 repeater as used in time stamps, for example `+3d'.
8030 When a valid repeater is given and the entry contains any time
8031 stamps, the clones will become a sequence in time, with time
8032 stamps in the subtree shifted for each clone produced. If SHIFT
8033 is nil or the empty string, time stamps will be left alone. The
8034 ID property of the original subtree is removed.
8036 If the original subtree did contain time stamps with a repeater,
8037 the following will happen:
8038 - the repeater will be removed in each clone
8039 - an additional clone will be produced, with the current, unshifted
8040 date(s) in the entry.
8041 - the original entry will be placed *after* all the clones, with
8042 repeater intact.
8043 - the start days in the repeater in the original entry will be shifted
8044 to past the last clone.
8045 In this way you can spell out a number of instances of a repeating task,
8046 and still retain the repeater to cover future instances of the task."
8047 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8048 (let (beg end template task idprop
8049 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8050 (drawer-re org-drawer-regexp))
8051 (if (not (and (integerp n) (> n 0)))
8052 (error "Invalid number of replications %s" n))
8053 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8054 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8055 shift)))
8056 (error "Invalid shift specification %s" shift))
8057 (when doshift
8058 (setq shift-n (string-to-number (match-string 1 shift))
8059 shift-what (cdr (assoc (match-string 2 shift)
8060 '(("d" . day) ("w" . week)
8061 ("m" . month) ("y" . year))))))
8062 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8063 (setq nmin 1 nmax n)
8064 (org-back-to-heading t)
8065 (setq beg (point))
8066 (setq idprop (org-entry-get nil "ID"))
8067 (org-end-of-subtree t t)
8068 (or (bolp) (insert "\n"))
8069 (setq end (point))
8070 (setq template (buffer-substring beg end))
8071 (when (and doshift
8072 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8073 (delete-region beg end)
8074 (setq end beg)
8075 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8076 (goto-char end)
8077 (loop for n from nmin to nmax do
8078 ;; prepare clone
8079 (with-temp-buffer
8080 (insert template)
8081 (org-mode)
8082 (goto-char (point-min))
8083 (org-show-subtree)
8084 (and idprop (if org-clone-delete-id
8085 (org-entry-delete nil "ID")
8086 (org-id-get-create t)))
8087 (unless (= n 0)
8088 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8089 (kill-whole-line))
8090 (goto-char (point-min))
8091 (while (re-search-forward drawer-re nil t)
8092 (mapc (lambda (d)
8093 (org-remove-empty-drawer-at d (point))) org-drawers)))
8094 (goto-char (point-min))
8095 (when doshift
8096 (while (re-search-forward org-ts-regexp-both nil t)
8097 (org-timestamp-change (* n shift-n) shift-what))
8098 (unless (= n n-no-remove)
8099 (goto-char (point-min))
8100 (while (re-search-forward org-ts-regexp nil t)
8101 (save-excursion
8102 (goto-char (match-beginning 0))
8103 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8104 (delete-region (match-beginning 1) (match-end 1)))))))
8105 (setq task (buffer-string)))
8106 (insert task))
8107 (goto-char beg)))
8109 ;;; Outline Sorting
8111 (defun org-sort (with-case)
8112 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8113 Optional argument WITH-CASE means sort case-sensitively."
8114 (interactive "P")
8115 (cond
8116 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8117 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8119 (org-call-with-arg 'org-sort-entries with-case))))
8121 (defun org-sort-remove-invisible (s)
8122 (remove-text-properties 0 (length s) org-rm-props s)
8123 (while (string-match org-bracket-link-regexp s)
8124 (setq s (replace-match (if (match-end 2)
8125 (match-string 3 s)
8126 (match-string 1 s)) t t s)))
8129 (defvar org-priority-regexp) ; defined later in the file
8131 (defvar org-after-sorting-entries-or-items-hook nil
8132 "Hook that is run after a bunch of entries or items have been sorted.
8133 When children are sorted, the cursor is in the parent line when this
8134 hook gets called. When a region or a plain list is sorted, the cursor
8135 will be in the first entry of the sorted region/list.")
8137 (defun org-sort-entries
8138 (&optional with-case sorting-type getkey-func compare-func property)
8139 "Sort entries on a certain level of an outline tree.
8140 If there is an active region, the entries in the region are sorted.
8141 Else, if the cursor is before the first entry, sort the top-level items.
8142 Else, the children of the entry at point are sorted.
8144 Sorting can be alphabetically, numerically, by date/time as given by
8145 a time stamp, by a property or by priority.
8147 The command prompts for the sorting type unless it has been given to the
8148 function through the SORTING-TYPE argument, which needs to be a character,
8149 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8150 precise meaning of each character:
8152 n Numerically, by converting the beginning of the entry/item to a number.
8153 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8154 t By date/time, either the first active time stamp in the entry, or, if
8155 none exist, by the first inactive one.
8156 s By the scheduled date/time.
8157 d By deadline date/time.
8158 c By creation time, which is assumed to be the first inactive time stamp
8159 at the beginning of a line.
8160 p By priority according to the cookie.
8161 r By the value of a property.
8163 Capital letters will reverse the sort order.
8165 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8166 called with point at the beginning of the record. It must return either
8167 a string or a number that should serve as the sorting key for that record.
8169 Comparing entries ignores case by default. However, with an optional argument
8170 WITH-CASE, the sorting considers case as well."
8171 (interactive "P")
8172 (let ((case-func (if with-case 'identity 'downcase))
8173 start beg end stars re re2
8174 txt what tmp)
8175 ;; Find beginning and end of region to sort
8176 (cond
8177 ((org-region-active-p)
8178 ;; we will sort the region
8179 (setq end (region-end)
8180 what "region")
8181 (goto-char (region-beginning))
8182 (if (not (org-at-heading-p)) (outline-next-heading))
8183 (setq start (point)))
8184 ((or (org-at-heading-p)
8185 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8186 ;; we will sort the children of the current headline
8187 (org-back-to-heading)
8188 (setq start (point)
8189 end (progn (org-end-of-subtree t t)
8190 (or (bolp) (insert "\n"))
8191 (org-back-over-empty-lines)
8192 (point))
8193 what "children")
8194 (goto-char start)
8195 (show-subtree)
8196 (outline-next-heading))
8198 ;; we will sort the top-level entries in this file
8199 (goto-char (point-min))
8200 (or (org-at-heading-p) (outline-next-heading))
8201 (setq start (point))
8202 (goto-char (point-max))
8203 (beginning-of-line 1)
8204 (when (looking-at ".*?\\S-")
8205 ;; File ends in a non-white line
8206 (end-of-line 1)
8207 (insert "\n"))
8208 (setq end (point-max))
8209 (setq what "top-level")
8210 (goto-char start)
8211 (show-all)))
8213 (setq beg (point))
8214 (if (>= beg end) (error "Nothing to sort"))
8216 (looking-at "\\(\\*+\\)")
8217 (setq stars (match-string 1)
8218 re (concat "^" (regexp-quote stars) " +")
8219 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8220 txt (buffer-substring beg end))
8221 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8222 (if (and (not (equal stars "*")) (string-match re2 txt))
8223 (error "Region to sort contains a level above the first entry"))
8225 (unless sorting-type
8226 (message
8227 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8228 [t]ime [s]cheduled [d]eadline [c]reated
8229 A/N/T/S/D/C/P/O/F means reversed:"
8230 what)
8231 (setq sorting-type (read-char-exclusive))
8233 (and (= (downcase sorting-type) ?f)
8234 (setq getkey-func
8235 (org-icompleting-read "Sort using function: "
8236 obarray 'fboundp t nil nil))
8237 (setq getkey-func (intern getkey-func)))
8239 (and (= (downcase sorting-type) ?r)
8240 (setq property
8241 (org-icompleting-read "Property: "
8242 (mapcar 'list (org-buffer-property-keys t))
8243 nil t))))
8245 (message "Sorting entries...")
8247 (save-restriction
8248 (narrow-to-region start end)
8249 (let ((dcst (downcase sorting-type))
8250 (case-fold-search nil)
8251 (now (current-time)))
8252 (sort-subr
8253 (/= dcst sorting-type)
8254 ;; This function moves to the beginning character of the "record" to
8255 ;; be sorted.
8256 (lambda nil
8257 (if (re-search-forward re nil t)
8258 (goto-char (match-beginning 0))
8259 (goto-char (point-max))))
8260 ;; This function moves to the last character of the "record" being
8261 ;; sorted.
8262 (lambda nil
8263 (save-match-data
8264 (condition-case nil
8265 (outline-forward-same-level 1)
8266 (error
8267 (goto-char (point-max))))))
8268 ;; This function returns the value that gets sorted against.
8269 (lambda nil
8270 (cond
8271 ((= dcst ?n)
8272 (if (looking-at org-complex-heading-regexp)
8273 (string-to-number (match-string 4))
8274 nil))
8275 ((= dcst ?a)
8276 (if (looking-at org-complex-heading-regexp)
8277 (funcall case-func (match-string 4))
8278 nil))
8279 ((= dcst ?t)
8280 (let ((end (save-excursion (outline-next-heading) (point))))
8281 (if (or (re-search-forward org-ts-regexp end t)
8282 (re-search-forward org-ts-regexp-both end t))
8283 (org-time-string-to-seconds (match-string 0))
8284 (org-float-time now))))
8285 ((= dcst ?c)
8286 (let ((end (save-excursion (outline-next-heading) (point))))
8287 (if (re-search-forward
8288 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8289 end t)
8290 (org-time-string-to-seconds (match-string 0))
8291 (org-float-time now))))
8292 ((= dcst ?s)
8293 (let ((end (save-excursion (outline-next-heading) (point))))
8294 (if (re-search-forward org-scheduled-time-regexp end t)
8295 (org-time-string-to-seconds (match-string 1))
8296 (org-float-time now))))
8297 ((= dcst ?d)
8298 (let ((end (save-excursion (outline-next-heading) (point))))
8299 (if (re-search-forward org-deadline-time-regexp end t)
8300 (org-time-string-to-seconds (match-string 1))
8301 (org-float-time now))))
8302 ((= dcst ?p)
8303 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8304 (string-to-char (match-string 2))
8305 org-default-priority))
8306 ((= dcst ?r)
8307 (or (org-entry-get nil property) ""))
8308 ((= dcst ?o)
8309 (if (looking-at org-complex-heading-regexp)
8310 (- 9999 (length (member (match-string 2)
8311 org-todo-keywords-1)))))
8312 ((= dcst ?f)
8313 (if getkey-func
8314 (progn
8315 (setq tmp (funcall getkey-func))
8316 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8317 tmp)
8318 (error "Invalid key function `%s'" getkey-func)))
8319 (t (error "Invalid sorting type `%c'" sorting-type))))
8321 (cond
8322 ((= dcst ?a) 'string<)
8323 ((= dcst ?f) compare-func)
8324 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8325 (t nil)))))
8326 (run-hooks 'org-after-sorting-entries-or-items-hook)
8327 (message "Sorting entries...done")))
8329 (defun org-do-sort (table what &optional with-case sorting-type)
8330 "Sort TABLE of WHAT according to SORTING-TYPE.
8331 The user will be prompted for the SORTING-TYPE if the call to this
8332 function does not specify it. WHAT is only for the prompt, to indicate
8333 what is being sorted. The sorting key will be extracted from
8334 the car of the elements of the table.
8335 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8336 (unless sorting-type
8337 (message
8338 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8339 what)
8340 (setq sorting-type (read-char-exclusive)))
8341 (let ((dcst (downcase sorting-type))
8342 extractfun comparefun)
8343 ;; Define the appropriate functions
8344 (cond
8345 ((= dcst ?n)
8346 (setq extractfun 'string-to-number
8347 comparefun (if (= dcst sorting-type) '< '>)))
8348 ((= dcst ?a)
8349 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8350 (lambda(x) (downcase (org-sort-remove-invisible x))))
8351 comparefun (if (= dcst sorting-type)
8352 'string<
8353 (lambda (a b) (and (not (string< a b))
8354 (not (string= a b)))))))
8355 ((= dcst ?t)
8356 (setq extractfun
8357 (lambda (x)
8358 (if (or (string-match org-ts-regexp x)
8359 (string-match org-ts-regexp-both x))
8360 (org-float-time
8361 (org-time-string-to-time (match-string 0 x)))
8363 comparefun (if (= dcst sorting-type) '< '>)))
8364 (t (error "Invalid sorting type `%c'" sorting-type)))
8366 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8367 table)
8368 (lambda (a b) (funcall comparefun (car a) (car b))))))
8371 ;;; The orgstruct minor mode
8373 ;; Define a minor mode which can be used in other modes in order to
8374 ;; integrate the org-mode structure editing commands.
8376 ;; This is really a hack, because the org-mode structure commands use
8377 ;; keys which normally belong to the major mode. Here is how it
8378 ;; works: The minor mode defines all the keys necessary to operate the
8379 ;; structure commands, but wraps the commands into a function which
8380 ;; tests if the cursor is currently at a headline or a plain list
8381 ;; item. If that is the case, the structure command is used,
8382 ;; temporarily setting many Org-mode variables like regular
8383 ;; expressions for filling etc. However, when any of those keys is
8384 ;; used at a different location, function uses `key-binding' to look
8385 ;; up if the key has an associated command in another currently active
8386 ;; keymap (minor modes, major mode, global), and executes that
8387 ;; command. There might be problems if any of the keys is otherwise
8388 ;; used as a prefix key.
8390 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8391 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8392 ;; addresses this by checking explicitly for both bindings.
8394 (defvar orgstruct-mode-map (make-sparse-keymap)
8395 "Keymap for the minor `orgstruct-mode'.")
8397 (defvar org-local-vars nil
8398 "List of local variables, for use by `orgstruct-mode'.")
8400 ;;;###autoload
8401 (define-minor-mode orgstruct-mode
8402 "Toggle the minor mode `orgstruct-mode'.
8403 This mode is for using Org-mode structure commands in other
8404 modes. The following keys behave as if Org-mode were active, if
8405 the cursor is on a headline, or on a plain list item (both as
8406 defined by Org-mode).
8408 M-up Move entry/item up
8409 M-down Move entry/item down
8410 M-left Promote
8411 M-right Demote
8412 M-S-up Move entry/item up
8413 M-S-down Move entry/item down
8414 M-S-left Promote subtree
8415 M-S-right Demote subtree
8416 M-q Fill paragraph and items like in Org-mode
8417 C-c ^ Sort entries
8418 C-c - Cycle list bullet
8419 TAB Cycle item visibility
8420 M-RET Insert new heading/item
8421 S-M-RET Insert new TODO heading / Checkbox item
8422 C-c C-c Set tags / toggle checkbox"
8423 nil " OrgStruct" nil
8424 (org-load-modules-maybe)
8425 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8427 ;;;###autoload
8428 (defun turn-on-orgstruct ()
8429 "Unconditionally turn on `orgstruct-mode'."
8430 (orgstruct-mode 1))
8432 (defvar org-fb-vars nil)
8433 (make-variable-buffer-local 'org-fb-vars)
8434 (defun orgstruct++-mode (&optional arg)
8435 "Toggle `orgstruct-mode', the enhanced version of it.
8436 In addition to setting orgstruct-mode, this also exports all
8437 indentation and autofilling variables from org-mode into the
8438 buffer. It will also recognize item context in multiline items."
8439 (interactive "P")
8440 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8441 (if (< arg 1)
8442 (progn (orgstruct-mode -1)
8443 (mapc (lambda(v)
8444 (org-set-local (car v)
8445 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8446 org-fb-vars))
8447 (orgstruct-mode 1)
8448 (setq org-fb-vars nil)
8449 (let (var val)
8450 (mapc
8451 (lambda (x)
8452 (when (string-match
8453 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8454 (symbol-name (car x)))
8455 (setq var (car x) val (nth 1 x))
8456 (push (list var `(quote ,(eval var))) org-fb-vars)
8457 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8458 org-local-vars)
8459 (org-set-local 'orgstruct-is-++ t))))
8461 (defvar orgstruct-is-++ nil
8462 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8463 (make-variable-buffer-local 'orgstruct-is-++)
8465 ;;;###autoload
8466 (defun turn-on-orgstruct++ ()
8467 "Unconditionally turn on `orgstruct++-mode'."
8468 (orgstruct++-mode 1))
8470 (defun orgstruct-error ()
8471 "Error when there is no default binding for a structure key."
8472 (interactive)
8473 (error "This key has no function outside structure elements"))
8475 (defun orgstruct-setup ()
8476 "Setup orgstruct keymaps."
8477 (let ((nfunc 0)
8478 (bindings
8479 (list
8480 '([(meta up)] org-metaup)
8481 '([(meta down)] org-metadown)
8482 '([(meta left)] org-metaleft)
8483 '([(meta right)] org-metaright)
8484 '([(meta shift up)] org-shiftmetaup)
8485 '([(meta shift down)] org-shiftmetadown)
8486 '([(meta shift left)] org-shiftmetaleft)
8487 '([(meta shift right)] org-shiftmetaright)
8488 '([?\e (up)] org-metaup)
8489 '([?\e (down)] org-metadown)
8490 '([?\e (left)] org-metaleft)
8491 '([?\e (right)] org-metaright)
8492 '([?\e (shift up)] org-shiftmetaup)
8493 '([?\e (shift down)] org-shiftmetadown)
8494 '([?\e (shift left)] org-shiftmetaleft)
8495 '([?\e (shift right)] org-shiftmetaright)
8496 '([(shift up)] org-shiftup)
8497 '([(shift down)] org-shiftdown)
8498 '([(shift left)] org-shiftleft)
8499 '([(shift right)] org-shiftright)
8500 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8501 '("\M-q" fill-paragraph)
8502 '("\C-c^" org-sort)
8503 '("\C-c-" org-cycle-list-bullet)))
8504 elt key fun cmd)
8505 (while (setq elt (pop bindings))
8506 (setq nfunc (1+ nfunc))
8507 (setq key (org-key (car elt))
8508 fun (nth 1 elt)
8509 cmd (orgstruct-make-binding fun nfunc key))
8510 (org-defkey orgstruct-mode-map key cmd))
8512 ;; Special treatment needed for TAB and RET
8513 (org-defkey orgstruct-mode-map [(tab)]
8514 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8515 (org-defkey orgstruct-mode-map "\C-i"
8516 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8518 (org-defkey orgstruct-mode-map "\M-\C-m"
8519 (orgstruct-make-binding 'org-insert-heading 105
8520 "\M-\C-m" [(meta return)]))
8521 (org-defkey orgstruct-mode-map [(meta return)]
8522 (orgstruct-make-binding 'org-insert-heading 106
8523 [(meta return)] "\M-\C-m"))
8525 (org-defkey orgstruct-mode-map [(shift meta return)]
8526 (orgstruct-make-binding 'org-insert-todo-heading 107
8527 [(meta return)] "\M-\C-m"))
8529 (org-defkey orgstruct-mode-map "\e\C-m"
8530 (orgstruct-make-binding 'org-insert-heading 108
8531 "\e\C-m" [?\e (return)]))
8532 (org-defkey orgstruct-mode-map [?\e (return)]
8533 (orgstruct-make-binding 'org-insert-heading 109
8534 [?\e (return)] "\e\C-m"))
8535 (org-defkey orgstruct-mode-map [?\e (shift return)]
8536 (orgstruct-make-binding 'org-insert-todo-heading 110
8537 [?\e (return)] "\e\C-m"))
8539 (unless org-local-vars
8540 (setq org-local-vars (org-get-local-variables)))
8544 (defun orgstruct-make-binding (fun n &rest keys)
8545 "Create a function for binding in the structure minor mode.
8546 FUN is the command to call inside a table. N is used to create a unique
8547 command name. KEYS are keys that should be checked in for a command
8548 to execute outside of tables."
8549 (eval
8550 (list 'defun
8551 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8552 '(arg)
8553 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8554 "Outside of structure, run the binding of `"
8555 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8556 "'.")
8557 '(interactive "p")
8558 (list 'if
8559 `(org-context-p 'headline 'item
8560 (and orgstruct-is-++
8561 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8562 'item-body))
8563 (list 'org-run-like-in-org-mode (list 'quote fun))
8564 (list 'let '(orgstruct-mode)
8565 (list 'call-interactively
8566 (append '(or)
8567 (mapcar (lambda (k)
8568 (list 'key-binding k))
8569 keys)
8570 '('orgstruct-error))))))))
8572 (defun org-context-p (&rest contexts)
8573 "Check if local context is any of CONTEXTS.
8574 Possible values in the list of contexts are `table', `headline', and `item'."
8575 (let ((pos (point)))
8576 (goto-char (point-at-bol))
8577 (prog1 (or (and (memq 'table contexts)
8578 (looking-at "[ \t]*|"))
8579 (and (memq 'headline contexts)
8580 (looking-at org-outline-regexp))
8581 (and (memq 'item contexts)
8582 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8583 (and (memq 'item-body contexts)
8584 (org-in-item-p)))
8585 (goto-char pos))))
8587 (defun org-get-local-variables ()
8588 "Return a list of all local variables in an Org mode buffer."
8589 (let (varlist)
8590 (with-current-buffer (get-buffer-create "*Org tmp*")
8591 (erase-buffer)
8592 (org-mode)
8593 (setq varlist (buffer-local-variables)))
8594 (kill-buffer "*Org tmp*")
8595 (delq nil
8596 (mapcar
8597 (lambda (x)
8598 (setq x
8599 (if (symbolp x)
8600 (list x)
8601 (list (car x) (list 'quote (cdr x)))))
8602 (if (string-match
8603 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8604 (symbol-name (car x)))
8605 x nil))
8606 varlist))))
8608 (defun org-clone-local-variables (from-buffer &optional regexp)
8609 "Clone local variables from FROM-BUFFER.
8610 Optional argument REGEXP selects variables to clone."
8611 (mapc
8612 (lambda (pair)
8613 (and (symbolp (car pair))
8614 (or (null regexp)
8615 (string-match regexp (symbol-name (car pair))))
8616 (set (make-local-variable (car pair))
8617 (cdr pair))))
8618 (buffer-local-variables from-buffer)))
8620 ;;;###autoload
8621 (defun org-run-like-in-org-mode (cmd)
8622 "Run a command, pretending that the current buffer is in Org-mode.
8623 This will temporarily bind local variables that are typically bound in
8624 Org-mode to the values they have in Org-mode, and then interactively
8625 call CMD."
8626 (org-load-modules-maybe)
8627 (unless org-local-vars
8628 (setq org-local-vars (org-get-local-variables)))
8629 (eval (list 'let org-local-vars
8630 (list 'call-interactively (list 'quote cmd)))))
8632 ;;;; Archiving
8634 (defun org-get-category (&optional pos force-refresh)
8635 "Get the category applying to position POS."
8636 (save-match-data
8637 (if force-refresh (org-refresh-category-properties))
8638 (let ((pos (or pos (point))))
8639 (or (get-text-property pos 'org-category)
8640 (progn (org-refresh-category-properties)
8641 (get-text-property pos 'org-category))))))
8643 (defun org-refresh-category-properties ()
8644 "Refresh category text properties in the buffer."
8645 (let ((inhibit-read-only t)
8646 (def-cat (cond
8647 ((null org-category)
8648 (if buffer-file-name
8649 (file-name-sans-extension
8650 (file-name-nondirectory buffer-file-name))
8651 "???"))
8652 ((symbolp org-category) (symbol-name org-category))
8653 (t org-category)))
8654 beg end cat pos optionp)
8655 (org-unmodified
8656 (save-excursion
8657 (save-restriction
8658 (widen)
8659 (goto-char (point-min))
8660 (put-text-property (point) (point-max) 'org-category def-cat)
8661 (while (re-search-forward
8662 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8663 (setq pos (match-end 0)
8664 optionp (equal (char-after (match-beginning 0)) ?#)
8665 cat (org-trim (match-string 2)))
8666 (if optionp
8667 (setq beg (point-at-bol) end (point-max))
8668 (org-back-to-heading t)
8669 (setq beg (point) end (org-end-of-subtree t t)))
8670 (put-text-property beg end 'org-category cat)
8671 (put-text-property beg end 'org-category-position beg)
8672 (goto-char pos)))))))
8675 ;;;; Link Stuff
8677 ;;; Link abbreviations
8679 (defun org-link-expand-abbrev (link)
8680 "Apply replacements as defined in `org-link-abbrev-alist'."
8681 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8682 (let* ((key (match-string 1 link))
8683 (as (or (assoc key org-link-abbrev-alist-local)
8684 (assoc key org-link-abbrev-alist)))
8685 (tag (and (match-end 2) (match-string 3 link)))
8686 rpl)
8687 (if (not as)
8688 link
8689 (setq rpl (cdr as))
8690 (cond
8691 ((symbolp rpl) (funcall rpl tag))
8692 ((string-match "%(\\([^)]+\\))" rpl)
8693 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8694 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8695 ((string-match "%h" rpl)
8696 (replace-match (url-hexify-string (or tag "")) t t rpl))
8697 (t (concat rpl tag)))))
8698 link))
8700 ;;; Storing and inserting links
8702 (defvar org-insert-link-history nil
8703 "Minibuffer history for links inserted with `org-insert-link'.")
8705 (defvar org-stored-links nil
8706 "Contains the links stored with `org-store-link'.")
8708 (defvar org-store-link-plist nil
8709 "Plist with info about the most recently link created with `org-store-link'.")
8711 (defvar org-link-protocols nil
8712 "Link protocols added to Org-mode using `org-add-link-type'.")
8714 (defvar org-store-link-functions nil
8715 "List of functions that are called to create and store a link.
8716 Each function will be called in turn until one returns a non-nil
8717 value. Each function should check if it is responsible for creating
8718 this link (for example by looking at the major mode).
8719 If not, it must exit and return nil.
8720 If yes, it should return a non-nil value after a calling
8721 `org-store-link-props' with a list of properties and values.
8722 Special properties are:
8724 :type The link prefix, like \"http\". This must be given.
8725 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8726 This is obligatory as well.
8727 :description Optional default description for the second pair
8728 of brackets in an Org-mode link. The user can still change
8729 this when inserting this link into an Org-mode buffer.
8731 In addition to these, any additional properties can be specified
8732 and then used in remember templates.")
8734 (defun org-add-link-type (type &optional follow export)
8735 "Add TYPE to the list of `org-link-types'.
8736 Re-compute all regular expressions depending on `org-link-types'
8738 FOLLOW and EXPORT are two functions.
8740 FOLLOW should take the link path as the single argument and do whatever
8741 is necessary to follow the link, for example find a file or display
8742 a mail message.
8744 EXPORT should format the link path for export to one of the export formats.
8745 It should be a function accepting three arguments:
8747 path the path of the link, the text after the prefix (like \"http:\")
8748 desc the description of the link, if any, or a description added by
8749 org-export-normalize-links if there is none
8750 format the export format, a symbol like `html' or `latex' or `ascii'..
8752 The function may use the FORMAT information to return different values
8753 depending on the format. The return value will be put literally into
8754 the exported file. If the return value is nil, this means Org should
8755 do what it normally does with links which do not have EXPORT defined.
8757 Org-mode has a built-in default for exporting links. If you are happy with
8758 this default, there is no need to define an export function for the link
8759 type. For a simple example of an export function, see `org-bbdb.el'."
8760 (add-to-list 'org-link-types type t)
8761 (org-make-link-regexps)
8762 (if (assoc type org-link-protocols)
8763 (setcdr (assoc type org-link-protocols) (list follow export))
8764 (push (list type follow export) org-link-protocols)))
8766 (defvar org-agenda-buffer-name)
8768 ;;;###autoload
8769 (defun org-store-link (arg)
8770 "\\<org-mode-map>Store an org-link to the current location.
8771 This link is added to `org-stored-links' and can later be inserted
8772 into an org-buffer with \\[org-insert-link].
8774 For some link types, a prefix arg is interpreted:
8775 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8776 For file links, arg negates `org-context-in-file-links'."
8777 (interactive "P")
8778 (org-load-modules-maybe)
8779 (setq org-store-link-plist nil) ; reset
8780 (org-with-limited-levels
8781 (let (link cpltxt desc description search txt custom-id agenda-link)
8782 (cond
8784 ((run-hook-with-args-until-success 'org-store-link-functions)
8785 (setq link (plist-get org-store-link-plist :link)
8786 desc (or (plist-get org-store-link-plist :description) link)))
8788 ((org-src-edit-buffer-p)
8789 (let (label gc)
8790 (while (or (not label)
8791 (save-excursion
8792 (save-restriction
8793 (widen)
8794 (goto-char (point-min))
8795 (re-search-forward
8796 (regexp-quote (format org-coderef-label-format label))
8797 nil t))))
8798 (when label (message "Label exists already") (sit-for 2))
8799 (setq label (read-string "Code line label: " label)))
8800 (end-of-line 1)
8801 (setq link (format org-coderef-label-format label))
8802 (setq gc (- 79 (length link)))
8803 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8804 (insert link)
8805 (setq link (concat "(" label ")") desc nil)))
8807 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8808 ;; We are in the agenda, link to referenced location
8809 (let ((m (or (get-text-property (point) 'org-hd-marker)
8810 (get-text-property (point) 'org-marker))))
8811 (when m
8812 (org-with-point-at m
8813 (setq agenda-link
8814 (if (org-called-interactively-p 'any)
8815 (call-interactively 'org-store-link)
8816 (org-store-link nil)))))))
8818 ((eq major-mode 'calendar-mode)
8819 (let ((cd (calendar-cursor-to-date)))
8820 (setq link
8821 (format-time-string
8822 (car org-time-stamp-formats)
8823 (apply 'encode-time
8824 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8825 nil nil nil))))
8826 (org-store-link-props :type "calendar" :date cd)))
8828 ((eq major-mode 'w3-mode)
8829 (setq cpltxt (if (and (buffer-name)
8830 (not (string-match "Untitled" (buffer-name))))
8831 (buffer-name)
8832 (url-view-url t))
8833 link (org-make-link (url-view-url t)))
8834 (org-store-link-props :type "w3" :url (url-view-url t)))
8836 ((eq major-mode 'w3m-mode)
8837 (setq cpltxt (or w3m-current-title w3m-current-url)
8838 link (org-make-link w3m-current-url))
8839 (org-store-link-props :type "w3m" :url (url-view-url t)))
8841 ((setq search (run-hook-with-args-until-success
8842 'org-create-file-search-functions))
8843 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8844 "::" search))
8845 (setq cpltxt (or description link)))
8847 ((eq major-mode 'image-mode)
8848 (setq cpltxt (concat "file:"
8849 (abbreviate-file-name buffer-file-name))
8850 link (org-make-link cpltxt))
8851 (org-store-link-props :type "image" :file buffer-file-name))
8853 ((eq major-mode 'dired-mode)
8854 ;; link to the file in the current line
8855 (let ((file (dired-get-filename nil t)))
8856 (setq file (if file
8857 (abbreviate-file-name
8858 (expand-file-name (dired-get-filename nil t)))
8859 ;; otherwise, no file so use current directory.
8860 default-directory))
8861 (setq cpltxt (concat "file:" file)
8862 link (org-make-link cpltxt))))
8864 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8865 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8866 (cond
8867 ((org-in-regexp "<<\\(.*?\\)>>")
8868 (setq cpltxt
8869 (concat "file:"
8870 (abbreviate-file-name
8871 (buffer-file-name (buffer-base-buffer)))
8872 "::" (match-string 1))
8873 link (org-make-link cpltxt)))
8874 ((and (featurep 'org-id)
8875 (or (eq org-link-to-org-use-id t)
8876 (and (eq org-link-to-org-use-id 'create-if-interactive)
8877 (org-called-interactively-p 'any))
8878 (and (eq org-link-to-org-use-id
8879 'create-if-interactive-and-no-custom-id)
8880 (org-called-interactively-p 'any)
8881 (not custom-id))
8882 (and org-link-to-org-use-id
8883 (org-entry-get nil "ID"))))
8884 ;; We can make a link using the ID.
8885 (setq link (condition-case nil
8886 (prog1 (org-id-store-link)
8887 (setq desc (plist-get org-store-link-plist
8888 :description)))
8889 (error
8890 ;; probably before first headline, link to file only
8891 (concat "file:"
8892 (abbreviate-file-name
8893 (buffer-file-name (buffer-base-buffer))))))))
8895 ;; Just link to current headline
8896 (setq cpltxt (concat "file:"
8897 (abbreviate-file-name
8898 (buffer-file-name (buffer-base-buffer)))))
8899 ;; Add a context search string
8900 (when (org-xor org-context-in-file-links arg)
8901 (setq txt (cond
8902 ((org-at-heading-p) nil)
8903 ((org-region-active-p)
8904 (buffer-substring (region-beginning) (region-end)))
8905 (t nil)))
8906 (when (or (null txt) (string-match "\\S-" txt))
8907 (setq cpltxt
8908 (concat cpltxt "::"
8909 (condition-case nil
8910 (org-make-org-heading-search-string txt)
8911 (error "")))
8912 desc (or (nth 4 (ignore-errors
8913 (org-heading-components))) "NONE"))))
8914 (if (string-match "::\\'" cpltxt)
8915 (setq cpltxt (substring cpltxt 0 -2)))
8916 (setq link (org-make-link cpltxt)))))
8918 ((buffer-file-name (buffer-base-buffer))
8919 ;; Just link to this file here.
8920 (setq cpltxt (concat "file:"
8921 (abbreviate-file-name
8922 (buffer-file-name (buffer-base-buffer)))))
8923 ;; Add a context string
8924 (when (org-xor org-context-in-file-links arg)
8925 (setq txt (if (org-region-active-p)
8926 (buffer-substring (region-beginning) (region-end))
8927 (buffer-substring (point-at-bol) (point-at-eol))))
8928 ;; Only use search option if there is some text.
8929 (when (string-match "\\S-" txt)
8930 (setq cpltxt
8931 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8932 desc "NONE")))
8933 (setq link (org-make-link cpltxt)))
8935 ((org-called-interactively-p 'interactive)
8936 (error "Cannot link to a buffer which is not visiting a file"))
8938 (t (setq link nil)))
8940 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8941 (setq link (or link cpltxt)
8942 desc (or desc cpltxt))
8943 (if (equal desc "NONE") (setq desc nil))
8945 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8946 (progn
8947 (setq org-stored-links
8948 (cons (list link desc) org-stored-links))
8949 (message "Stored: %s" (or desc link))
8950 (when custom-id
8951 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8952 "::#" custom-id))
8953 (setq org-stored-links
8954 (cons (list link desc) org-stored-links))))
8955 (or agenda-link (and link (org-make-link-string link desc)))))))
8957 (defun org-store-link-props (&rest plist)
8958 "Store link properties, extract names and addresses."
8959 (let (x adr)
8960 (when (setq x (plist-get plist :from))
8961 (setq adr (mail-extract-address-components x))
8962 (setq plist (plist-put plist :fromname (car adr)))
8963 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8964 (when (setq x (plist-get plist :to))
8965 (setq adr (mail-extract-address-components x))
8966 (setq plist (plist-put plist :toname (car adr)))
8967 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8968 (let ((from (plist-get plist :from))
8969 (to (plist-get plist :to)))
8970 (when (and from to org-from-is-user-regexp)
8971 (setq plist
8972 (plist-put plist :fromto
8973 (if (string-match org-from-is-user-regexp from)
8974 (concat "to %t")
8975 (concat "from %f"))))))
8976 (setq org-store-link-plist plist))
8978 (defun org-add-link-props (&rest plist)
8979 "Add these properties to the link property list."
8980 (let (key value)
8981 (while plist
8982 (setq key (pop plist) value (pop plist))
8983 (setq org-store-link-plist
8984 (plist-put org-store-link-plist key value)))))
8986 (defun org-email-link-description (&optional fmt)
8987 "Return the description part of an email link.
8988 This takes information from `org-store-link-plist' and formats it
8989 according to FMT (default from `org-email-link-description-format')."
8990 (setq fmt (or fmt org-email-link-description-format))
8991 (let* ((p org-store-link-plist)
8992 (to (plist-get p :toaddress))
8993 (from (plist-get p :fromaddress))
8994 (table
8995 (list
8996 (cons "%c" (plist-get p :fromto))
8997 (cons "%F" (plist-get p :from))
8998 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8999 (cons "%T" (plist-get p :to))
9000 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9001 (cons "%s" (plist-get p :subject))
9002 (cons "%d" (plist-get p :date))
9003 (cons "%m" (plist-get p :message-id)))))
9004 (when (string-match "%c" fmt)
9005 ;; Check if the user wrote this message
9006 (if (and org-from-is-user-regexp from to
9007 (save-match-data (string-match org-from-is-user-regexp from)))
9008 (setq fmt (replace-match "to %t" t t fmt))
9009 (setq fmt (replace-match "from %f" t t fmt))))
9010 (org-replace-escapes fmt table)))
9012 (defun org-make-org-heading-search-string (&optional string heading)
9013 "Make search string for STRING or current headline."
9014 (interactive)
9015 (let ((s (or string (org-get-heading)))
9016 (lines org-context-in-file-links))
9017 (unless (and string (not heading))
9018 ;; We are using a headline, clean up garbage in there.
9019 (if (string-match org-todo-regexp s)
9020 (setq s (replace-match "" t t s)))
9021 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9022 (setq s (replace-match "" t t s)))
9023 (setq s (org-trim s))
9024 (if (string-match (concat "^\\(" org-quote-string "\\|"
9025 org-comment-string "\\)") s)
9026 (setq s (replace-match "" t t s)))
9027 (while (string-match org-ts-regexp s)
9028 (setq s (replace-match "" t t s))))
9029 (or string (setq s (concat "*" s))) ; Add * for headlines
9030 (when (and string (integerp lines) (> lines 0))
9031 (let ((slines (org-split-string s "\n")))
9032 (when (< lines (length slines))
9033 (setq s (mapconcat
9034 'identity
9035 (reverse (nthcdr (- (length slines) lines)
9036 (reverse slines))) "\n")))))
9037 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9039 (defun org-make-link (&rest strings)
9040 "Concatenate STRINGS."
9041 (apply 'concat strings))
9043 (defun org-make-link-string (link &optional description)
9044 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9045 (unless (string-match "\\S-" link)
9046 (error "Empty link"))
9047 (when (and description
9048 (stringp description)
9049 (not (string-match "\\S-" description)))
9050 (setq description nil))
9051 (when (stringp description)
9052 ;; Remove brackets from the description, they are fatal.
9053 (while (string-match "\\[" description)
9054 (setq description (replace-match "{" t t description)))
9055 (while (string-match "\\]" description)
9056 (setq description (replace-match "}" t t description))))
9057 (when (equal link description)
9058 ;; No description needed, it is identical
9059 (setq description nil))
9060 (when (and (not description)
9061 (not (string-match (org-image-file-name-regexp) link))
9062 (not (equal link (org-link-escape link))))
9063 (setq description (org-extract-attributes link)))
9064 (setq link
9065 (cond ((string-match (org-image-file-name-regexp) link) link)
9066 ((string-match org-link-types-re link)
9067 (concat (match-string 1 link)
9068 (org-link-escape (substring link (match-end 1)))))
9069 (t (org-link-escape link))))
9070 (concat "[[" link "]"
9071 (if description (concat "[" description "]") "")
9072 "]"))
9074 (defconst org-link-escape-chars
9075 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9076 "List of characters that should be escaped in link.
9077 This is the list that is used for internal purposes.")
9079 (defvar org-url-encoding-use-url-hexify nil)
9081 (defconst org-link-escape-chars-browser
9082 '(?\ )
9083 "List of escapes for characters that are problematic in links.
9084 This is the list that is used before handing over to the browser.")
9086 (defun org-link-escape (text &optional table merge)
9087 "Return percent escaped representation of TEXT.
9088 TEXT is a string with the text to escape.
9089 Optional argument TABLE is a list with characters that should be
9090 escaped. When nil, `org-link-escape-chars' is used.
9091 If optional argument MERGE is set, merge TABLE into
9092 `org-link-escape-chars'."
9093 (if (and org-url-encoding-use-url-hexify (not table))
9094 (url-hexify-string text)
9095 (cond
9096 ((and table merge)
9097 (mapc (lambda (defchr)
9098 (unless (member defchr table)
9099 (setq table (cons defchr table)))) org-link-escape-chars))
9100 ((null table)
9101 (setq table org-link-escape-chars)))
9102 (mapconcat
9103 (lambda (char)
9104 (if (or (member char table)
9105 (< char 32) (= char 37) (> char 126))
9106 (mapconcat (lambda (sequence-element)
9107 (format "%%%.2X" sequence-element))
9108 (or (encode-coding-char char 'utf-8)
9109 (error "Unable to percent escape character: %s"
9110 (char-to-string char))) "")
9111 (char-to-string char))) text "")))
9113 (defun org-link-unescape (str)
9114 "Unhex hexified Unicode strings as returned from the JavaScript function
9115 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9116 (unless (and (null str) (string= "" str))
9117 (let ((pos 0) (case-fold-search t) unhexed)
9118 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9119 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9120 (setq str (replace-match unhexed t t str))
9121 (setq pos (+ pos (length unhexed))))))
9122 str)
9124 (defun org-link-unescape-compound (hex)
9125 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9126 Note: this function also decodes single byte encodings like
9127 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9128 (save-match-data
9129 (let* ((bytes (cdr (split-string hex "%")))
9130 (ret "")
9131 (eat 0)
9132 (sum 0))
9133 (while bytes
9134 (let* ((val (string-to-number (pop bytes) 16))
9135 (shift-xor
9136 (if (= 0 eat)
9137 (cond
9138 ((>= val 252) (cons 6 252))
9139 ((>= val 248) (cons 5 248))
9140 ((>= val 240) (cons 4 240))
9141 ((>= val 224) (cons 3 224))
9142 ((>= val 192) (cons 2 192))
9143 (t (cons 0 0)))
9144 (cons 6 128))))
9145 (if (>= val 192) (setq eat (car shift-xor)))
9146 (setq val (logxor val (cdr shift-xor)))
9147 (setq sum (+ (lsh sum (car shift-xor)) val))
9148 (if (> eat 0) (setq eat (- eat 1)))
9149 (cond
9150 ((= 0 eat) ;multi byte
9151 (setq ret (concat ret (org-char-to-string sum)))
9152 (setq sum 0))
9153 ((not bytes) ; single byte(s)
9154 (setq ret (org-link-unescape-single-byte-sequence hex))))
9155 )) ;; end (while bytes
9156 ret )))
9158 (defun org-link-unescape-single-byte-sequence (hex)
9159 "Unhexify hex-encoded single byte character sequences."
9160 (mapconcat (lambda (byte)
9161 (char-to-string (string-to-number byte 16)))
9162 (cdr (split-string hex "%")) ""))
9164 (defun org-xor (a b)
9165 "Exclusive or."
9166 (if a (not b) b))
9168 (defun org-fixup-message-id-for-http (s)
9169 "Replace special characters in a message id, so it can be used in an http query."
9170 (when (string-match "%" s)
9171 (setq s (mapconcat (lambda (c)
9172 (if (eq c ?%)
9173 "%25"
9174 (char-to-string c)))
9175 s "")))
9176 (while (string-match "<" s)
9177 (setq s (replace-match "%3C" t t s)))
9178 (while (string-match ">" s)
9179 (setq s (replace-match "%3E" t t s)))
9180 (while (string-match "@" s)
9181 (setq s (replace-match "%40" t t s)))
9184 (defun org-link-prettify (link)
9185 "Return a human-readable representation of LINK.
9186 The car of LINK must be a raw link the cdr of LINK must be either
9187 a link description or nil."
9188 (let ((desc (or (cadr link) "<no description>")))
9189 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9190 "[[" (car link) "]]")))
9192 ;;;###autoload
9193 (defun org-insert-link-global ()
9194 "Insert a link like Org-mode does.
9195 This command can be called in any mode to insert a link in Org-mode syntax."
9196 (interactive)
9197 (org-load-modules-maybe)
9198 (org-run-like-in-org-mode 'org-insert-link))
9200 (defun org-insert-all-links (&optional keep)
9201 "Insert all links in `org-stored-links'."
9202 (interactive "P")
9203 (let ((links (copy-sequence org-stored-links)) l)
9204 (while (setq l (if keep (pop links) (pop org-stored-links)))
9205 (insert "- ")
9206 (org-insert-link nil (car l) (cadr l))
9207 (insert "\n"))))
9209 (defun org-insert-link (&optional complete-file link-location default-description)
9210 "Insert a link. At the prompt, enter the link.
9212 Completion can be used to insert any of the link protocol prefixes like
9213 http or ftp in use.
9215 The history can be used to select a link previously stored with
9216 `org-store-link'. When the empty string is entered (i.e. if you just
9217 press RET at the prompt), the link defaults to the most recently
9218 stored link. As SPC triggers completion in the minibuffer, you need to
9219 use M-SPC or C-q SPC to force the insertion of a space character.
9221 You will also be prompted for a description, and if one is given, it will
9222 be displayed in the buffer instead of the link.
9224 If there is already a link at point, this command will allow you to edit link
9225 and description parts.
9227 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9228 be selected using completion. The path to the file will be relative to the
9229 current directory if the file is in the current directory or a subdirectory.
9230 Otherwise, the link will be the absolute path as completed in the minibuffer
9231 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9232 option `org-link-file-path-type'.
9234 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9235 the current directory or below.
9237 With three \\[universal-argument] prefixes, negate the meaning of
9238 `org-keep-stored-link-after-insertion'.
9240 If `org-make-link-description-function' is non-nil, this function will be
9241 called with the link target, and the result will be the default
9242 link description.
9244 If the LINK-LOCATION parameter is non-nil, this value will be
9245 used as the link location instead of reading one interactively.
9247 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9248 be used as the default description."
9249 (interactive "P")
9250 (let* ((wcf (current-window-configuration))
9251 (region (if (org-region-active-p)
9252 (buffer-substring (region-beginning) (region-end))))
9253 (remove (and region (list (region-beginning) (region-end))))
9254 (desc region)
9255 tmphist ; byte-compile incorrectly complains about this
9256 (link link-location)
9257 entry file all-prefixes)
9258 (cond
9259 (link-location) ; specified by arg, just use it.
9260 ((org-in-regexp org-bracket-link-regexp 1)
9261 ;; We do have a link at point, and we are going to edit it.
9262 (setq remove (list (match-beginning 0) (match-end 0)))
9263 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9264 (setq link (read-string "Link: "
9265 (org-link-unescape
9266 (org-match-string-no-properties 1)))))
9267 ((or (org-in-regexp org-angle-link-re)
9268 (org-in-regexp org-plain-link-re))
9269 ;; Convert to bracket link
9270 (setq remove (list (match-beginning 0) (match-end 0))
9271 link (read-string "Link: "
9272 (org-remove-angle-brackets (match-string 0)))))
9273 ((member complete-file '((4) (16)))
9274 ;; Completing read for file names.
9275 (setq link (org-file-complete-link complete-file)))
9277 ;; Read link, with completion for stored links.
9278 (with-output-to-temp-buffer "*Org Links*"
9279 (princ "Insert a link.
9280 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9281 (when org-stored-links
9282 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9283 (princ (mapconcat 'org-link-prettify
9284 (reverse org-stored-links) "\n"))))
9285 (let ((cw (selected-window)))
9286 (select-window (get-buffer-window "*Org Links*" 'visible))
9287 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9288 (unless (pos-visible-in-window-p (point-max))
9289 (org-fit-window-to-buffer))
9290 (and (window-live-p cw) (select-window cw)))
9291 ;; Fake a link history, containing the stored links.
9292 (setq tmphist (append (mapcar 'car org-stored-links)
9293 org-insert-link-history))
9294 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9295 (mapcar 'car org-link-abbrev-alist)
9296 org-link-types))
9297 (unwind-protect
9298 (progn
9299 (setq link
9300 (let ((org-completion-use-ido nil)
9301 (org-completion-use-iswitchb nil))
9302 (org-completing-read
9303 "Link: "
9304 (append
9305 (mapcar (lambda (x) (list (concat x ":")))
9306 all-prefixes)
9307 (mapcar 'car org-stored-links))
9308 nil nil nil
9309 'tmphist
9310 (car (car org-stored-links)))))
9311 (if (not (string-match "\\S-" link))
9312 (error "No link selected"))
9313 (if (or (member link all-prefixes)
9314 (and (equal ":" (substring link -1))
9315 (member (substring link 0 -1) all-prefixes)
9316 (setq link (substring link 0 -1))))
9317 (setq link (org-link-try-special-completion link))))
9318 (set-window-configuration wcf)
9319 (kill-buffer "*Org Links*"))
9320 (setq entry (assoc link org-stored-links))
9321 (or entry (push link org-insert-link-history))
9322 (setq desc (or desc (nth 1 entry)))))
9324 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9325 (not org-keep-stored-link-after-insertion))
9326 (setq org-stored-links (delq (assoc link org-stored-links)
9327 org-stored-links)))
9329 (if (string-match org-plain-link-re link)
9330 ;; URL-like link, normalize the use of angular brackets.
9331 (setq link (org-make-link (org-remove-angle-brackets link))))
9333 ;; Check if we are linking to the current file with a search option
9334 ;; If yes, simplify the link by using only the search option.
9335 (when (and buffer-file-name
9336 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9337 (let* ((path (match-string 1 link))
9338 (case-fold-search nil)
9339 (search (match-string 2 link)))
9340 (save-match-data
9341 (if (equal (file-truename buffer-file-name) (file-truename path))
9342 ;; We are linking to this same file, with a search option
9343 (setq link search)))))
9345 ;; Check if we can/should use a relative path. If yes, simplify the link
9346 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9347 (let* ((type (match-string 1 link))
9348 (path (match-string 2 link))
9349 (origpath path)
9350 (case-fold-search nil))
9351 (cond
9352 ((or (eq org-link-file-path-type 'absolute)
9353 (equal complete-file '(16)))
9354 (setq path (abbreviate-file-name (expand-file-name path))))
9355 ((eq org-link-file-path-type 'noabbrev)
9356 (setq path (expand-file-name path)))
9357 ((eq org-link-file-path-type 'relative)
9358 (setq path (file-relative-name path)))
9360 (save-match-data
9361 (if (string-match (concat "^" (regexp-quote
9362 (expand-file-name
9363 (file-name-as-directory
9364 default-directory))))
9365 (expand-file-name path))
9366 ;; We are linking a file with relative path name.
9367 (setq path (substring (expand-file-name path)
9368 (match-end 0)))
9369 (setq path (abbreviate-file-name (expand-file-name path)))))))
9370 (setq link (concat type path))
9371 (if (equal desc origpath)
9372 (setq desc path))))
9374 (if org-make-link-description-function
9375 (setq desc (funcall org-make-link-description-function link desc))
9376 (if default-description (setq desc default-description)
9377 (setq desc (read-string "Description: " desc))))
9379 (unless (string-match "\\S-" desc) (setq desc nil))
9380 (if remove (apply 'delete-region remove))
9381 (insert (org-make-link-string link desc))))
9383 (defun org-link-try-special-completion (type)
9384 "If there is completion support for link type TYPE, offer it."
9385 (let ((fun (intern (concat "org-" type "-complete-link"))))
9386 (if (functionp fun)
9387 (funcall fun)
9388 (read-string "Link (no completion support): " (concat type ":")))))
9390 (defun org-file-complete-link (&optional arg)
9391 "Create a file link using completion."
9392 (let (file link)
9393 (setq file (read-file-name "File: "))
9394 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9395 (pwd1 (file-name-as-directory (abbreviate-file-name
9396 (expand-file-name ".")))))
9397 (cond
9398 ((equal arg '(16))
9399 (setq link (org-make-link
9400 "file:"
9401 (abbreviate-file-name (expand-file-name file)))))
9402 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9403 (setq link (org-make-link "file:" (match-string 1 file))))
9404 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9405 (expand-file-name file))
9406 (setq link (org-make-link
9407 "file:" (match-string 1 (expand-file-name file)))))
9408 (t (setq link (org-make-link "file:" file)))))
9409 link))
9411 (defun org-completing-read (&rest args)
9412 "Completing-read with SPACE being a normal character."
9413 (let ((enable-recursive-minibuffers t)
9414 (minibuffer-local-completion-map
9415 (copy-keymap minibuffer-local-completion-map)))
9416 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9417 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9418 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9419 (apply 'org-icompleting-read args)))
9421 (defun org-completing-read-no-i (&rest args)
9422 (let (org-completion-use-ido org-completion-use-iswitchb)
9423 (apply 'org-completing-read args)))
9425 (defun org-iswitchb-completing-read (prompt choices &rest args)
9426 "Use iswitch as a completing-read replacement to choose from choices.
9427 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9428 from."
9429 (let* ((iswitchb-use-virtual-buffers nil)
9430 (iswitchb-make-buflist-hook
9431 (lambda ()
9432 (setq iswitchb-temp-buflist choices))))
9433 (iswitchb-read-buffer prompt)))
9435 (defun org-icompleting-read (&rest args)
9436 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9437 (org-without-partial-completion
9438 (if (and org-completion-use-ido
9439 (fboundp 'ido-completing-read)
9440 (boundp 'ido-mode) ido-mode
9441 (listp (second args)))
9442 (let ((ido-enter-matching-directory nil))
9443 (apply 'ido-completing-read (concat (car args))
9444 (if (consp (car (nth 1 args)))
9445 (mapcar 'car (nth 1 args))
9446 (nth 1 args))
9447 (cddr args)))
9448 (if (and org-completion-use-iswitchb
9449 (boundp 'iswitchb-mode) iswitchb-mode
9450 (listp (second args)))
9451 (apply 'org-iswitchb-completing-read (concat (car args))
9452 (if (consp (car (nth 1 args)))
9453 (mapcar 'car (nth 1 args))
9454 (nth 1 args))
9455 (cddr args))
9456 (apply 'completing-read args)))))
9458 (defun org-extract-attributes (s)
9459 "Extract the attributes cookie from a string and set as text property."
9460 (let (a attr (start 0) key value)
9461 (save-match-data
9462 (when (string-match "{{\\([^}]+\\)}}$" s)
9463 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9464 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9465 (setq key (match-string 1 a) value (match-string 2 a)
9466 start (match-end 0)
9467 attr (plist-put attr (intern key) value))))
9468 (org-add-props s nil 'org-attr attr))
9471 (defun org-extract-attributes-from-string (tag)
9472 (let (key value attr)
9473 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9474 (setq key (match-string 1 tag) value (match-string 2 tag)
9475 tag (replace-match "" t t tag)
9476 attr (plist-put attr (intern key) value)))
9477 (cons tag attr)))
9479 (defun org-attributes-to-string (plist)
9480 "Format a property list into an HTML attribute list."
9481 (let ((s "") key value)
9482 (while plist
9483 (setq key (pop plist) value (pop plist))
9484 (and value
9485 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9488 ;;; Opening/following a link
9490 (defvar org-link-search-failed nil)
9492 (defvar org-open-link-functions nil
9493 "Hook for functions finding a plain text link.
9494 These functions must take a single argument, the link content.
9495 They will be called for links that look like [[link text][description]]
9496 when LINK TEXT does not have a protocol like \"http:\" and does not look
9497 like a filename (e.g. \"./blue.png\").
9499 These functions will be called *before* Org attempts to resolve the
9500 link by doing text searches in the current buffer - so if you want a
9501 link \"[[target]]\" to still find \"<<target>>\", your function should
9502 handle this as a special case.
9504 When the function does handle the link, it must return a non-nil value.
9505 If it decides that it is not responsible for this link, it must return
9506 nil to indicate that that Org-mode can continue with other options
9507 like exact and fuzzy text search.")
9509 (defun org-next-link ()
9510 "Move forward to the next link.
9511 If the link is in hidden text, expose it."
9512 (interactive)
9513 (when (and org-link-search-failed (eq this-command last-command))
9514 (goto-char (point-min))
9515 (message "Link search wrapped back to beginning of buffer"))
9516 (setq org-link-search-failed nil)
9517 (let* ((pos (point))
9518 (ct (org-context))
9519 (a (assoc :link ct)))
9520 (if a (goto-char (nth 2 a)))
9521 (if (re-search-forward org-any-link-re nil t)
9522 (progn
9523 (goto-char (match-beginning 0))
9524 (if (outline-invisible-p) (org-show-context)))
9525 (goto-char pos)
9526 (setq org-link-search-failed t)
9527 (error "No further link found"))))
9529 (defun org-previous-link ()
9530 "Move backward to the previous link.
9531 If the link is in hidden text, expose it."
9532 (interactive)
9533 (when (and org-link-search-failed (eq this-command last-command))
9534 (goto-char (point-max))
9535 (message "Link search wrapped back to end of buffer"))
9536 (setq org-link-search-failed nil)
9537 (let* ((pos (point))
9538 (ct (org-context))
9539 (a (assoc :link ct)))
9540 (if a (goto-char (nth 1 a)))
9541 (if (re-search-backward org-any-link-re nil t)
9542 (progn
9543 (goto-char (match-beginning 0))
9544 (if (outline-invisible-p) (org-show-context)))
9545 (goto-char pos)
9546 (setq org-link-search-failed t)
9547 (error "No further link found"))))
9549 (defun org-translate-link (s)
9550 "Translate a link string if a translation function has been defined."
9551 (if (and org-link-translation-function
9552 (fboundp org-link-translation-function)
9553 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9554 (progn
9555 (setq s (funcall org-link-translation-function
9556 (match-string 1 s) (match-string 2 s)))
9557 (concat (car s) ":" (cdr s)))
9560 (defun org-translate-link-from-planner (type path)
9561 "Translate a link from Emacs Planner syntax so that Org can follow it.
9562 This is still an experimental function, your mileage may vary."
9563 (cond
9564 ((member type '("http" "https" "news" "ftp"))
9565 ;; standard Internet links are the same.
9566 nil)
9567 ((and (equal type "irc") (string-match "^//" path))
9568 ;; Planner has two / at the beginning of an irc link, we have 1.
9569 ;; We should have zero, actually....
9570 (setq path (substring path 1)))
9571 ((and (equal type "lisp") (string-match "^/" path))
9572 ;; Planner has a slash, we do not.
9573 (setq type "elisp" path (substring path 1)))
9574 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9575 ;; A typical message link. Planner has the id after the final slash,
9576 ;; we separate it with a hash mark
9577 (setq path (concat (match-string 1 path) "#"
9578 (org-remove-angle-brackets (match-string 2 path)))))
9580 (cons type path))
9582 (defun org-find-file-at-mouse (ev)
9583 "Open file link or URL at mouse."
9584 (interactive "e")
9585 (mouse-set-point ev)
9586 (org-open-at-point 'in-emacs))
9588 (defun org-open-at-mouse (ev)
9589 "Open file link or URL at mouse.
9590 See the docstring of `org-open-file' for details."
9591 (interactive "e")
9592 (mouse-set-point ev)
9593 (if (eq major-mode 'org-agenda-mode)
9594 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9595 (org-open-at-point))
9597 (defvar org-window-config-before-follow-link nil
9598 "The window configuration before following a link.
9599 This is saved in case the need arises to restore it.")
9601 (defvar org-open-link-marker (make-marker)
9602 "Marker pointing to the location where `org-open-at-point; was called.")
9604 ;;;###autoload
9605 (defun org-open-at-point-global ()
9606 "Follow a link like Org-mode does.
9607 This command can be called in any mode to follow a link that has
9608 Org-mode syntax."
9609 (interactive)
9610 (org-run-like-in-org-mode 'org-open-at-point))
9612 ;;;###autoload
9613 (defun org-open-link-from-string (s &optional arg reference-buffer)
9614 "Open a link in the string S, as if it was in Org-mode."
9615 (interactive "sLink: \nP")
9616 (let ((reference-buffer (or reference-buffer (current-buffer))))
9617 (with-temp-buffer
9618 (let ((org-inhibit-startup (not reference-buffer)))
9619 (org-mode)
9620 (insert s)
9621 (goto-char (point-min))
9622 (when reference-buffer
9623 (setq org-link-abbrev-alist-local
9624 (with-current-buffer reference-buffer
9625 org-link-abbrev-alist-local)))
9626 (org-open-at-point arg reference-buffer)))))
9628 (defvar org-open-at-point-functions nil
9629 "Hook that is run when following a link at point.
9631 Functions in this hook must return t if they identify and follow
9632 a link at point. If they don't find anything interesting at point,
9633 they must return nil.")
9635 (defun org-open-at-point (&optional arg reference-buffer)
9636 "Open link at or after point.
9637 If there is no link at point, this function will search forward up to
9638 the end of the current line.
9639 Normally, files will be opened by an appropriate application. If the
9640 optional prefix argument ARG is non-nil, Emacs will visit the file.
9641 With a double prefix argument, try to open outside of Emacs, in the
9642 application the system uses for this file type."
9643 (interactive "P")
9644 ;; if in a code block, then open the block's results
9645 (unless (call-interactively #'org-babel-open-src-block-result)
9646 (org-load-modules-maybe)
9647 (move-marker org-open-link-marker (point))
9648 (setq org-window-config-before-follow-link (current-window-configuration))
9649 (org-remove-occur-highlights nil nil t)
9650 (cond
9651 ((and (org-at-heading-p)
9652 (not (org-at-timestamp-p t))
9653 (not (org-in-regexp
9654 (concat org-plain-link-re "\\|"
9655 org-bracket-link-regexp "\\|"
9656 org-angle-link-re "\\|"
9657 "[ \t]:[^ \t\n]+:[ \t]*$")))
9658 (not (get-text-property (point) 'org-linked-text)))
9659 (or (org-offer-links-in-entry arg)
9660 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9661 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9662 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9663 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9664 (not (org-in-regexp org-bracket-link-regexp)))
9665 (org-footnote-action))
9667 (let (type path link line search (pos (point)))
9668 (catch 'match
9669 (save-excursion
9670 (skip-chars-forward "^]\n\r")
9671 (when (org-in-regexp org-bracket-link-regexp 1)
9672 (setq link (org-extract-attributes
9673 (org-link-unescape (org-match-string-no-properties 1))))
9674 (while (string-match " *\n *" link)
9675 (setq link (replace-match " " t t link)))
9676 (setq link (org-link-expand-abbrev link))
9677 (cond
9678 ((or (file-name-absolute-p link)
9679 (string-match "^\\.\\.?/" link))
9680 (setq type "file" path link))
9681 ((string-match org-link-re-with-space3 link)
9682 (setq type (match-string 1 link) path (match-string 2 link)))
9683 (t (setq type "thisfile" path link)))
9684 (throw 'match t)))
9686 (when (get-text-property (point) 'org-linked-text)
9687 (setq type "thisfile"
9688 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9689 (1+ (point)) (point))
9690 path (buffer-substring
9691 (or (previous-single-property-change pos 'org-linked-text)
9692 (point-min))
9693 (or (next-single-property-change pos 'org-linked-text)
9694 (point-max))))
9695 (throw 'match t))
9697 (save-excursion
9698 (when (or (org-in-regexp org-angle-link-re)
9699 (org-in-regexp org-plain-link-re))
9700 (setq type (match-string 1)
9701 path (org-link-unescape (match-string 2)))
9702 (throw 'match t)))
9703 (save-excursion
9704 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9705 (setq type "tags"
9706 path (match-string 1))
9707 (while (string-match ":" path)
9708 (setq path (replace-match "+" t t path)))
9709 (throw 'match t)))
9710 (when (org-in-regexp "<\\([^><\n]+\\)>")
9711 (setq type "tree-match"
9712 path (match-string 1))
9713 (throw 'match t)))
9714 (unless path
9715 (error "No link found"))
9717 ;; switch back to reference buffer
9718 ;; needed when if called in a temporary buffer through
9719 ;; org-open-link-from-string
9720 (with-current-buffer (or reference-buffer (current-buffer))
9722 ;; Remove any trailing spaces in path
9723 (if (string-match " +\\'" path)
9724 (setq path (replace-match "" t t path)))
9725 (if (and org-link-translation-function
9726 (fboundp org-link-translation-function))
9727 ;; Check if we need to translate the link
9728 (let ((tmp (funcall org-link-translation-function type path)))
9729 (setq type (car tmp) path (cdr tmp))))
9731 (cond
9733 ((assoc type org-link-protocols)
9734 (funcall (nth 1 (assoc type org-link-protocols)) path))
9736 ((equal type "mailto")
9737 (let ((cmd (car org-link-mailto-program))
9738 (args (cdr org-link-mailto-program)) args1
9739 (address path) (subject "") a)
9740 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9741 (setq address (match-string 1 path)
9742 subject (org-link-escape (match-string 2 path))))
9743 (while args
9744 (cond
9745 ((not (stringp (car args))) (push (pop args) args1))
9746 (t (setq a (pop args))
9747 (if (string-match "%a" a)
9748 (setq a (replace-match address t t a)))
9749 (if (string-match "%s" a)
9750 (setq a (replace-match subject t t a)))
9751 (push a args1))))
9752 (apply cmd (nreverse args1))))
9754 ((member type '("http" "https" "ftp" "news"))
9755 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9756 (org-link-escape
9757 path org-link-escape-chars-browser)
9758 path))))
9760 ((string= type "doi")
9761 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9762 (org-link-escape
9763 path org-link-escape-chars-browser)
9764 path))))
9766 ((member type '("message"))
9767 (browse-url (concat type ":" path)))
9769 ((string= type "tags")
9770 (org-tags-view arg path))
9772 ((string= type "tree-match")
9773 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9775 ((string= type "file")
9776 (if (string-match "::\\([0-9]+\\)\\'" path)
9777 (setq line (string-to-number (match-string 1 path))
9778 path (substring path 0 (match-beginning 0)))
9779 (if (string-match "::\\(.+\\)\\'" path)
9780 (setq search (match-string 1 path)
9781 path (substring path 0 (match-beginning 0)))))
9782 (if (string-match "[*?{]" (file-name-nondirectory path))
9783 (dired path)
9784 (org-open-file path arg line search)))
9786 ((string= type "shell")
9787 (let ((cmd path))
9788 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9789 (string-match org-confirm-shell-link-not-regexp cmd))
9790 (not org-confirm-shell-link-function)
9791 (funcall org-confirm-shell-link-function
9792 (format "Execute \"%s\" in shell? "
9793 (org-add-props cmd nil
9794 'face 'org-warning))))
9795 (progn
9796 (message "Executing %s" cmd)
9797 (shell-command cmd))
9798 (error "Abort"))))
9800 ((string= type "elisp")
9801 (let ((cmd path))
9802 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9803 (string-match org-confirm-elisp-link-not-regexp cmd))
9804 (not org-confirm-elisp-link-function)
9805 (funcall org-confirm-elisp-link-function
9806 (format "Execute \"%s\" as elisp? "
9807 (org-add-props cmd nil
9808 'face 'org-warning))))
9809 (message "%s => %s" cmd
9810 (if (equal (string-to-char cmd) ?\()
9811 (eval (read cmd))
9812 (call-interactively (read cmd))))
9813 (error "Abort"))))
9815 ((and (string= type "thisfile")
9816 (run-hook-with-args-until-success
9817 'org-open-link-functions path)))
9819 ((string= type "thisfile")
9820 (if arg
9821 (switch-to-buffer-other-window
9822 (org-get-buffer-for-internal-link (current-buffer)))
9823 (org-mark-ring-push))
9824 (let ((cmd `(org-link-search
9825 ,path
9826 ,(cond ((equal arg '(4)) ''occur)
9827 ((equal arg '(16)) ''org-occur)
9828 (t nil))
9829 ,pos)))
9830 (condition-case nil (let ((org-link-search-inhibit-query t))
9831 (eval cmd))
9832 (error (progn (widen) (eval cmd))))))
9835 (browse-url-at-point)))))))
9836 (move-marker org-open-link-marker nil)
9837 (run-hook-with-args 'org-follow-link-hook)))
9839 (defun org-offer-links-in-entry (&optional nth zero)
9840 "Offer links in the current entry and follow the selected link.
9841 If there is only one link, follow it immediately as well.
9842 If NTH is an integer, immediately pick the NTH link found.
9843 If ZERO is a string, check also this string for a link, and if
9844 there is one, offer it as link number zero."
9845 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9846 "\\(" org-angle-link-re "\\)\\|"
9847 "\\(" org-plain-link-re "\\)"))
9848 (cnt ?0)
9849 (in-emacs (if (integerp nth) nil nth))
9850 have-zero end links link c)
9851 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9852 (push (match-string 0 zero) links)
9853 (setq cnt (1- cnt) have-zero t))
9854 (save-excursion
9855 (org-back-to-heading t)
9856 (setq end (save-excursion (outline-next-heading) (point)))
9857 (while (re-search-forward re end t)
9858 (push (match-string 0) links))
9859 (setq links (org-uniquify (reverse links))))
9861 (cond
9862 ((null links)
9863 (message "No links"))
9864 ((equal (length links) 1)
9865 (setq link (list (car links))))
9866 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9867 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9868 (t ; we have to select a link
9869 (save-excursion
9870 (save-window-excursion
9871 (delete-other-windows)
9872 (with-output-to-temp-buffer "*Select Link*"
9873 (mapc (lambda (l)
9874 (if (not (string-match org-bracket-link-regexp l))
9875 (princ (format "[%c] %s\n" (incf cnt)
9876 (org-remove-angle-brackets l)))
9877 (if (match-end 3)
9878 (princ (format "[%c] %s (%s)\n" (incf cnt)
9879 (match-string 3 l) (match-string 1 l)))
9880 (princ (format "[%c] %s\n" (incf cnt)
9881 (match-string 1 l))))))
9882 links))
9883 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9884 (message "Select link to open, RET to open all:")
9885 (setq c (read-char-exclusive))
9886 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9887 (when (equal c ?q) (error "Abort"))
9888 (if (equal c ?\C-m)
9889 (setq link links)
9890 (setq nth (- c ?0))
9891 (if have-zero (setq nth (1+ nth)))
9892 (unless (and (integerp nth) (>= (length links) nth))
9893 (error "Invalid link selection"))
9894 (setq link (list (nth (1- nth) links))))))
9895 (if link
9896 (let ((buf (current-buffer)))
9897 (dolist (l link)
9898 (org-open-link-from-string l in-emacs buf))
9900 nil)))
9902 ;; Add special file links that specify the way of opening
9904 (org-add-link-type "file+sys" 'org-open-file-with-system)
9905 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9906 (defun org-open-file-with-system (path)
9907 "Open file at PATH using the system way of opening it."
9908 (org-open-file path 'system))
9909 (defun org-open-file-with-emacs (path)
9910 "Open file at PATH in Emacs."
9911 (org-open-file path 'emacs))
9912 (defun org-remove-file-link-modifiers ()
9913 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9914 (goto-char (point-min))
9915 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9916 (org-if-unprotected
9917 (replace-match "file:" t t))))
9918 (eval-after-load "org-exp"
9919 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9920 'org-remove-file-link-modifiers))
9922 ;;;; Time estimates
9924 (defun org-get-effort (&optional pom)
9925 "Get the effort estimate for the current entry."
9926 (org-entry-get pom org-effort-property))
9928 ;;; File search
9930 (defvar org-create-file-search-functions nil
9931 "List of functions to construct the right search string for a file link.
9932 These functions are called in turn with point at the location to
9933 which the link should point.
9935 A function in the hook should first test if it would like to
9936 handle this file type, for example by checking the `major-mode'
9937 or the file extension. If it decides not to handle this file, it
9938 should just return nil to give other functions a chance. If it
9939 does handle the file, it must return the search string to be used
9940 when following the link. The search string will be part of the
9941 file link, given after a double colon, and `org-open-at-point'
9942 will automatically search for it. If special measures must be
9943 taken to make the search successful, another function should be
9944 added to the companion hook `org-execute-file-search-functions',
9945 which see.
9947 A function in this hook may also use `setq' to set the variable
9948 `description' to provide a suggestion for the descriptive text to
9949 be used for this link when it gets inserted into an Org-mode
9950 buffer with \\[org-insert-link].")
9952 (defvar org-execute-file-search-functions nil
9953 "List of functions to execute a file search triggered by a link.
9955 Functions added to this hook must accept a single argument, the
9956 search string that was part of the file link, the part after the
9957 double colon. The function must first check if it would like to
9958 handle this search, for example by checking the `major-mode' or
9959 the file extension. If it decides not to handle this search, it
9960 should just return nil to give other functions a chance. If it
9961 does handle the search, it must return a non-nil value to keep
9962 other functions from trying.
9964 Each function can access the current prefix argument through the
9965 variable `current-prefix-argument'. Note that a single prefix is
9966 used to force opening a link in Emacs, so it may be good to only
9967 use a numeric or double prefix to guide the search function.
9969 In case this is needed, a function in this hook can also restore
9970 the window configuration before `org-open-at-point' was called using:
9972 (set-window-configuration org-window-config-before-follow-link)")
9974 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9975 (defun org-link-search (s &optional type avoid-pos stealth)
9976 "Search for a link search option.
9977 If S is surrounded by forward slashes, it is interpreted as a
9978 regular expression. In org-mode files, this will create an `org-occur'
9979 sparse tree. In ordinary files, `occur' will be used to list matches.
9980 If the current buffer is in `dired-mode', grep will be used to search
9981 in all files. If AVOID-POS is given, ignore matches near that position.
9983 When optional argument STEALTH is non-nil, do not modify
9984 visibility around point, thus ignoring
9985 `org-show-hierarchy-above', `org-show-following-heading' and
9986 `org-show-siblings' variables."
9987 (let ((case-fold-search t)
9988 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9989 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9990 (append '(("") (" ") ("\t") ("\n"))
9991 org-emphasis-alist)
9992 "\\|") "\\)"))
9993 (pos (point))
9994 (pre nil) (post nil)
9995 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9996 (cond
9997 ;; First check if there are any special search functions
9998 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9999 ;; Now try the builtin stuff
10000 ((and (equal (string-to-char s0) ?#)
10001 (> (length s0) 1)
10002 (save-excursion
10003 (goto-char (point-min))
10004 (and
10005 (re-search-forward
10006 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10007 (setq type 'dedicated
10008 pos (match-beginning 0))))
10009 ;; There is an exact target for this
10010 (goto-char pos)
10011 (org-back-to-heading t)))
10012 ((save-excursion
10013 (goto-char (point-min))
10014 (and
10015 (re-search-forward
10016 (concat "<<" (regexp-quote s0) ">>") nil t)
10017 (setq type 'dedicated
10018 pos (match-beginning 0))))
10019 ;; There is an exact target for this
10020 (goto-char pos))
10021 ((save-excursion
10022 (goto-char (point-min))
10023 (and
10024 (re-search-forward
10025 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10026 (setq type 'dedicated pos (match-beginning 0))))
10027 ;; Found an invisible target.
10028 (goto-char pos))
10029 ((save-excursion
10030 (goto-char (point-min))
10031 (and
10032 (re-search-forward
10033 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10034 (setq type 'dedicated pos (match-beginning 0))))
10035 ;; Found an element with a matching #+name affiliated keyword.
10036 (goto-char pos))
10037 ((and (string-match "^(\\(.*\\))$" s0)
10038 (save-excursion
10039 (goto-char (point-min))
10040 (and
10041 (re-search-forward
10042 (concat "[^[]" (regexp-quote
10043 (format org-coderef-label-format
10044 (match-string 1 s0))))
10045 nil t)
10046 (setq type 'dedicated
10047 pos (1+ (match-beginning 0))))))
10048 ;; There is a coderef target for this
10049 (goto-char pos))
10050 ((string-match "^/\\(.*\\)/$" s)
10051 ;; A regular expression
10052 (cond
10053 ((derived-mode-p 'org-mode)
10054 (org-occur (match-string 1 s)))
10055 ;;((eq major-mode 'dired-mode)
10056 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10057 (t (org-do-occur (match-string 1 s)))))
10058 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10059 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10060 (goto-char (point-min))
10061 (cond
10062 ((let (case-fold-search)
10063 (re-search-forward (format org-complex-heading-regexp-format
10064 (regexp-quote s))
10065 nil t))
10066 ;; OK, found a match
10067 (setq type 'dedicated)
10068 (goto-char (match-beginning 0)))
10069 ((and (not org-link-search-inhibit-query)
10070 (eq org-link-search-must-match-exact-headline 'query-to-create)
10071 (y-or-n-p "No match - create this as a new heading? "))
10072 (goto-char (point-max))
10073 (or (bolp) (newline))
10074 (insert "* " s "\n")
10075 (beginning-of-line 0))
10077 (goto-char pos)
10078 (error "No match"))))
10080 ;; A normal search string
10081 (when (equal (string-to-char s) ?*)
10082 ;; Anchor on headlines, post may include tags.
10083 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10084 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10085 s (substring s 1)))
10086 (remove-text-properties
10087 0 (length s)
10088 '(face nil mouse-face nil keymap nil fontified nil) s)
10089 ;; Make a series of regular expressions to find a match
10090 (setq words (org-split-string s "[ \n\r\t]+")
10092 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10093 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10094 "\\)" markers)
10095 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10096 re2a (concat "[ \t\r\n]" re2a_)
10097 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10098 re4 (concat "[^a-zA-Z_]" re4_)
10100 re1 (concat pre re2 post)
10101 re3 (concat pre (if pre re4_ re4) post)
10102 re5 (concat pre ".*" re4)
10103 re2 (concat pre re2)
10104 re2a (concat pre (if pre re2a_ re2a))
10105 re4 (concat pre (if pre re4_ re4))
10106 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10107 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10108 re5 "\\)"
10110 (cond
10111 ((eq type 'org-occur) (org-occur reall))
10112 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10113 (t (goto-char (point-min))
10114 (setq type 'fuzzy)
10115 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10116 (org-search-not-self 1 re1 nil t)
10117 (org-search-not-self 1 re2 nil t)
10118 (org-search-not-self 1 re2a nil t)
10119 (org-search-not-self 1 re3 nil t)
10120 (org-search-not-self 1 re4 nil t)
10121 (org-search-not-self 1 re5 nil t)
10123 (goto-char (match-beginning 1))
10124 (goto-char pos)
10125 (error "No match"))))))
10126 (and (derived-mode-p 'org-mode)
10127 (not stealth)
10128 (org-show-context 'link-search))
10129 type))
10131 (defun org-search-not-self (group &rest args)
10132 "Execute `re-search-forward', but only accept matches that do not
10133 enclose the position of `org-open-link-marker'."
10134 (let ((m org-open-link-marker))
10135 (catch 'exit
10136 (while (apply 're-search-forward args)
10137 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10138 (goto-char (match-end group))
10139 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10140 (> (match-beginning 0) (marker-position m))
10141 (< (match-end 0) (marker-position m)))
10142 (save-match-data
10143 (or (not (org-in-regexp
10144 org-bracket-link-analytic-regexp 1))
10145 (not (match-end 4)) ; no description
10146 (and (<= (match-beginning 4) (point))
10147 (>= (match-end 4) (point))))))
10148 (throw 'exit (point))))))))
10150 (defun org-get-buffer-for-internal-link (buffer)
10151 "Return a buffer to be used for displaying the link target of internal links."
10152 (cond
10153 ((not org-display-internal-link-with-indirect-buffer)
10154 buffer)
10155 ((string-match "(Clone)$" (buffer-name buffer))
10156 (message "Buffer is already a clone, not making another one")
10157 ;; we also do not modify visibility in this case
10158 buffer)
10159 (t ; make a new indirect buffer for displaying the link
10160 (let* ((bn (buffer-name buffer))
10161 (ibn (concat bn "(Clone)"))
10162 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10163 (with-current-buffer ib (org-overview))
10164 ib))))
10166 (defun org-do-occur (regexp &optional cleanup)
10167 "Call the Emacs command `occur'.
10168 If CLEANUP is non-nil, remove the printout of the regular expression
10169 in the *Occur* buffer. This is useful if the regex is long and not useful
10170 to read."
10171 (occur regexp)
10172 (when cleanup
10173 (let ((cwin (selected-window)) win beg end)
10174 (when (setq win (get-buffer-window "*Occur*"))
10175 (select-window win))
10176 (goto-char (point-min))
10177 (when (re-search-forward "match[a-z]+" nil t)
10178 (setq beg (match-end 0))
10179 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10180 (setq end (1- (match-beginning 0)))))
10181 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10182 (goto-char (point-min))
10183 (select-window cwin))))
10185 ;;; The mark ring for links jumps
10187 (defvar org-mark-ring nil
10188 "Mark ring for positions before jumps in Org-mode.")
10189 (defvar org-mark-ring-last-goto nil
10190 "Last position in the mark ring used to go back.")
10191 ;; Fill and close the ring
10192 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10193 (loop for i from 1 to org-mark-ring-length do
10194 (push (make-marker) org-mark-ring))
10195 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10196 org-mark-ring)
10198 (defun org-mark-ring-push (&optional pos buffer)
10199 "Put the current position or POS into the mark ring and rotate it."
10200 (interactive)
10201 (setq pos (or pos (point)))
10202 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10203 (move-marker (car org-mark-ring)
10204 (or pos (point))
10205 (or buffer (current-buffer)))
10206 (message "%s"
10207 (substitute-command-keys
10208 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10210 (defun org-mark-ring-goto (&optional n)
10211 "Jump to the previous position in the mark ring.
10212 With prefix arg N, jump back that many stored positions. When
10213 called several times in succession, walk through the entire ring.
10214 Org-mode commands jumping to a different position in the current file,
10215 or to another Org-mode file, automatically push the old position
10216 onto the ring."
10217 (interactive "p")
10218 (let (p m)
10219 (if (eq last-command this-command)
10220 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10221 (setq p org-mark-ring))
10222 (setq org-mark-ring-last-goto p)
10223 (setq m (car p))
10224 (org-pop-to-buffer-same-window (marker-buffer m))
10225 (goto-char m)
10226 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10228 (defun org-remove-angle-brackets (s)
10229 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10230 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10232 (defun org-add-angle-brackets (s)
10233 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10234 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10236 (defun org-remove-double-quotes (s)
10237 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10238 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10241 ;;; Following specific links
10243 (defun org-follow-timestamp-link ()
10244 (cond
10245 ((org-at-date-range-p t)
10246 (let ((org-agenda-start-on-weekday)
10247 (t1 (match-string 1))
10248 (t2 (match-string 2)))
10249 (setq t1 (time-to-days (org-time-string-to-time t1))
10250 t2 (time-to-days (org-time-string-to-time t2)))
10251 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10252 ((org-at-timestamp-p t)
10253 (org-agenda-list nil (time-to-days (org-time-string-to-time
10254 (substring (match-string 1) 0 10)))
10256 (t (error "This should not happen"))))
10259 ;;; Following file links
10260 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10261 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10262 (declare-function mailcap-mime-info
10263 "mailcap" (string &optional request no-decode))
10264 (defvar org-wait nil)
10265 (defun org-open-file (path &optional in-emacs line search)
10266 "Open the file at PATH.
10267 First, this expands any special file name abbreviations. Then the
10268 configuration variable `org-file-apps' is checked if it contains an
10269 entry for this file type, and if yes, the corresponding command is launched.
10271 If no application is found, Emacs simply visits the file.
10273 With optional prefix argument IN-EMACS, Emacs will visit the file.
10274 With a double \\[universal-argument] \\[universal-argument] \
10275 prefix arg, Org tries to avoid opening in Emacs
10276 and to use an external application to visit the file.
10278 Optional LINE specifies a line to go to, optional SEARCH a string
10279 to search for. If LINE or SEARCH is given, the file will be
10280 opened in Emacs, unless an entry from org-file-apps that makes
10281 use of groups in a regexp matches.
10283 If you want to change the way frames are used when following a
10284 link, please customize `org-link-frame-setup'.
10286 If the file does not exist, an error is thrown."
10287 (let* ((file (if (equal path "")
10288 buffer-file-name
10289 (substitute-in-file-name (expand-file-name path))))
10290 (file-apps (append org-file-apps (org-default-apps)))
10291 (apps (org-remove-if
10292 'org-file-apps-entry-match-against-dlink-p file-apps))
10293 (apps-dlink (org-remove-if-not
10294 'org-file-apps-entry-match-against-dlink-p file-apps))
10295 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10296 (dirp (if remp nil (file-directory-p file)))
10297 (file (if (and dirp org-open-directory-means-index-dot-org)
10298 (concat (file-name-as-directory file) "index.org")
10299 file))
10300 (a-m-a-p (assq 'auto-mode apps))
10301 (dfile (downcase file))
10302 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10303 (link (cond ((and (eq line nil)
10304 (eq search nil))
10305 file)
10306 (line
10307 (concat file "::" (number-to-string line)))
10308 (search
10309 (concat file "::" search))))
10310 (dlink (downcase link))
10311 (old-buffer (current-buffer))
10312 (old-pos (point))
10313 (old-mode major-mode)
10314 ext cmd link-match-data)
10315 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10316 (setq ext (match-string 1 dfile))
10317 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10318 (setq ext (match-string 1 dfile))))
10319 (cond
10320 ((member in-emacs '((16) system))
10321 (setq cmd (cdr (assoc 'system apps))))
10322 (in-emacs (setq cmd 'emacs))
10324 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10325 (and dirp (cdr (assoc 'directory apps)))
10326 ; first, try matching against apps-dlink
10327 ; if we get a match here, store the match data for later
10328 (let ((match (assoc-default dlink apps-dlink
10329 'string-match)))
10330 (if match
10331 (progn (setq link-match-data (match-data))
10332 match)
10333 (progn (setq in-emacs (or in-emacs line search))
10334 nil))) ; if we have no match in apps-dlink,
10335 ; always open the file in emacs if line or search
10336 ; is given (for backwards compatibility)
10337 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10338 'string-match)
10339 (cdr (assoc ext apps))
10340 (cdr (assoc t apps))))))
10341 (when (eq cmd 'system)
10342 (setq cmd (cdr (assoc 'system apps))))
10343 (when (eq cmd 'default)
10344 (setq cmd (cdr (assoc t apps))))
10345 (when (eq cmd 'mailcap)
10346 (require 'mailcap)
10347 (mailcap-parse-mailcaps)
10348 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10349 (command (mailcap-mime-info mime-type)))
10350 (if (stringp command)
10351 (setq cmd command)
10352 (setq cmd 'emacs))))
10353 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10354 (not (file-exists-p file))
10355 (not org-open-non-existing-files))
10356 (error "No such file: %s" file))
10357 (cond
10358 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10359 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10360 (while (string-match "['\"]%s['\"]" cmd)
10361 (setq cmd (replace-match "%s" t t cmd)))
10362 (while (string-match "%s" cmd)
10363 (setq cmd (replace-match
10364 (save-match-data
10365 (shell-quote-argument
10366 (convert-standard-filename file)))
10367 t t cmd)))
10369 ;; Replace "%1", "%2" etc. in command with group matches from regex
10370 (save-match-data
10371 (let ((match-index 1)
10372 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10373 (set-match-data link-match-data)
10374 (while (<= match-index number-of-groups)
10375 (let ((regex (concat "%" (number-to-string match-index)))
10376 (replace-with (match-string match-index dlink)))
10377 (while (string-match regex cmd)
10378 (setq cmd (replace-match replace-with t t cmd))))
10379 (setq match-index (+ match-index 1)))))
10381 (save-window-excursion
10382 (start-process-shell-command cmd nil cmd)
10383 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10385 ((or (stringp cmd)
10386 (eq cmd 'emacs))
10387 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10388 (widen)
10389 (if line (org-goto-line line)
10390 (if search (org-link-search search))))
10391 ((consp cmd)
10392 (let ((file (convert-standard-filename file)))
10393 (save-match-data
10394 (set-match-data link-match-data)
10395 (eval cmd))))
10396 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10397 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10398 (or (not (equal old-buffer (current-buffer)))
10399 (not (equal old-pos (point))))
10400 (org-mark-ring-push old-pos old-buffer))))
10402 (defun org-file-apps-entry-match-against-dlink-p (entry)
10403 "This function returns non-nil if `entry' uses a regular
10404 expression which should be matched against the whole link by
10405 org-open-file.
10407 It assumes that is the case when the entry uses a regular
10408 expression which has at least one grouping construct and the
10409 action is either a lisp form or a command string containing
10410 '%1', i.e. using at least one subexpression match as a
10411 parameter."
10412 (let ((selector (car entry))
10413 (action (cdr entry)))
10414 (if (stringp selector)
10415 (and (> (regexp-opt-depth selector) 0)
10416 (or (and (stringp action)
10417 (string-match "%[0-9]" action))
10418 (consp action)))
10419 nil)))
10421 (defun org-default-apps ()
10422 "Return the default applications for this operating system."
10423 (cond
10424 ((eq system-type 'darwin)
10425 org-file-apps-defaults-macosx)
10426 ((eq system-type 'windows-nt)
10427 org-file-apps-defaults-windowsnt)
10428 (t org-file-apps-defaults-gnu)))
10430 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10431 "Convert extensions to regular expressions in the cars of LIST.
10432 Also, weed out any non-string entries, because the return value is used
10433 only for regexp matching.
10434 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10435 point to the symbol `emacs', indicating that the file should
10436 be opened in Emacs."
10437 (append
10438 (delq nil
10439 (mapcar (lambda (x)
10440 (if (not (stringp (car x)))
10442 (if (string-match "\\W" (car x))
10444 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10445 list))
10446 (if add-auto-mode
10447 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10449 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10450 (defun org-file-remote-p (file)
10451 "Test whether FILE specifies a location on a remote system.
10452 Return non-nil if the location is indeed remote.
10454 For example, the filename \"/user@host:/foo\" specifies a location
10455 on the system \"/user@host:\"."
10456 (cond ((fboundp 'file-remote-p)
10457 (file-remote-p file))
10458 ((fboundp 'tramp-handle-file-remote-p)
10459 (tramp-handle-file-remote-p file))
10460 ((and (boundp 'ange-ftp-name-format)
10461 (string-match (car ange-ftp-name-format) file))
10463 (t nil)))
10466 ;;;; Refiling
10468 (defun org-get-org-file ()
10469 "Read a filename, with default directory `org-directory'."
10470 (let ((default (or org-default-notes-file remember-data-file)))
10471 (read-file-name (format "File name [%s]: " default)
10472 (file-name-as-directory org-directory)
10473 default)))
10475 (defun org-notes-order-reversed-p ()
10476 "Check if the current file should receive notes in reversed order."
10477 (cond
10478 ((not org-reverse-note-order) nil)
10479 ((eq t org-reverse-note-order) t)
10480 ((not (listp org-reverse-note-order)) nil)
10481 (t (catch 'exit
10482 (let ((all org-reverse-note-order)
10483 entry)
10484 (while (setq entry (pop all))
10485 (if (string-match (car entry) buffer-file-name)
10486 (throw 'exit (cdr entry))))
10487 nil)))))
10489 (defvar org-refile-target-table nil
10490 "The list of refile targets, created by `org-refile'.")
10492 (defvar org-agenda-new-buffers nil
10493 "Buffers created to visit agenda files.")
10495 (defvar org-refile-cache nil
10496 "Cache for refile targets.")
10498 (defvar org-refile-markers nil
10499 "All the markers used for caching refile locations.")
10501 (defun org-refile-marker (pos)
10502 "Get a new refile marker, but only if caching is in use."
10503 (if (not org-refile-use-cache)
10505 (let ((m (make-marker)))
10506 (move-marker m pos)
10507 (push m org-refile-markers)
10508 m)))
10510 (defun org-refile-cache-clear ()
10511 "Clear the refile cache and disable all the markers."
10512 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10513 (setq org-refile-markers nil)
10514 (setq org-refile-cache nil)
10515 (message "Refile cache has been cleared"))
10517 (defun org-refile-cache-check-set (set)
10518 "Check if all the markers in the cache still have live buffers."
10519 (let (marker)
10520 (catch 'exit
10521 (while (and set (setq marker (nth 3 (pop set))))
10522 ;; if org-refile-use-outline-path is 'file, marker may be nil
10523 (when (and marker (null (marker-buffer marker)))
10524 (message "not found") (sit-for 3)
10525 (throw 'exit nil)))
10526 t)))
10528 (defun org-refile-cache-put (set &rest identifiers)
10529 "Push the refile targets SET into the cache, under IDENTIFIERS."
10530 (let* ((key (sha1 (prin1-to-string identifiers)))
10531 (entry (assoc key org-refile-cache)))
10532 (if entry
10533 (setcdr entry set)
10534 (push (cons key set) org-refile-cache))))
10536 (defun org-refile-cache-get (&rest identifiers)
10537 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10538 (cond
10539 ((not org-refile-cache) nil)
10540 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10542 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10543 org-refile-cache))))
10544 (and set (org-refile-cache-check-set set) set)))))
10546 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10547 "Produce a table with refile targets."
10548 (let ((case-fold-search nil)
10549 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10550 (entries (or org-refile-targets '((nil . (:level . 1)))))
10551 targets tgs txt re files f desc descre fast-path-p level pos0)
10552 (message "Getting targets...")
10553 (with-current-buffer (or default-buffer (current-buffer))
10554 (while (setq entry (pop entries))
10555 (setq files (car entry) desc (cdr entry))
10556 (setq fast-path-p nil)
10557 (cond
10558 ((null files) (setq files (list (current-buffer))))
10559 ((eq files 'org-agenda-files)
10560 (setq files (org-agenda-files 'unrestricted)))
10561 ((and (symbolp files) (fboundp files))
10562 (setq files (funcall files)))
10563 ((and (symbolp files) (boundp files))
10564 (setq files (symbol-value files))))
10565 (if (stringp files) (setq files (list files)))
10566 (cond
10567 ((eq (car desc) :tag)
10568 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10569 ((eq (car desc) :todo)
10570 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10571 ((eq (car desc) :regexp)
10572 (setq descre (cdr desc)))
10573 ((eq (car desc) :level)
10574 (setq descre (concat "^\\*\\{" (number-to-string
10575 (if org-odd-levels-only
10576 (1- (* 2 (cdr desc)))
10577 (cdr desc)))
10578 "\\}[ \t]")))
10579 ((eq (car desc) :maxlevel)
10580 (setq fast-path-p t)
10581 (setq descre (concat "^\\*\\{1," (number-to-string
10582 (if org-odd-levels-only
10583 (1- (* 2 (cdr desc)))
10584 (cdr desc)))
10585 "\\}[ \t]")))
10586 (t (error "Bad refiling target description %s" desc)))
10587 (while (setq f (pop files))
10588 (with-current-buffer
10589 (if (bufferp f) f (org-get-agenda-file-buffer f))
10591 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10592 (progn
10593 (if (bufferp f) (setq f (buffer-file-name
10594 (buffer-base-buffer f))))
10595 (setq f (and f (expand-file-name f)))
10596 (if (eq org-refile-use-outline-path 'file)
10597 (push (list (file-name-nondirectory f) f nil nil) tgs))
10598 (save-excursion
10599 (save-restriction
10600 (widen)
10601 (goto-char (point-min))
10602 (while (re-search-forward descre nil t)
10603 (goto-char (setq pos0 (point-at-bol)))
10604 (catch 'next
10605 (when org-refile-target-verify-function
10606 (save-match-data
10607 (or (funcall org-refile-target-verify-function)
10608 (throw 'next t))))
10609 (when (and (looking-at org-complex-heading-regexp)
10610 (not (member (match-string 4) excluded-entries))
10611 (match-string 4))
10612 (setq level (org-reduced-level
10613 (- (match-end 1) (match-beginning 1)))
10614 txt (org-link-display-format (match-string 4))
10615 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10616 re (format org-complex-heading-regexp-format
10617 (regexp-quote (match-string 4))))
10618 (when org-refile-use-outline-path
10619 (setq txt (mapconcat
10620 'org-protect-slash
10621 (append
10622 (if (eq org-refile-use-outline-path
10623 'file)
10624 (list (file-name-nondirectory
10625 (buffer-file-name
10626 (buffer-base-buffer))))
10627 (if (eq org-refile-use-outline-path
10628 'full-file-path)
10629 (list (buffer-file-name
10630 (buffer-base-buffer)))))
10631 (org-get-outline-path fast-path-p
10632 level txt)
10633 (list txt))
10634 "/")))
10635 (push (list txt f re (org-refile-marker (point)))
10636 tgs)))
10637 (when (= (point) pos0)
10638 ;; verification function has not moved point
10639 (goto-char (point-at-eol))))))))
10640 (when org-refile-use-cache
10641 (org-refile-cache-put tgs (buffer-file-name) descre))
10642 (setq targets (append tgs targets))
10643 ))))
10644 (message "Getting targets...done")
10645 (nreverse targets)))
10647 (defun org-protect-slash (s)
10648 (while (string-match "/" s)
10649 (setq s (replace-match "\\" t t s)))
10652 (defvar org-olpa (make-vector 20 nil))
10654 (defun org-get-outline-path (&optional fastp level heading)
10655 "Return the outline path to the current entry, as a list.
10657 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10658 routine which makes outline path derivations for an entire file,
10659 avoiding backtracing. Refile target collection makes use of that."
10660 (if fastp
10661 (progn
10662 (if (> level 19)
10663 (error "Outline path failure, more than 19 levels"))
10664 (loop for i from level upto 19 do
10665 (aset org-olpa i nil))
10666 (prog1
10667 (delq nil (append org-olpa nil))
10668 (aset org-olpa level heading)))
10669 (let (rtn case-fold-search)
10670 (save-excursion
10671 (save-restriction
10672 (widen)
10673 (while (org-up-heading-safe)
10674 (when (looking-at org-complex-heading-regexp)
10675 (push (org-match-string-no-properties 4) rtn)))
10676 rtn)))))
10678 (defun org-format-outline-path (path &optional width prefix)
10679 "Format the outline path PATH for display.
10680 Width is the maximum number of characters that is available.
10681 Prefix is a prefix to be included in the returned string,
10682 such as the file name."
10683 (setq width (or width 79))
10684 (if prefix (setq width (- width (length prefix))))
10685 (if (not path)
10686 (or prefix "")
10687 (let* ((nsteps (length path))
10688 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10689 (maxwidth (if (<= total-width width)
10690 10000 ;; everything fits
10691 ;; we need to shorten the level headings
10692 (/ (- width nsteps) nsteps)))
10693 (org-odd-levels-only nil)
10694 (n 0)
10695 (total (1+ (length prefix))))
10696 (setq maxwidth (max maxwidth 10))
10697 (concat prefix
10698 (mapconcat
10699 (lambda (h)
10700 (setq n (1+ n))
10701 (if (and (= n nsteps) (< maxwidth 10000))
10702 (setq maxwidth (- total-width total)))
10703 (if (< (length h) maxwidth)
10704 (progn (setq total (+ total (length h) 1)) h)
10705 (setq h (substring h 0 (- maxwidth 2))
10706 total (+ total maxwidth 1))
10707 (if (string-match "[ \t]+\\'" h)
10708 (setq h (substring h 0 (match-beginning 0))))
10709 (setq h (concat h "..")))
10710 (org-add-props h nil 'face
10711 (nth (% (1- n) org-n-level-faces)
10712 org-level-faces))
10714 path "/")))))
10716 (defun org-display-outline-path (&optional file current)
10717 "Display the current outline path in the echo area."
10718 (interactive "P")
10719 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10720 (case-fold-search nil)
10721 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10722 (if current (setq path (append path
10723 (save-excursion
10724 (org-back-to-heading t)
10725 (if (looking-at org-complex-heading-regexp)
10726 (list (match-string 4)))))))
10727 (message "%s"
10728 (org-format-outline-path
10729 path
10730 (1- (frame-width))
10731 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10733 (defvar org-refile-history nil
10734 "History for refiling operations.")
10736 (defvar org-after-refile-insert-hook nil
10737 "Hook run after `org-refile' has inserted its stuff at the new location.
10738 Note that this is still *before* the stuff will be removed from
10739 the *old* location.")
10741 (defvar org-capture-last-stored-marker)
10742 (defun org-refile (&optional goto default-buffer rfloc)
10743 "Move the entry or entries at point to another heading.
10744 The list of target headings is compiled using the information in
10745 `org-refile-targets', which see.
10747 At the target location, the entry is filed as a subitem of the target
10748 heading. Depending on `org-reverse-note-order', the new subitem will
10749 either be the first or the last subitem.
10751 If there is an active region, all entries in that region will be moved.
10752 However, the region must fulfill the requirement that the first heading
10753 is the first one sets the top-level of the moved text - at most siblings
10754 below it are allowed.
10756 With prefix arg GOTO, the command will only visit the target location
10757 and not actually move anything.
10759 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10760 go to the location where the last refiling operation has put the subtree.
10761 With a prefix argument of `2', refile to the running clock.
10763 RFLOC can be a refile location obtained in a different way.
10765 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10767 If you are using target caching (see `org-refile-use-cache'),
10768 you have to clear the target cache in order to find new targets.
10769 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10770 prefix argument (`C-u C-u C-u C-c C-w')."
10772 (interactive "P")
10773 (if (member goto '(0 (64)))
10774 (org-refile-cache-clear)
10775 (let* ((cbuf (current-buffer))
10776 (regionp (org-region-active-p))
10777 (region-start (and regionp (region-beginning)))
10778 (region-end (and regionp (region-end)))
10779 (region-length (and regionp (- region-end region-start)))
10780 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10781 pos it nbuf file re level reversed)
10782 (setq last-command nil)
10783 (when regionp
10784 (goto-char region-start)
10785 (or (bolp) (goto-char (point-at-bol)))
10786 (setq region-start (point))
10787 (unless (or (org-kill-is-subtree-p
10788 (buffer-substring region-start region-end))
10789 (prog1 org-refile-active-region-within-subtree
10790 (org-toggle-heading)))
10791 (error "The region is not a (sequence of) subtree(s)")))
10792 (if (equal goto '(16))
10793 (org-refile-goto-last-stored)
10794 (when (or
10795 (and (equal goto 2)
10796 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10797 (prog1
10798 (setq it (list (or org-clock-heading "running clock")
10799 (buffer-file-name
10800 (marker-buffer org-clock-hd-marker))
10802 (marker-position org-clock-hd-marker)))
10803 (setq goto nil)))
10804 (setq it (or rfloc
10805 (let (heading-text)
10806 (save-excursion
10807 (unless goto
10808 (org-back-to-heading t)
10809 (setq heading-text
10810 (nth 4 (org-heading-components))))
10811 (org-refile-get-location
10812 (cond (goto "Goto")
10813 (regionp "Refile region to")
10814 (t (concat "Refile subtree \""
10815 heading-text "\" to")))
10816 default-buffer
10817 (and (not (equal '(4) goto))
10818 org-refile-allow-creating-parent-nodes)
10819 goto))))))
10820 (setq file (nth 1 it)
10821 re (nth 2 it)
10822 pos (nth 3 it))
10823 (if (and (not goto)
10825 (equal (buffer-file-name) file)
10826 (if regionp
10827 (and (>= pos region-start)
10828 (<= pos region-end))
10829 (and (>= pos (point))
10830 (< pos (save-excursion
10831 (org-end-of-subtree t t))))))
10832 (error "Cannot refile to position inside the tree or region"))
10834 (setq nbuf (or (find-buffer-visiting file)
10835 (find-file-noselect file)))
10836 (if goto
10837 (progn
10838 (org-pop-to-buffer-same-window nbuf)
10839 (goto-char pos)
10840 (org-show-context 'org-goto))
10841 (if regionp
10842 (progn
10843 (org-kill-new (buffer-substring region-start region-end))
10844 (org-save-markers-in-region region-start region-end))
10845 (org-copy-subtree 1 nil t))
10846 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10847 (find-file-noselect file)))
10848 (setq reversed (org-notes-order-reversed-p))
10849 (save-excursion
10850 (save-restriction
10851 (widen)
10852 (if pos
10853 (progn
10854 (goto-char pos)
10855 (looking-at org-outline-regexp)
10856 (setq level (org-get-valid-level (funcall outline-level) 1))
10857 (goto-char
10858 (if reversed
10859 (or (outline-next-heading) (point-max))
10860 (or (save-excursion (org-get-next-sibling))
10861 (org-end-of-subtree t t)
10862 (point-max)))))
10863 (setq level 1)
10864 (if (not reversed)
10865 (goto-char (point-max))
10866 (goto-char (point-min))
10867 (or (outline-next-heading) (goto-char (point-max)))))
10868 (if (not (bolp)) (newline))
10869 (org-paste-subtree level)
10870 (when org-log-refile
10871 (org-add-log-setup 'refile nil nil 'findpos
10872 org-log-refile)
10873 (unless (eq org-log-refile 'note)
10874 (save-excursion (org-add-log-note))))
10875 (and org-auto-align-tags
10876 (let ((org-loop-over-headlines-in-active-region nil))
10877 (org-set-tags nil t)))
10878 (bookmark-set "org-refile-last-stored")
10879 ;; If we are refiling for capture, make sure that the
10880 ;; last-capture pointers point here
10881 (when (org-bound-and-true-p org-refile-for-capture)
10882 (bookmark-set "org-capture-last-stored-marker")
10883 (move-marker org-capture-last-stored-marker (point)))
10884 (if (fboundp 'deactivate-mark) (deactivate-mark))
10885 (run-hooks 'org-after-refile-insert-hook))))
10886 (if regionp
10887 (delete-region (point) (+ (point) region-length))
10888 (org-cut-subtree))
10889 (when (featurep 'org-inlinetask)
10890 (org-inlinetask-remove-END-maybe))
10891 (setq org-markers-to-move nil)
10892 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10894 (defun org-refile-goto-last-stored ()
10895 "Go to the location where the last refile was stored."
10896 (interactive)
10897 (bookmark-jump "org-refile-last-stored")
10898 (message "This is the location of the last refile"))
10900 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10901 no-exclude)
10902 "Prompt the user for a refile location, using PROMPT.
10903 PROMPT should not be suffixed with a colon and a space, because
10904 this function appends the default value from
10905 `org-refile-history' automatically, if that is not empty.
10906 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10907 this is used for the GOTO interface."
10908 (let ((org-refile-targets org-refile-targets)
10909 (org-refile-use-outline-path org-refile-use-outline-path)
10910 excluded-entries)
10911 (when (and (derived-mode-p 'org-mode)
10912 (not org-refile-use-cache)
10913 (not no-exclude))
10914 (org-map-tree
10915 (lambda()
10916 (setq excluded-entries
10917 (append excluded-entries (list (org-get-heading t t)))))))
10918 (setq org-refile-target-table
10919 (org-refile-get-targets default-buffer excluded-entries)))
10920 (unless org-refile-target-table
10921 (error "No refile targets"))
10922 (let* ((prompt (concat prompt
10923 (and (car org-refile-history)
10924 (concat " (default " (car org-refile-history) ")"))
10925 ": "))
10926 (cbuf (current-buffer))
10927 (partial-completion-mode nil)
10928 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10929 (cfunc (if (and org-refile-use-outline-path
10930 org-outline-path-complete-in-steps)
10931 'org-olpath-completing-read
10932 'org-icompleting-read))
10933 (extra (if org-refile-use-outline-path "/" ""))
10934 (filename (and cfn (expand-file-name cfn)))
10935 (tbl (mapcar
10936 (lambda (x)
10937 (if (and (not (member org-refile-use-outline-path
10938 '(file full-file-path)))
10939 (not (equal filename (nth 1 x))))
10940 (cons (concat (car x) extra " ("
10941 (file-name-nondirectory (nth 1 x)) ")")
10942 (cdr x))
10943 (cons (concat (car x) extra) (cdr x))))
10944 org-refile-target-table))
10945 (completion-ignore-case t)
10946 pa answ parent-target child parent old-hist)
10947 (setq old-hist org-refile-history)
10948 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10949 nil 'org-refile-history (car org-refile-history)))
10950 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10951 (org-refile-check-position pa)
10952 (if pa
10953 (progn
10954 (when (or (not org-refile-history)
10955 (not (eq old-hist org-refile-history))
10956 (not (equal (car pa) (car org-refile-history))))
10957 (setq org-refile-history
10958 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10959 org-refile-history
10960 (cdr org-refile-history))))
10961 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10962 (pop org-refile-history)))
10964 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10965 (progn
10966 (setq parent (match-string 1 answ)
10967 child (match-string 2 answ))
10968 (setq parent-target (or (assoc parent tbl)
10969 (assoc (concat parent "/") tbl)))
10970 (when (and parent-target
10971 (or (eq new-nodes t)
10972 (and (eq new-nodes 'confirm)
10973 (y-or-n-p (format "Create new node \"%s\"? "
10974 child)))))
10975 (org-refile-new-child parent-target child)))
10976 (error "Invalid target location")))))
10978 (declare-function org-string-nw-p "org-macs.el" (s))
10979 (defun org-refile-check-position (refile-pointer)
10980 "Check if the refile pointer matches the readline to which it points."
10981 (let* ((file (nth 1 refile-pointer))
10982 (re (nth 2 refile-pointer))
10983 (pos (nth 3 refile-pointer))
10984 buffer)
10985 (when (org-string-nw-p re)
10986 (setq buffer (if (markerp pos)
10987 (marker-buffer pos)
10988 (or (find-buffer-visiting file)
10989 (find-file-noselect file))))
10990 (with-current-buffer buffer
10991 (save-excursion
10992 (save-restriction
10993 (widen)
10994 (goto-char pos)
10995 (beginning-of-line 1)
10996 (unless (org-looking-at-p re)
10997 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10999 (defun org-refile-new-child (parent-target child)
11000 "Use refile target PARENT-TARGET to add new CHILD below it."
11001 (unless parent-target
11002 (error "Cannot find parent for new node"))
11003 (let ((file (nth 1 parent-target))
11004 (pos (nth 3 parent-target))
11005 level)
11006 (with-current-buffer (or (find-buffer-visiting file)
11007 (find-file-noselect file))
11008 (save-excursion
11009 (save-restriction
11010 (widen)
11011 (if pos
11012 (goto-char pos)
11013 (goto-char (point-max))
11014 (if (not (bolp)) (newline)))
11015 (when (looking-at org-outline-regexp)
11016 (setq level (funcall outline-level))
11017 (org-end-of-subtree t t))
11018 (org-back-over-empty-lines)
11019 (insert "\n" (make-string
11020 (if pos (org-get-valid-level level 1) 1) ?*)
11021 " " child "\n")
11022 (beginning-of-line 0)
11023 (list (concat (car parent-target) "/" child) file "" (point)))))))
11025 (defun org-olpath-completing-read (prompt collection &rest args)
11026 "Read an outline path like a file name."
11027 (let ((thetable collection)
11028 (org-completion-use-ido nil) ; does not work with ido.
11029 (org-completion-use-iswitchb nil)) ; or iswitchb
11030 (apply
11031 'org-icompleting-read prompt
11032 (lambda (string predicate &optional flag)
11033 (let (rtn r f (l (length string)))
11034 (cond
11035 ((eq flag nil)
11036 ;; try completion
11037 (try-completion string thetable))
11038 ((eq flag t)
11039 ;; all-completions
11040 (setq rtn (all-completions string thetable predicate))
11041 (mapcar
11042 (lambda (x)
11043 (setq r (substring x l))
11044 (if (string-match " ([^)]*)$" x)
11045 (setq f (match-string 0 x))
11046 (setq f ""))
11047 (if (string-match "/" r)
11048 (concat string (substring r 0 (match-end 0)) f)
11050 rtn))
11051 ((eq flag 'lambda)
11052 ;; exact match?
11053 (assoc string thetable)))))
11054 args)))
11056 ;;;; Dynamic blocks
11058 (defun org-find-dblock (name)
11059 "Find the first dynamic block with name NAME in the buffer.
11060 If not found, stay at current position and return nil."
11061 (let (pos)
11062 (save-excursion
11063 (goto-char (point-min))
11064 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11065 nil t)
11066 (match-beginning 0))))
11067 (if pos (goto-char pos))
11068 pos))
11070 (defconst org-dblock-start-re
11071 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11072 "Matches the start line of a dynamic block, with parameters.")
11074 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11075 "Matches the end of a dynamic block.")
11077 (defun org-create-dblock (plist)
11078 "Create a dynamic block section, with parameters taken from PLIST.
11079 PLIST must contain a :name entry which is used as name of the block."
11080 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11081 (end-of-line 1)
11082 (newline))
11083 (let ((col (current-column))
11084 (name (plist-get plist :name)))
11085 (insert "#+BEGIN: " name)
11086 (while plist
11087 (if (eq (car plist) :name)
11088 (setq plist (cddr plist))
11089 (insert " " (prin1-to-string (pop plist)))))
11090 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11091 (beginning-of-line -2)))
11093 (defun org-prepare-dblock ()
11094 "Prepare dynamic block for refresh.
11095 This empties the block, puts the cursor at the insert position and returns
11096 the property list including an extra property :name with the block name."
11097 (unless (looking-at org-dblock-start-re)
11098 (error "Not at a dynamic block"))
11099 (let* ((begdel (1+ (match-end 0)))
11100 (name (org-no-properties (match-string 1)))
11101 (params (append (list :name name)
11102 (read (concat "(" (match-string 3) ")")))))
11103 (save-excursion
11104 (beginning-of-line 1)
11105 (skip-chars-forward " \t")
11106 (setq params (plist-put params :indentation-column (current-column))))
11107 (unless (re-search-forward org-dblock-end-re nil t)
11108 (error "Dynamic block not terminated"))
11109 (setq params
11110 (append params
11111 (list :content (buffer-substring
11112 begdel (match-beginning 0)))))
11113 (delete-region begdel (match-beginning 0))
11114 (goto-char begdel)
11115 (open-line 1)
11116 params))
11118 (defun org-map-dblocks (&optional command)
11119 "Apply COMMAND to all dynamic blocks in the current buffer.
11120 If COMMAND is not given, use `org-update-dblock'."
11121 (let ((cmd (or command 'org-update-dblock)))
11122 (save-excursion
11123 (goto-char (point-min))
11124 (while (re-search-forward org-dblock-start-re nil t)
11125 (goto-char (match-beginning 0))
11126 (save-excursion
11127 (condition-case nil
11128 (funcall cmd)
11129 (error (message "Error during update of dynamic block"))))
11130 (unless (re-search-forward org-dblock-end-re nil t)
11131 (error "Dynamic block not terminated"))))))
11133 (defun org-dblock-update (&optional arg)
11134 "User command for updating dynamic blocks.
11135 Update the dynamic block at point. With prefix ARG, update all dynamic
11136 blocks in the buffer."
11137 (interactive "P")
11138 (if arg
11139 (org-update-all-dblocks)
11140 (or (looking-at org-dblock-start-re)
11141 (org-beginning-of-dblock))
11142 (org-update-dblock)))
11144 (defun org-update-dblock ()
11145 "Update the dynamic block at point.
11146 This means to empty the block, parse for parameters and then call
11147 the correct writing function."
11148 (interactive)
11149 (save-window-excursion
11150 (let* ((pos (point))
11151 (line (org-current-line))
11152 (params (org-prepare-dblock))
11153 (name (plist-get params :name))
11154 (indent (plist-get params :indentation-column))
11155 (cmd (intern (concat "org-dblock-write:" name))))
11156 (message "Updating dynamic block `%s' at line %d..." name line)
11157 (funcall cmd params)
11158 (message "Updating dynamic block `%s' at line %d...done" name line)
11159 (goto-char pos)
11160 (when (and indent (> indent 0))
11161 (setq indent (make-string indent ?\ ))
11162 (save-excursion
11163 (org-beginning-of-dblock)
11164 (forward-line 1)
11165 (while (not (looking-at org-dblock-end-re))
11166 (insert indent)
11167 (beginning-of-line 2))
11168 (when (looking-at org-dblock-end-re)
11169 (and (looking-at "[ \t]+")
11170 (replace-match ""))
11171 (insert indent)))))))
11173 (defun org-beginning-of-dblock ()
11174 "Find the beginning of the dynamic block at point.
11175 Error if there is no such block at point."
11176 (let ((pos (point))
11177 beg)
11178 (end-of-line 1)
11179 (if (and (re-search-backward org-dblock-start-re nil t)
11180 (setq beg (match-beginning 0))
11181 (re-search-forward org-dblock-end-re nil t)
11182 (> (match-end 0) pos))
11183 (goto-char beg)
11184 (goto-char pos)
11185 (error "Not in a dynamic block"))))
11187 ;;;###autoload
11188 (defun org-update-all-dblocks ()
11189 "Update all dynamic blocks in the buffer.
11190 This function can be used in a hook."
11191 (interactive)
11192 (when (derived-mode-p 'org-mode)
11193 (org-map-dblocks 'org-update-dblock)))
11196 ;;;; Completion
11198 (defconst org-additional-option-like-keywords
11199 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11200 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11201 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11202 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11203 "BEGIN:" "END:"
11204 "ORGTBL" "TBLFM:" "TBLNAME:"
11205 "BEGIN_EXAMPLE" "END_EXAMPLE"
11206 "BEGIN_VERBATIM" "END_VERBATIM"
11207 "BEGIN_QUOTE" "END_QUOTE"
11208 "BEGIN_VERSE" "END_VERSE"
11209 "BEGIN_CENTER" "END_CENTER"
11210 "BEGIN_SRC" "END_SRC"
11211 "BEGIN_RESULT" "END_RESULT"
11212 "BEGIN_lstlisting" "END_lstlisting"
11213 "NAME:" "RESULTS:"
11214 "HEADER:" "HEADERS:"
11215 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11216 "CAPTION:" "LABEL:"
11217 "SETUPFILE:"
11218 "STARTUP:"
11219 "OPTIONS:"
11220 "INCLUDE:"
11221 "BIND:"
11222 "MACRO:"))
11224 (defconst org-additional-option-like-keywords-for-flyspell
11225 (delete-dups
11226 (split-string
11227 (mapconcat (lambda(k) (replace-regexp-in-string
11228 "_\\|:" " "
11229 (concat k " " (downcase k) " " (upcase k))))
11230 org-additional-option-like-keywords " ") " +" t)))
11232 (defcustom org-structure-template-alist
11234 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11235 "<src lang=\"?\">\n\n</src>")
11236 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11237 "<example>\n?\n</example>")
11238 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11239 "<quote>\n?\n</quote>")
11240 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11241 "<verse>\n?\n</verse>")
11242 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11243 "<center>\n?\n</center>")
11244 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11245 "<literal style=\"latex\">\n?\n</literal>")
11246 ("L" "#+LaTeX: "
11247 "<literal style=\"latex\">?</literal>")
11248 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11249 "<literal style=\"html\">\n?\n</literal>")
11250 ("H" "#+HTML: "
11251 "<literal style=\"html\">?</literal>")
11252 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11253 ("A" "#+ASCII: ")
11254 ("i" "#+INDEX: ?"
11255 "#+INDEX: ?")
11256 ("I" "#+INCLUDE %file ?"
11257 "<include file=%file markup=\"?\">")
11259 "Structure completion elements.
11260 This is a list of abbreviation keys and values. The value gets inserted
11261 if you type `<' followed by the key and then press the completion key,
11262 usually `M-TAB'. %file will be replaced by a file name after prompting
11263 for the file using completion. The cursor will be placed at the position
11264 of the `?` in the template.
11265 There are two templates for each key, the first uses the original Org syntax,
11266 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11267 the default when the /org-mtags.el/ module has been loaded. See also the
11268 variable `org-mtags-prefer-muse-templates'."
11269 :group 'org-completion
11270 :type '(repeat
11271 (string :tag "Key")
11272 (string :tag "Template")
11273 (string :tag "Muse Template")))
11275 (defun org-try-structure-completion ()
11276 "Try to complete a structure template before point.
11277 This looks for strings like \"<e\" on an otherwise empty line and
11278 expands them."
11279 (let ((l (buffer-substring (point-at-bol) (point)))
11281 (when (and (looking-at "[ \t]*$")
11282 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11283 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11284 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11285 (match-beginning 1)) a)
11286 t)))
11288 (defun org-complete-expand-structure-template (start cell)
11289 "Expand a structure template."
11290 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11291 (rpl (nth (if musep 2 1) cell))
11292 (ind ""))
11293 (delete-region start (point))
11294 (when (string-match "\\`#\\+" rpl)
11295 (cond
11296 ((bolp))
11297 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11298 (setq ind (buffer-substring (point-at-bol) (point))))
11299 (t (newline))))
11300 (setq start (point))
11301 (if (string-match "%file" rpl)
11302 (setq rpl (replace-match
11303 (concat
11304 "\""
11305 (save-match-data
11306 (abbreviate-file-name (read-file-name "Include file: ")))
11307 "\"")
11308 t t rpl)))
11309 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11310 (concat "\n" ind)))
11311 (insert rpl)
11312 (if (re-search-backward "\\?" start t) (delete-char 1))))
11314 ;;;; TODO, DEADLINE, Comments
11316 (defun org-toggle-comment ()
11317 "Change the COMMENT state of an entry."
11318 (interactive)
11319 (save-excursion
11320 (org-back-to-heading)
11321 (let (case-fold-search)
11322 (cond
11323 ((looking-at (format org-heading-keyword-regexp-format
11324 org-comment-string))
11325 (goto-char (match-end 1))
11326 (looking-at (concat " +" org-comment-string))
11327 (replace-match "" t t)
11328 (when (eolp) (insert " ")))
11329 ((looking-at org-outline-regexp)
11330 (goto-char (match-end 0))
11331 (insert org-comment-string " "))))))
11333 (defvar org-last-todo-state-is-todo nil
11334 "This is non-nil when the last TODO state change led to a TODO state.
11335 If the last change removed the TODO tag or switched to DONE, then
11336 this is nil.")
11338 (defvar org-setting-tags nil) ; dynamically skipped
11340 (defvar org-todo-setup-filter-hook nil
11341 "Hook for functions that pre-filter todo specs.
11342 Each function takes a todo spec and returns either nil or the spec
11343 transformed into canonical form." )
11345 (defvar org-todo-get-default-hook nil
11346 "Hook for functions that get a default item for todo.
11347 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11348 nil or a string to be used for the todo mark." )
11350 (defvar org-agenda-headline-snapshot-before-repeat)
11352 (defun org-current-effective-time ()
11353 "Return current time adjusted for `org-extend-today-until' variable."
11354 (let* ((ct (org-current-time))
11355 (dct (decode-time ct))
11356 (ct1
11357 (if (and org-use-effective-time
11358 (< (nth 2 dct) org-extend-today-until))
11359 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11360 ct)))
11361 ct1))
11363 (defun org-todo-yesterday (&optional arg)
11364 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11365 (interactive "P")
11366 (if (eq major-mode 'org-agenda-mode)
11367 (apply 'org-agenda-todo-yesterday arg)
11368 (let* ((hour (third (decode-time
11369 (org-current-time))))
11370 (org-extend-today-until (1+ hour)))
11371 (org-todo arg))))
11373 (defun org-todo (&optional arg)
11374 "Change the TODO state of an item.
11375 The state of an item is given by a keyword at the start of the heading,
11376 like
11377 *** TODO Write paper
11378 *** DONE Call mom
11380 The different keywords are specified in the variable `org-todo-keywords'.
11381 By default the available states are \"TODO\" and \"DONE\".
11382 So for this example: when the item starts with TODO, it is changed to DONE.
11383 When it starts with DONE, the DONE is removed. And when neither TODO nor
11384 DONE are present, add TODO at the beginning of the heading.
11386 With \\[universal-argument] prefix arg, use completion to determine the new \
11387 state.
11388 With numeric prefix arg, switch to that state.
11389 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11390 keywords (nextset).
11391 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11392 With a numeric prefix arg of 0, inhibit note taking for the change.
11394 For calling through lisp, arg is also interpreted in the following way:
11395 'none -> empty state
11396 \"\"(empty string) -> switch to empty state
11397 'done -> switch to DONE
11398 'nextset -> switch to the next set of keywords
11399 'previousset -> switch to the previous set of keywords
11400 \"WAITING\" -> switch to the specified keyword, but only if it
11401 really is a member of `org-todo-keywords'."
11402 (interactive "P")
11403 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11404 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11405 'region-start-level 'region))
11406 org-loop-over-headlines-in-active-region)
11407 (org-map-entries
11408 `(org-todo ,arg)
11409 org-loop-over-headlines-in-active-region
11410 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11411 (if (equal arg '(16)) (setq arg 'nextset))
11412 (let ((org-blocker-hook org-blocker-hook)
11413 (case-fold-search nil))
11414 (when (equal arg '(64))
11415 (setq arg nil org-blocker-hook nil))
11416 (when (and org-blocker-hook
11417 (or org-inhibit-blocking
11418 (org-entry-get nil "NOBLOCKING")))
11419 (setq org-blocker-hook nil))
11420 (save-excursion
11421 (catch 'exit
11422 (org-back-to-heading t)
11423 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11424 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11425 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11426 (let* ((match-data (match-data))
11427 (startpos (point-at-bol))
11428 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11429 (org-log-done org-log-done)
11430 (org-log-repeat org-log-repeat)
11431 (org-todo-log-states org-todo-log-states)
11432 (org-inhibit-logging
11433 (if (equal arg 0)
11434 (progn (setq arg nil) 'note) org-inhibit-logging))
11435 (this (match-string 1))
11436 (hl-pos (match-beginning 0))
11437 (head (org-get-todo-sequence-head this))
11438 (ass (assoc head org-todo-kwd-alist))
11439 (interpret (nth 1 ass))
11440 (done-word (nth 3 ass))
11441 (final-done-word (nth 4 ass))
11442 (org-last-state (or this ""))
11443 (completion-ignore-case t)
11444 (member (member this org-todo-keywords-1))
11445 (tail (cdr member))
11446 (org-state (cond
11447 ((and org-todo-key-trigger
11448 (or (and (equal arg '(4))
11449 (eq org-use-fast-todo-selection 'prefix))
11450 (and (not arg) org-use-fast-todo-selection
11451 (not (eq org-use-fast-todo-selection
11452 'prefix)))))
11453 ;; Use fast selection
11454 (org-fast-todo-selection))
11455 ((and (equal arg '(4))
11456 (or (not org-use-fast-todo-selection)
11457 (not org-todo-key-trigger)))
11458 ;; Read a state with completion
11459 (org-icompleting-read
11460 "State: " (mapcar (lambda(x) (list x))
11461 org-todo-keywords-1)
11462 nil t))
11463 ((eq arg 'right)
11464 (if this
11465 (if tail (car tail) nil)
11466 (car org-todo-keywords-1)))
11467 ((eq arg 'left)
11468 (if (equal member org-todo-keywords-1)
11470 (if this
11471 (nth (- (length org-todo-keywords-1)
11472 (length tail) 2)
11473 org-todo-keywords-1)
11474 (org-last org-todo-keywords-1))))
11475 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11476 (setq arg nil))) ; hack to fall back to cycling
11477 (arg
11478 ;; user or caller requests a specific state
11479 (cond
11480 ((equal arg "") nil)
11481 ((eq arg 'none) nil)
11482 ((eq arg 'done) (or done-word (car org-done-keywords)))
11483 ((eq arg 'nextset)
11484 (or (car (cdr (member head org-todo-heads)))
11485 (car org-todo-heads)))
11486 ((eq arg 'previousset)
11487 (let ((org-todo-heads (reverse org-todo-heads)))
11488 (or (car (cdr (member head org-todo-heads)))
11489 (car org-todo-heads))))
11490 ((car (member arg org-todo-keywords-1)))
11491 ((stringp arg)
11492 (error "State `%s' not valid in this file" arg))
11493 ((nth (1- (prefix-numeric-value arg))
11494 org-todo-keywords-1))))
11495 ((null member) (or head (car org-todo-keywords-1)))
11496 ((equal this final-done-word) nil) ;; -> make empty
11497 ((null tail) nil) ;; -> first entry
11498 ((memq interpret '(type priority))
11499 (if (eq this-command last-command)
11500 (car tail)
11501 (if (> (length tail) 0)
11502 (or done-word (car org-done-keywords))
11503 nil)))
11505 (car tail))))
11506 (org-state (or
11507 (run-hook-with-args-until-success
11508 'org-todo-get-default-hook org-state org-last-state)
11509 org-state))
11510 (next (if org-state (concat " " org-state " ") " "))
11511 (change-plist (list :type 'todo-state-change :from this :to org-state
11512 :position startpos))
11513 dolog now-done-p)
11514 (when org-blocker-hook
11515 (setq org-last-todo-state-is-todo
11516 (not (member this org-done-keywords)))
11517 (unless (save-excursion
11518 (save-match-data
11519 (org-with-wide-buffer
11520 (run-hook-with-args-until-failure
11521 'org-blocker-hook change-plist))))
11522 (if (org-called-interactively-p 'interactive)
11523 (error "TODO state change from %s to %s blocked" this org-state)
11524 ;; fail silently
11525 (message "TODO state change from %s to %s blocked" this org-state)
11526 (throw 'exit nil))))
11527 (store-match-data match-data)
11528 (replace-match next t t)
11529 (unless (pos-visible-in-window-p hl-pos)
11530 (message "TODO state changed to %s" (org-trim next)))
11531 (unless head
11532 (setq head (org-get-todo-sequence-head org-state)
11533 ass (assoc head org-todo-kwd-alist)
11534 interpret (nth 1 ass)
11535 done-word (nth 3 ass)
11536 final-done-word (nth 4 ass)))
11537 (when (memq arg '(nextset previousset))
11538 (message "Keyword-Set %d/%d: %s"
11539 (- (length org-todo-sets) -1
11540 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11541 (length org-todo-sets)
11542 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11543 (setq org-last-todo-state-is-todo
11544 (not (member org-state org-done-keywords)))
11545 (setq now-done-p (and (member org-state org-done-keywords)
11546 (not (member this org-done-keywords))))
11547 (and logging (org-local-logging logging))
11548 (when (and (or org-todo-log-states org-log-done)
11549 (not (eq org-inhibit-logging t))
11550 (not (memq arg '(nextset previousset))))
11551 ;; we need to look at recording a time and note
11552 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11553 (nth 2 (assoc this org-todo-log-states))))
11554 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11555 (setq dolog 'time))
11556 (when (and org-state
11557 (member org-state org-not-done-keywords)
11558 (not (member this org-not-done-keywords)))
11559 ;; This is now a todo state and was not one before
11560 ;; If there was a CLOSED time stamp, get rid of it.
11561 (org-add-planning-info nil nil 'closed))
11562 (when (and now-done-p org-log-done)
11563 ;; It is now done, and it was not done before
11564 (org-add-planning-info 'closed (org-current-effective-time))
11565 (if (and (not dolog) (eq 'note org-log-done))
11566 (org-add-log-setup 'done org-state this 'findpos 'note)))
11567 (when (and org-state dolog)
11568 ;; This is a non-nil state, and we need to log it
11569 (org-add-log-setup 'state org-state this 'findpos dolog)))
11570 ;; Fixup tag positioning
11571 (org-todo-trigger-tag-changes org-state)
11572 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11573 (when org-provide-todo-statistics
11574 (org-update-parent-todo-statistics))
11575 (run-hooks 'org-after-todo-state-change-hook)
11576 (if (and arg (not (member org-state org-done-keywords)))
11577 (setq head (org-get-todo-sequence-head org-state)))
11578 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11579 ;; Do we need to trigger a repeat?
11580 (when now-done-p
11581 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11582 ;; This is for the agenda, take a snapshot of the headline.
11583 (save-match-data
11584 (setq org-agenda-headline-snapshot-before-repeat
11585 (org-get-heading))))
11586 (org-auto-repeat-maybe org-state))
11587 ;; Fixup cursor location if close to the keyword
11588 (if (and (outline-on-heading-p)
11589 (not (bolp))
11590 (save-excursion (beginning-of-line 1)
11591 (looking-at org-todo-line-regexp))
11592 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11593 (progn
11594 (goto-char (or (match-end 2) (match-end 1)))
11595 (and (looking-at " ") (just-one-space))))
11596 (when org-trigger-hook
11597 (save-excursion
11598 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11600 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11601 "Block turning an entry into a TODO, using the hierarchy.
11602 This checks whether the current task should be blocked from state
11603 changes. Such blocking occurs when:
11605 1. The task has children which are not all in a completed state.
11607 2. A task has a parent with the property :ORDERED:, and there
11608 are siblings prior to the current task with incomplete
11609 status.
11611 3. The parent of the task is blocked because it has siblings that should
11612 be done first, or is child of a block grandparent TODO entry."
11614 (if (not org-enforce-todo-dependencies)
11615 t ; if locally turned off don't block
11616 (catch 'dont-block
11617 ;; If this is not a todo state change, or if this entry is already DONE,
11618 ;; do not block
11619 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11620 (member (plist-get change-plist :from)
11621 (cons 'done org-done-keywords))
11622 (member (plist-get change-plist :to)
11623 (cons 'todo org-not-done-keywords))
11624 (not (plist-get change-plist :to)))
11625 (throw 'dont-block t))
11626 ;; If this task has children, and any are undone, it's blocked
11627 (save-excursion
11628 (org-back-to-heading t)
11629 (let ((this-level (funcall outline-level)))
11630 (outline-next-heading)
11631 (let ((child-level (funcall outline-level)))
11632 (while (and (not (eobp))
11633 (> child-level this-level))
11634 ;; this todo has children, check whether they are all
11635 ;; completed
11636 (if (and (not (org-entry-is-done-p))
11637 (org-entry-is-todo-p))
11638 (throw 'dont-block nil))
11639 (outline-next-heading)
11640 (setq child-level (funcall outline-level))))))
11641 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11642 ;; any previous siblings are undone, it's blocked
11643 (save-excursion
11644 (org-back-to-heading t)
11645 (let* ((pos (point))
11646 (parent-pos (and (org-up-heading-safe) (point))))
11647 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11648 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11649 (forward-line 1)
11650 (re-search-forward org-not-done-heading-regexp pos t))
11651 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11652 ;; Search further up the hierarchy, to see if an ancestor is blocked
11653 (while t
11654 (goto-char parent-pos)
11655 (if (not (looking-at org-not-done-heading-regexp))
11656 (throw 'dont-block t)) ; do not block, parent is not a TODO
11657 (setq pos (point))
11658 (setq parent-pos (and (org-up-heading-safe) (point)))
11659 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11660 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11661 (forward-line 1)
11662 (re-search-forward org-not-done-heading-regexp pos t))
11663 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11665 (defcustom org-track-ordered-property-with-tag nil
11666 "Should the ORDERED property also be shown as a tag?
11667 The ORDERED property decides if an entry should require subtasks to be
11668 completed in sequence. Since a property is not very visible, setting
11669 this option means that toggling the ORDERED property with the command
11670 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11671 not relevant for the behavior, but it makes things more visible.
11673 Note that toggling the tag with tags commands will not change the property
11674 and therefore not influence behavior!
11676 This can be t, meaning the tag ORDERED should be used, It can also be a
11677 string to select a different tag for this task."
11678 :group 'org-todo
11679 :type '(choice
11680 (const :tag "No tracking" nil)
11681 (const :tag "Track with ORDERED tag" t)
11682 (string :tag "Use other tag")))
11684 (defun org-toggle-ordered-property ()
11685 "Toggle the ORDERED property of the current entry.
11686 For better visibility, you can track the value of this property with a tag.
11687 See variable `org-track-ordered-property-with-tag'."
11688 (interactive)
11689 (let* ((t1 org-track-ordered-property-with-tag)
11690 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11691 (save-excursion
11692 (org-back-to-heading)
11693 (if (org-entry-get nil "ORDERED")
11694 (progn
11695 (org-delete-property "ORDERED")
11696 (and tag (org-toggle-tag tag 'off))
11697 (message "Subtasks can be completed in arbitrary order"))
11698 (org-entry-put nil "ORDERED" "t")
11699 (and tag (org-toggle-tag tag 'on))
11700 (message "Subtasks must be completed in sequence")))))
11702 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11703 (defun org-block-todo-from-checkboxes (change-plist)
11704 "Block turning an entry into a TODO, using checkboxes.
11705 This checks whether the current task should be blocked from state
11706 changes because there are unchecked boxes in this entry."
11707 (if (not org-enforce-todo-checkbox-dependencies)
11708 t ; if locally turned off don't block
11709 (catch 'dont-block
11710 ;; If this is not a todo state change, or if this entry is already DONE,
11711 ;; do not block
11712 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11713 (member (plist-get change-plist :from)
11714 (cons 'done org-done-keywords))
11715 (member (plist-get change-plist :to)
11716 (cons 'todo org-not-done-keywords))
11717 (not (plist-get change-plist :to)))
11718 (throw 'dont-block t))
11719 ;; If this task has checkboxes that are not checked, it's blocked
11720 (save-excursion
11721 (org-back-to-heading t)
11722 (let ((beg (point)) end)
11723 (outline-next-heading)
11724 (setq end (point))
11725 (goto-char beg)
11726 (if (org-list-search-forward
11727 (concat (org-item-beginning-re)
11728 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11729 "\\[[- ]\\]")
11730 end t)
11731 (progn
11732 (if (boundp 'org-blocked-by-checkboxes)
11733 (setq org-blocked-by-checkboxes t))
11734 (throw 'dont-block nil)))))
11735 t))) ; do not block
11737 (defun org-entry-blocked-p ()
11738 "Is the current entry blocked?"
11739 (if (org-entry-get nil "NOBLOCKING")
11740 nil ;; Never block this entry
11741 (not
11742 (run-hook-with-args-until-failure
11743 'org-blocker-hook
11744 (list :type 'todo-state-change
11745 :position (point)
11746 :from 'todo
11747 :to 'done)))))
11749 (defun org-update-statistics-cookies (all)
11750 "Update the statistics cookie, either from TODO or from checkboxes.
11751 This should be called with the cursor in a line with a statistics cookie."
11752 (interactive "P")
11753 (if all
11754 (progn
11755 (org-update-checkbox-count 'all)
11756 (org-map-entries 'org-update-parent-todo-statistics))
11757 (if (not (org-at-heading-p))
11758 (org-update-checkbox-count)
11759 (let ((pos (move-marker (make-marker) (point)))
11760 end l1 l2)
11761 (ignore-errors (org-back-to-heading t))
11762 (if (not (org-at-heading-p))
11763 (org-update-checkbox-count)
11764 (setq l1 (org-outline-level))
11765 (setq end (save-excursion
11766 (outline-next-heading)
11767 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11768 (point)))
11769 (if (and (save-excursion
11770 (re-search-forward
11771 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11772 (not (save-excursion (re-search-forward
11773 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11774 (org-update-checkbox-count)
11775 (if (and l2 (> l2 l1))
11776 (progn
11777 (goto-char end)
11778 (org-update-parent-todo-statistics))
11779 (goto-char pos)
11780 (beginning-of-line 1)
11781 (while (re-search-forward
11782 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11783 (point-at-eol) t)
11784 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11785 (goto-char pos)
11786 (move-marker pos nil)))))
11788 (defvar org-entry-property-inherited-from) ;; defined below
11789 (defun org-update-parent-todo-statistics ()
11790 "Update any statistics cookie in the parent of the current headline.
11791 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11792 the entire subtree and this will travel up the hierarchy and update
11793 statistics everywhere."
11794 (let* ((prop (save-excursion (org-up-heading-safe)
11795 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11796 (recursive (or (not org-hierarchical-todo-statistics)
11797 (and prop (string-match "\\<recursive\\>" prop))))
11798 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11800 (first t)
11801 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11802 level ltoggle l1 new ndel
11803 (cnt-all 0) (cnt-done 0) is-percent kwd
11804 checkbox-beg ov ovs ove cookie-present)
11805 (catch 'exit
11806 (save-excursion
11807 (beginning-of-line 1)
11808 (setq ltoggle (funcall outline-level))
11809 ;; Three situations are to consider:
11811 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11812 ;; to the top-level ancestor on the headline;
11814 ;; 2. If parent has "recursive" property, repeat up to the
11815 ;; headline setting that property, taking inheritance into
11816 ;; account;
11818 ;; 3. Else, move up to direct parent and proceed only once.
11819 (while (and (setq level (org-up-heading-safe))
11820 (or recursive first)
11821 (>= (point) lim))
11822 (setq first nil cookie-present nil)
11823 (unless (and level
11824 (not (string-match
11825 "\\<checkbox\\>"
11826 (downcase (or (org-entry-get nil "COOKIE_DATA")
11827 "")))))
11828 (throw 'exit nil))
11829 (while (re-search-forward box-re (point-at-eol) t)
11830 (setq cnt-all 0 cnt-done 0 cookie-present t)
11831 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11832 (save-match-data
11833 (unless (outline-next-heading) (throw 'exit nil))
11834 (while (and (looking-at org-complex-heading-regexp)
11835 (> (setq l1 (length (match-string 1))) level))
11836 (setq kwd (and (or recursive (= l1 ltoggle))
11837 (match-string 2)))
11838 (if (or (eq org-provide-todo-statistics 'all-headlines)
11839 (and (listp org-provide-todo-statistics)
11840 (or (member kwd org-provide-todo-statistics)
11841 (member kwd org-done-keywords))))
11842 (setq cnt-all (1+ cnt-all))
11843 (if (eq org-provide-todo-statistics t)
11844 (and kwd (setq cnt-all (1+ cnt-all)))))
11845 (and (member kwd org-done-keywords)
11846 (setq cnt-done (1+ cnt-done)))
11847 (outline-next-heading)))
11848 (setq new
11849 (if is-percent
11850 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11851 (format "[%d/%d]" cnt-done cnt-all))
11852 ndel (- (match-end 0) checkbox-beg))
11853 ;; handle overlays when updating cookie from column view
11854 (when (setq ov (car (overlays-at checkbox-beg)))
11855 (setq ovs (overlay-start ov) ove (overlay-end ov))
11856 (delete-overlay ov))
11857 (goto-char checkbox-beg)
11858 (insert new)
11859 (delete-region (point) (+ (point) ndel))
11860 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11861 (when ov (move-overlay ov ovs ove)))
11862 (when cookie-present
11863 (run-hook-with-args 'org-after-todo-statistics-hook
11864 cnt-done (- cnt-all cnt-done))))))
11865 (run-hooks 'org-todo-statistics-hook)))
11867 (defvar org-after-todo-statistics-hook nil
11868 "Hook that is called after a TODO statistics cookie has been updated.
11869 Each function is called with two arguments: the number of not-done entries
11870 and the number of done entries.
11872 For example, the following function, when added to this hook, will switch
11873 an entry to DONE when all children are done, and back to TODO when new
11874 entries are set to a TODO status. Note that this hook is only called
11875 when there is a statistics cookie in the headline!
11877 (defun org-summary-todo (n-done n-not-done)
11878 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11879 (let (org-log-done org-log-states) ; turn off logging
11880 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11883 (defvar org-todo-statistics-hook nil
11884 "Hook that is run whenever Org thinks TODO statistics should be updated.
11885 This hook runs even if there is no statistics cookie present, in which case
11886 `org-after-todo-statistics-hook' would not run.")
11888 (defun org-todo-trigger-tag-changes (state)
11889 "Apply the changes defined in `org-todo-state-tags-triggers'."
11890 (let ((l org-todo-state-tags-triggers)
11891 changes)
11892 (when (or (not state) (equal state ""))
11893 (setq changes (append changes (cdr (assoc "" l)))))
11894 (when (and (stringp state) (> (length state) 0))
11895 (setq changes (append changes (cdr (assoc state l)))))
11896 (when (member state org-not-done-keywords)
11897 (setq changes (append changes (cdr (assoc 'todo l)))))
11898 (when (member state org-done-keywords)
11899 (setq changes (append changes (cdr (assoc 'done l)))))
11900 (dolist (c changes)
11901 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11903 (defun org-local-logging (value)
11904 "Get logging settings from a property VALUE."
11905 (let* (words w a)
11906 ;; directly set the variables, they are already local.
11907 (setq org-log-done nil
11908 org-log-repeat nil
11909 org-todo-log-states nil)
11910 (setq words (org-split-string value))
11911 (while (setq w (pop words))
11912 (cond
11913 ((setq a (assoc w org-startup-options))
11914 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11915 (set (nth 1 a) (nth 2 a))))
11916 ((setq a (org-extract-log-state-settings w))
11917 (and (member (car a) org-todo-keywords-1)
11918 (push a org-todo-log-states)))))))
11920 (defun org-get-todo-sequence-head (kwd)
11921 "Return the head of the TODO sequence to which KWD belongs.
11922 If KWD is not set, check if there is a text property remembering the
11923 right sequence."
11924 (let (p)
11925 (cond
11926 ((not kwd)
11927 (or (get-text-property (point-at-bol) 'org-todo-head)
11928 (progn
11929 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11930 nil (point-at-eol)))
11931 (get-text-property p 'org-todo-head))))
11932 ((not (member kwd org-todo-keywords-1))
11933 (car org-todo-keywords-1))
11934 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11936 (defun org-fast-todo-selection ()
11937 "Fast TODO keyword selection with single keys.
11938 Returns the new TODO keyword, or nil if no state change should occur."
11939 (let* ((fulltable org-todo-key-alist)
11940 (done-keywords org-done-keywords) ;; needed for the faces.
11941 (maxlen (apply 'max (mapcar
11942 (lambda (x)
11943 (if (stringp (car x)) (string-width (car x)) 0))
11944 fulltable)))
11945 (expert nil)
11946 (fwidth (+ maxlen 3 1 3))
11947 (ncol (/ (- (window-width) 4) fwidth))
11948 tg cnt e c tbl
11949 groups ingroup)
11950 (save-excursion
11951 (save-window-excursion
11952 (if expert
11953 (set-buffer (get-buffer-create " *Org todo*"))
11954 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11955 (erase-buffer)
11956 (org-set-local 'org-done-keywords done-keywords)
11957 (setq tbl fulltable cnt 0)
11958 (while (setq e (pop tbl))
11959 (cond
11960 ((equal e '(:startgroup))
11961 (push '() groups) (setq ingroup t)
11962 (when (not (= cnt 0))
11963 (setq cnt 0)
11964 (insert "\n"))
11965 (insert "{ "))
11966 ((equal e '(:endgroup))
11967 (setq ingroup nil cnt 0)
11968 (insert "}\n"))
11969 ((equal e '(:newline))
11970 (when (not (= cnt 0))
11971 (setq cnt 0)
11972 (insert "\n")
11973 (setq e (car tbl))
11974 (while (equal (car tbl) '(:newline))
11975 (insert "\n")
11976 (setq tbl (cdr tbl)))))
11978 (setq tg (car e) c (cdr e))
11979 (if ingroup (push tg (car groups)))
11980 (setq tg (org-add-props tg nil 'face
11981 (org-get-todo-face tg)))
11982 (if (and (= cnt 0) (not ingroup)) (insert " "))
11983 (insert "[" c "] " tg (make-string
11984 (- fwidth 4 (length tg)) ?\ ))
11985 (when (= (setq cnt (1+ cnt)) ncol)
11986 (insert "\n")
11987 (if ingroup (insert " "))
11988 (setq cnt 0)))))
11989 (insert "\n")
11990 (goto-char (point-min))
11991 (if (not expert) (org-fit-window-to-buffer))
11992 (message "[a-z..]:Set [SPC]:clear")
11993 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11994 (cond
11995 ((or (= c ?\C-g)
11996 (and (= c ?q) (not (rassoc c fulltable))))
11997 (setq quit-flag t))
11998 ((= c ?\ ) nil)
11999 ((setq e (rassoc c fulltable) tg (car e))
12001 (t (setq quit-flag t)))))))
12003 (defun org-entry-is-todo-p ()
12004 (member (org-get-todo-state) org-not-done-keywords))
12006 (defun org-entry-is-done-p ()
12007 (member (org-get-todo-state) org-done-keywords))
12009 (defun org-get-todo-state ()
12010 (save-excursion
12011 (org-back-to-heading t)
12012 (and (looking-at org-todo-line-regexp)
12013 (match-end 2)
12014 (match-string 2))))
12016 (defun org-at-date-range-p (&optional inactive-ok)
12017 "Is the cursor inside a date range?"
12018 (interactive)
12019 (save-excursion
12020 (catch 'exit
12021 (let ((pos (point)))
12022 (skip-chars-backward "^[<\r\n")
12023 (skip-chars-backward "<[")
12024 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12025 (>= (match-end 0) pos)
12026 (throw 'exit t))
12027 (skip-chars-backward "^<[\r\n")
12028 (skip-chars-backward "<[")
12029 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12030 (>= (match-end 0) pos)
12031 (throw 'exit t)))
12032 nil)))
12034 (defun org-get-repeat (&optional tagline)
12035 "Check if there is a deadline/schedule with repeater in this entry."
12036 (save-match-data
12037 (save-excursion
12038 (org-back-to-heading t)
12039 (and (re-search-forward (if tagline
12040 (concat tagline "\\s-*" org-repeat-re)
12041 org-repeat-re)
12042 (org-entry-end-position) t)
12043 (match-string-no-properties 1)))))
12045 (defvar org-last-changed-timestamp)
12046 (defvar org-last-inserted-timestamp)
12047 (defvar org-log-post-message)
12048 (defvar org-log-note-purpose)
12049 (defvar org-log-note-how)
12050 (defvar org-log-note-extra)
12051 (defun org-auto-repeat-maybe (done-word)
12052 "Check if the current headline contains a repeated deadline/schedule.
12053 If yes, set TODO state back to what it was and change the base date
12054 of repeating deadline/scheduled time stamps to new date.
12055 This function is run automatically after each state change to a DONE state."
12056 ;; last-state is dynamically scoped into this function
12057 (let* ((repeat (org-get-repeat))
12058 (aa (assoc org-last-state org-todo-kwd-alist))
12059 (interpret (nth 1 aa))
12060 (head (nth 2 aa))
12061 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12062 (msg "Entry repeats: ")
12063 (org-log-done nil)
12064 (org-todo-log-states nil)
12065 re type n what ts time to-state)
12066 (when repeat
12067 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12068 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12069 org-todo-repeat-to-state))
12070 (unless (and to-state (member to-state org-todo-keywords-1))
12071 (setq to-state (if (eq interpret 'type) org-last-state head)))
12072 (org-todo to-state)
12073 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12074 (org-entry-put nil "LAST_REPEAT" (format-time-string
12075 (org-time-stamp-format t t))))
12076 (when org-log-repeat
12077 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12078 (memq 'org-add-log-note post-command-hook))
12079 ;; OK, we are already setup for some record
12080 (if (eq org-log-repeat 'note)
12081 ;; make sure we take a note, not only a time stamp
12082 (setq org-log-note-how 'note))
12083 ;; Set up for taking a record
12084 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12085 org-last-state
12086 'findpos org-log-repeat)))
12087 (org-back-to-heading t)
12088 (org-add-planning-info nil nil 'closed)
12089 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12090 org-deadline-time-regexp "\\)\\|\\("
12091 org-ts-regexp "\\)"))
12092 (while (re-search-forward
12093 re (save-excursion (outline-next-heading) (point)) t)
12094 (setq type (if (match-end 1) org-scheduled-string
12095 (if (match-end 3) org-deadline-string "Plain:"))
12096 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12097 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12098 (setq n (string-to-number (match-string 2 ts))
12099 what (match-string 3 ts))
12100 (if (equal what "w") (setq n (* n 7) what "d"))
12101 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12102 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12103 ;; Preparation, see if we need to modify the start date for the change
12104 (when (match-end 1)
12105 (setq time (save-match-data (org-time-string-to-time ts)))
12106 (cond
12107 ((equal (match-string 1 ts) ".")
12108 ;; Shift starting date to today
12109 (org-timestamp-change
12110 (- (org-today) (time-to-days time))
12111 'day))
12112 ((equal (match-string 1 ts) "+")
12113 (let ((nshiftmax 10) (nshift 0))
12114 (while (or (= nshift 0)
12115 (<= (time-to-days time)
12116 (time-to-days (current-time))))
12117 (when (= (incf nshift) nshiftmax)
12118 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12119 (error "Abort")))
12120 (org-timestamp-change n (cdr (assoc what whata)))
12121 (org-at-timestamp-p t)
12122 (setq ts (match-string 1))
12123 (setq time (save-match-data (org-time-string-to-time ts)))))
12124 (org-timestamp-change (- n) (cdr (assoc what whata)))
12125 ;; rematch, so that we have everything in place for the real shift
12126 (org-at-timestamp-p t)
12127 (setq ts (match-string 1))
12128 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12129 (org-timestamp-change n (cdr (assoc what whata)))
12130 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12131 (setq org-log-post-message msg)
12132 (message "%s" msg))))
12134 (defun org-show-todo-tree (arg)
12135 "Make a compact tree which shows all headlines marked with TODO.
12136 The tree will show the lines where the regexp matches, and all higher
12137 headlines above the match.
12138 With a \\[universal-argument] prefix, prompt for a regexp to match.
12139 With a numeric prefix N, construct a sparse tree for the Nth element
12140 of `org-todo-keywords-1'."
12141 (interactive "P")
12142 (let ((case-fold-search nil)
12143 (kwd-re
12144 (cond ((null arg) org-not-done-regexp)
12145 ((equal arg '(4))
12146 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12147 (mapcar 'list org-todo-keywords-1))))
12148 (concat "\\("
12149 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12150 "\\)\\>")))
12151 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12152 (regexp-quote (nth (1- (prefix-numeric-value arg))
12153 org-todo-keywords-1)))
12154 (t (error "Invalid prefix argument: %s" arg)))))
12155 (message "%d TODO entries found"
12156 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12158 (defun org-deadline (&optional remove time)
12159 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12160 With argument REMOVE, remove any deadline from the item.
12161 With argument TIME, set the deadline at the corresponding date. TIME
12162 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12163 (interactive "P")
12164 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12165 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12166 'region-start-level 'region))
12167 org-loop-over-headlines-in-active-region)
12168 (org-map-entries
12169 `(org-deadline ',remove ,time)
12170 org-loop-over-headlines-in-active-region
12171 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12172 (let* ((old-date (org-entry-get nil "DEADLINE"))
12173 (repeater (and old-date
12174 (string-match
12175 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12176 old-date)
12177 (match-string 1 old-date))))
12178 (if remove
12179 (progn
12180 (when (and old-date org-log-redeadline)
12181 (org-add-log-setup 'deldeadline nil old-date 'findpos
12182 org-log-redeadline))
12183 (org-remove-timestamp-with-keyword org-deadline-string)
12184 (message "Item no longer has a deadline."))
12185 (org-add-planning-info 'deadline time 'closed)
12186 (when (and old-date org-log-redeadline
12187 (not (equal old-date
12188 (substring org-last-inserted-timestamp 1 -1))))
12189 (org-add-log-setup 'redeadline nil old-date 'findpos
12190 org-log-redeadline))
12191 (when repeater
12192 (save-excursion
12193 (org-back-to-heading t)
12194 (when (re-search-forward (concat org-deadline-string " "
12195 org-last-inserted-timestamp)
12196 (save-excursion
12197 (outline-next-heading) (point)) t)
12198 (goto-char (1- (match-end 0)))
12199 (insert " " repeater)
12200 (setq org-last-inserted-timestamp
12201 (concat (substring org-last-inserted-timestamp 0 -1)
12202 " " repeater
12203 (substring org-last-inserted-timestamp -1))))))
12204 (message "Deadline on %s" org-last-inserted-timestamp)))))
12206 (defun org-schedule (&optional remove time)
12207 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12208 With argument REMOVE, remove any scheduling date from the item.
12209 With argument TIME, scheduled at the corresponding date. TIME can
12210 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12211 (interactive "P")
12212 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12213 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12214 'region-start-level 'region))
12215 org-loop-over-headlines-in-active-region)
12216 (org-map-entries
12217 `(org-schedule ',remove ,time)
12218 org-loop-over-headlines-in-active-region
12219 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12220 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12221 (repeater (and old-date
12222 (string-match
12223 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12224 old-date)
12225 (match-string 1 old-date))))
12226 (if remove
12227 (progn
12228 (when (and old-date org-log-reschedule)
12229 (org-add-log-setup 'delschedule nil old-date 'findpos
12230 org-log-reschedule))
12231 (org-remove-timestamp-with-keyword org-scheduled-string)
12232 (message "Item is no longer scheduled."))
12233 (org-add-planning-info 'scheduled time 'closed)
12234 (when (and old-date org-log-reschedule
12235 (not (equal old-date
12236 (substring org-last-inserted-timestamp 1 -1))))
12237 (org-add-log-setup 'reschedule nil old-date 'findpos
12238 org-log-reschedule))
12239 (when repeater
12240 (save-excursion
12241 (org-back-to-heading t)
12242 (when (re-search-forward (concat org-scheduled-string " "
12243 org-last-inserted-timestamp)
12244 (save-excursion
12245 (outline-next-heading) (point)) t)
12246 (goto-char (1- (match-end 0)))
12247 (insert " " repeater)
12248 (setq org-last-inserted-timestamp
12249 (concat (substring org-last-inserted-timestamp 0 -1)
12250 " " repeater
12251 (substring org-last-inserted-timestamp -1))))))
12252 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12254 (defun org-get-scheduled-time (pom &optional inherit)
12255 "Get the scheduled time as a time tuple, of a format suitable
12256 for calling org-schedule with, or if there is no scheduling,
12257 returns nil."
12258 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12259 (when time
12260 (apply 'encode-time (org-parse-time-string time)))))
12262 (defun org-get-deadline-time (pom &optional inherit)
12263 "Get the deadline as a time tuple, of a format suitable for
12264 calling org-deadline with, or if there is no scheduling, returns
12265 nil."
12266 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12267 (when time
12268 (apply 'encode-time (org-parse-time-string time)))))
12270 (defun org-remove-timestamp-with-keyword (keyword)
12271 "Remove all time stamps with KEYWORD in the current entry."
12272 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12273 beg)
12274 (save-excursion
12275 (org-back-to-heading t)
12276 (setq beg (point))
12277 (outline-next-heading)
12278 (while (re-search-backward re beg t)
12279 (replace-match "")
12280 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12281 (equal (char-before) ?\ ))
12282 (backward-delete-char 1)
12283 (if (string-match "^[ \t]*$" (buffer-substring
12284 (point-at-bol) (point-at-eol)))
12285 (delete-region (point-at-bol)
12286 (min (point-max) (1+ (point-at-eol))))))))))
12288 (defun org-add-planning-info (what &optional time &rest remove)
12289 "Insert new timestamp with keyword in the line directly after the headline.
12290 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12291 If non is given, the user is prompted for a date.
12292 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12293 be removed."
12294 (interactive)
12295 (let (org-time-was-given org-end-time-was-given ts
12296 end default-time default-input)
12298 (catch 'exit
12299 (when (and (memq what '(scheduled deadline))
12300 (or (not time)
12301 (and (stringp time)
12302 (string-match "^[-+]+[0-9]" time))))
12303 ;; Try to get a default date/time from existing timestamp
12304 (save-excursion
12305 (org-back-to-heading t)
12306 (setq end (save-excursion (outline-next-heading) (point)))
12307 (when (re-search-forward (if (eq what 'scheduled)
12308 org-scheduled-time-regexp
12309 org-deadline-time-regexp)
12310 end t)
12311 (setq ts (match-string 1)
12312 default-time
12313 (apply 'encode-time (org-parse-time-string ts))
12314 default-input (and ts (org-get-compact-tod ts))))))
12315 (when what
12316 (setq time
12317 (if (stringp time)
12318 ;; This is a string (relative or absolute), set proper date
12319 (apply 'encode-time
12320 (org-read-date-analyze
12321 time default-time (decode-time default-time)))
12322 ;; If necessary, get the time from the user
12323 (or time (org-read-date nil 'to-time nil nil
12324 default-time default-input)))))
12326 (when (and org-insert-labeled-timestamps-at-point
12327 (member what '(scheduled deadline)))
12328 (insert
12329 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12330 (org-insert-time-stamp time org-time-was-given
12331 nil nil nil (list org-end-time-was-given))
12332 (setq what nil))
12333 (save-excursion
12334 (save-restriction
12335 (let (col list elt ts buffer-invisibility-spec)
12336 (org-back-to-heading t)
12337 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12338 (goto-char (match-end 1))
12339 (setq col (current-column))
12340 (goto-char (match-end 0))
12341 (if (eobp) (insert "\n") (forward-char 1))
12342 (when (and (not what)
12343 (not (looking-at
12344 (concat "[ \t]*"
12345 org-keyword-time-not-clock-regexp))))
12346 ;; Nothing to add, nothing to remove...... :-)
12347 (throw 'exit nil))
12348 (if (and (not (looking-at org-outline-regexp))
12349 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12350 "[^\r\n]*"))
12351 (not (equal (match-string 1) org-clock-string)))
12352 (narrow-to-region (match-beginning 0) (match-end 0))
12353 (insert-before-markers "\n")
12354 (backward-char 1)
12355 (narrow-to-region (point) (point))
12356 (and org-adapt-indentation (org-indent-to-column col)))
12357 ;; Check if we have to remove something.
12358 (setq list (cons what remove))
12359 (while list
12360 (setq elt (pop list))
12361 (when (or (and (eq elt 'scheduled)
12362 (re-search-forward org-scheduled-time-regexp nil t))
12363 (and (eq elt 'deadline)
12364 (re-search-forward org-deadline-time-regexp nil t))
12365 (and (eq elt 'closed)
12366 (re-search-forward org-closed-time-regexp nil t)))
12367 (replace-match "")
12368 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12369 (and (looking-at "[ \t]+") (replace-match ""))
12370 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12371 (when what
12372 (insert
12373 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12374 (cond ((eq what 'scheduled) org-scheduled-string)
12375 ((eq what 'deadline) org-deadline-string)
12376 ((eq what 'closed) org-closed-string))
12377 " ")
12378 (setq ts (org-insert-time-stamp
12379 time
12380 (or org-time-was-given
12381 (and (eq what 'closed) org-log-done-with-time))
12382 (eq what 'closed)
12383 nil nil (list org-end-time-was-given)))
12384 (insert
12385 (if (not (or (bolp) (eq (char-before) ?\ )
12386 (memq (char-after) '(32 10))
12387 (eobp))) " " ""))
12388 (end-of-line 1))
12389 (goto-char (point-min))
12390 (widen)
12391 (if (and (looking-at "[ \t]*\n")
12392 (equal (char-before) ?\n))
12393 (delete-region (1- (point)) (point-at-eol)))
12394 ts))))))
12396 (defvar org-log-note-marker (make-marker))
12397 (defvar org-log-note-purpose nil)
12398 (defvar org-log-note-state nil)
12399 (defvar org-log-note-previous-state nil)
12400 (defvar org-log-note-how nil)
12401 (defvar org-log-note-extra nil)
12402 (defvar org-log-note-window-configuration nil)
12403 (defvar org-log-note-return-to (make-marker))
12404 (defvar org-log-note-effective-time nil
12405 "Remembered current time so that dynamically scoped
12406 `org-extend-today-until' affects tha timestamps in state change
12407 log")
12409 (defvar org-log-post-message nil
12410 "Message to be displayed after a log note has been stored.
12411 The auto-repeater uses this.")
12413 (defun org-add-note ()
12414 "Add a note to the current entry.
12415 This is done in the same way as adding a state change note."
12416 (interactive)
12417 (org-add-log-setup 'note nil nil 'findpos nil))
12419 (defvar org-property-end-re)
12420 (defun org-add-log-setup (&optional purpose state prev-state
12421 findpos how extra)
12422 "Set up the post command hook to take a note.
12423 If this is about to TODO state change, the new state is expected in STATE.
12424 When FINDPOS is non-nil, find the correct position for the note in
12425 the current entry. If not, assume that it can be inserted at point.
12426 HOW is an indicator what kind of note should be created.
12427 EXTRA is additional text that will be inserted into the notes buffer."
12428 (let* ((org-log-into-drawer (org-log-into-drawer))
12429 (drawer (cond ((stringp org-log-into-drawer)
12430 org-log-into-drawer)
12431 (org-log-into-drawer "LOGBOOK")
12432 (t nil))))
12433 (save-restriction
12434 (save-excursion
12435 (when findpos
12436 (org-back-to-heading t)
12437 (narrow-to-region (point) (save-excursion
12438 (outline-next-heading) (point)))
12439 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12440 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12441 "[^\r\n]*\\)?"))
12442 (goto-char (match-end 0))
12443 (cond
12444 (drawer
12445 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12446 nil t)
12447 (progn
12448 (goto-char (match-end 0))
12449 (or org-log-states-order-reversed
12450 (and (re-search-forward org-property-end-re nil t)
12451 (goto-char (1- (match-beginning 0))))))
12452 (insert "\n:" drawer ":\n:END:")
12453 (beginning-of-line 0)
12454 (org-indent-line)
12455 (beginning-of-line 2)
12456 (org-indent-line)
12457 (end-of-line 0)))
12458 ((and org-log-state-notes-insert-after-drawers
12459 (save-excursion
12460 (forward-line) (looking-at org-drawer-regexp)))
12461 (forward-line)
12462 (while (looking-at org-drawer-regexp)
12463 (goto-char (match-end 0))
12464 (re-search-forward org-property-end-re (point-max) t)
12465 (forward-line))
12466 (forward-line -1)))
12467 (unless org-log-states-order-reversed
12468 (and (= (char-after) ?\n) (forward-char 1))
12469 (org-skip-over-state-notes)
12470 (skip-chars-backward " \t\n\r")))
12471 (move-marker org-log-note-marker (point))
12472 (setq org-log-note-purpose purpose
12473 org-log-note-state state
12474 org-log-note-previous-state prev-state
12475 org-log-note-how how
12476 org-log-note-extra extra
12477 org-log-note-effective-time (org-current-effective-time))
12478 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12480 (defun org-skip-over-state-notes ()
12481 "Skip past the list of State notes in an entry."
12482 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12483 (when (ignore-errors (goto-char (org-in-item-p)))
12484 (let* ((struct (org-list-struct))
12485 (prevs (org-list-prevs-alist struct)))
12486 (while (looking-at "[ \t]*- State")
12487 (goto-char (or (org-list-get-next-item (point) struct prevs)
12488 (org-list-get-item-end (point) struct)))))))
12490 (defun org-add-log-note (&optional purpose)
12491 "Pop up a window for taking a note, and add this note later at point."
12492 (remove-hook 'post-command-hook 'org-add-log-note)
12493 (setq org-log-note-window-configuration (current-window-configuration))
12494 (delete-other-windows)
12495 (move-marker org-log-note-return-to (point))
12496 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12497 (goto-char org-log-note-marker)
12498 (org-switch-to-buffer-other-window "*Org Note*")
12499 (erase-buffer)
12500 (if (memq org-log-note-how '(time state))
12501 (let (current-prefix-arg) (org-store-log-note))
12502 (let ((org-inhibit-startup t)) (org-mode))
12503 (insert (format "# Insert note for %s.
12504 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12505 (cond
12506 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12507 ((eq org-log-note-purpose 'done) "closed todo item")
12508 ((eq org-log-note-purpose 'state)
12509 (format "state change from \"%s\" to \"%s\""
12510 (or org-log-note-previous-state "")
12511 (or org-log-note-state "")))
12512 ((eq org-log-note-purpose 'reschedule)
12513 "rescheduling")
12514 ((eq org-log-note-purpose 'delschedule)
12515 "no longer scheduled")
12516 ((eq org-log-note-purpose 'redeadline)
12517 "changing deadline")
12518 ((eq org-log-note-purpose 'deldeadline)
12519 "removing deadline")
12520 ((eq org-log-note-purpose 'refile)
12521 "refiling")
12522 ((eq org-log-note-purpose 'note)
12523 "this entry")
12524 (t (error "This should not happen")))))
12525 (if org-log-note-extra (insert org-log-note-extra))
12526 (org-set-local 'org-finish-function 'org-store-log-note)
12527 (run-hooks 'org-log-buffer-setup-hook)))
12529 (defvar org-note-abort nil) ; dynamically scoped
12530 (defun org-store-log-note ()
12531 "Finish taking a log note, and insert it to where it belongs."
12532 (let ((txt (buffer-string))
12533 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12534 lines ind bul)
12535 (kill-buffer (current-buffer))
12536 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12537 (setq txt (replace-match "" t t txt)))
12538 (if (string-match "\\s-+\\'" txt)
12539 (setq txt (replace-match "" t t txt)))
12540 (setq lines (org-split-string txt "\n"))
12541 (when (and note (string-match "\\S-" note))
12542 (setq note
12543 (org-replace-escapes
12544 note
12545 (list (cons "%u" (user-login-name))
12546 (cons "%U" user-full-name)
12547 (cons "%t" (format-time-string
12548 (org-time-stamp-format 'long 'inactive)
12549 org-log-note-effective-time))
12550 (cons "%T" (format-time-string
12551 (org-time-stamp-format 'long nil)
12552 org-log-note-effective-time))
12553 (cons "%d" (format-time-string
12554 (org-time-stamp-format nil 'inactive)
12555 org-log-note-effective-time))
12556 (cons "%D" (format-time-string
12557 (org-time-stamp-format nil nil)
12558 org-log-note-effective-time))
12559 (cons "%s" (if org-log-note-state
12560 (concat "\"" org-log-note-state "\"")
12561 ""))
12562 (cons "%S" (if org-log-note-previous-state
12563 (concat "\"" org-log-note-previous-state "\"")
12564 "\"\"")))))
12565 (if lines (setq note (concat note " \\\\")))
12566 (push note lines))
12567 (when (or current-prefix-arg org-note-abort)
12568 (when org-log-into-drawer
12569 (org-remove-empty-drawer-at
12570 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12571 org-log-note-marker))
12572 (setq lines nil))
12573 (when lines
12574 (with-current-buffer (marker-buffer org-log-note-marker)
12575 (save-excursion
12576 (goto-char org-log-note-marker)
12577 (move-marker org-log-note-marker nil)
12578 (end-of-line 1)
12579 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12580 (setq ind (save-excursion
12581 (if (ignore-errors (goto-char (org-in-item-p)))
12582 (let ((struct (org-list-struct)))
12583 (org-list-get-ind
12584 (org-list-get-top-point struct) struct))
12585 (skip-chars-backward " \r\t\n")
12586 (cond
12587 ((and (org-at-heading-p)
12588 org-adapt-indentation)
12589 (1+ (org-current-level)))
12590 ((org-at-heading-p) 0)
12591 (t (org-get-indentation))))))
12592 (setq bul (org-list-bullet-string "-"))
12593 (org-indent-line-to ind)
12594 (insert bul (pop lines))
12595 (let ((ind-body (+ (length bul) ind)))
12596 (while lines
12597 (insert "\n")
12598 (org-indent-line-to ind-body)
12599 (insert (pop lines))))
12600 (message "Note stored")
12601 (org-back-to-heading t)
12602 (org-cycle-hide-drawers 'children)))))
12603 (set-window-configuration org-log-note-window-configuration)
12604 (with-current-buffer (marker-buffer org-log-note-return-to)
12605 (goto-char org-log-note-return-to))
12606 (move-marker org-log-note-return-to nil)
12607 (and org-log-post-message (message "%s" org-log-post-message)))
12609 (defun org-remove-empty-drawer-at (drawer pos)
12610 "Remove an empty drawer DRAWER at position POS.
12611 POS may also be a marker."
12612 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12613 (save-excursion
12614 (save-restriction
12615 (widen)
12616 (goto-char pos)
12617 (if (org-in-regexp
12618 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12619 (replace-match ""))))))
12621 (defvar org-ts-type nil)
12622 (defun org-sparse-tree (&optional arg type)
12623 "Create a sparse tree, prompt for the details.
12624 This command can create sparse trees. You first need to select the type
12625 of match used to create the tree:
12627 t Show all TODO entries.
12628 T Show entries with a specific TODO keyword.
12629 m Show entries selected by a tags/property match.
12630 p Enter a property name and its value (both with completion on existing
12631 names/values) and show entries with that property.
12632 r Show entries matching a regular expression (`/' can be used as well).
12633 b Show deadlines and scheduled items before a date.
12634 a Show deadlines and scheduled items after a date.
12635 d Show deadlines due within `org-deadline-warning-days'.
12636 D Show deadlines and scheduled items between a date range."
12637 (interactive "P")
12638 (let (ans kwd value ts-type)
12639 (setq type (or type org-sparse-tree-default-date-type))
12640 (setq org-ts-type type)
12641 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12642 (cond ((eq type 'all) "all timestamps")
12643 ((eq type 'scheduled) "only scheduled")
12644 ((eq type 'deadline) "only deadline")
12645 ((eq type 'active) "only active timestamps")
12646 ((eq type 'inactive) "only inactive timestamps")
12647 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12648 (t "scheduled/deadline")))
12649 (setq ans (read-char-exclusive))
12650 (cond
12651 ((equal ans ?c)
12652 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12653 ((equal ans ?d)
12654 (call-interactively 'org-check-deadlines))
12655 ((equal ans ?b)
12656 (call-interactively 'org-check-before-date))
12657 ((equal ans ?a)
12658 (call-interactively 'org-check-after-date))
12659 ((equal ans ?D)
12660 (call-interactively 'org-check-dates-range))
12661 ((equal ans ?t)
12662 (org-show-todo-tree nil))
12663 ((equal ans ?T)
12664 (org-show-todo-tree '(4)))
12665 ((member ans '(?T ?m))
12666 (call-interactively 'org-match-sparse-tree))
12667 ((member ans '(?p ?P))
12668 (setq kwd (org-icompleting-read "Property: "
12669 (mapcar 'list (org-buffer-property-keys))))
12670 (setq value (org-icompleting-read "Value: "
12671 (mapcar 'list (org-property-values kwd))))
12672 (unless (string-match "\\`{.*}\\'" value)
12673 (setq value (concat "\"" value "\"")))
12674 (org-match-sparse-tree arg (concat kwd "=" value)))
12675 ((member ans '(?r ?R ?/))
12676 (call-interactively 'org-occur))
12677 (t (error "No such sparse tree command \"%c\"" ans)))))
12679 (defvar org-occur-highlights nil
12680 "List of overlays used for occur matches.")
12681 (make-variable-buffer-local 'org-occur-highlights)
12682 (defvar org-occur-parameters nil
12683 "Parameters of the active org-occur calls.
12684 This is a list, each call to org-occur pushes as cons cell,
12685 containing the regular expression and the callback, onto the list.
12686 The list can contain several entries if `org-occur' has been called
12687 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12688 will only contain one set of parameters. When the highlights are
12689 removed (for example with `C-c C-c', or with the next edit (depending
12690 on `org-remove-highlights-with-change'), this variable is emptied
12691 as well.")
12692 (make-variable-buffer-local 'org-occur-parameters)
12694 (defun org-occur (regexp &optional keep-previous callback)
12695 "Make a compact tree which shows all matches of REGEXP.
12696 The tree will show the lines where the regexp matches, and all higher
12697 headlines above the match. It will also show the heading after the match,
12698 to make sure editing the matching entry is easy.
12699 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12700 call to `org-occur' will be kept, to allow stacking of calls to this
12701 command.
12702 If CALLBACK is non-nil, it is a function which is called to confirm
12703 that the match should indeed be shown."
12704 (interactive "sRegexp: \nP")
12705 (when (equal regexp "")
12706 (error "Regexp cannot be empty"))
12707 (unless keep-previous
12708 (org-remove-occur-highlights nil nil t))
12709 (push (cons regexp callback) org-occur-parameters)
12710 (let ((cnt 0))
12711 (save-excursion
12712 (goto-char (point-min))
12713 (if (or (not keep-previous) ; do not want to keep
12714 (not org-occur-highlights)) ; no previous matches
12715 ;; hide everything
12716 (org-overview))
12717 (while (re-search-forward regexp nil t)
12718 (when (or (not callback)
12719 (save-match-data (funcall callback)))
12720 (setq cnt (1+ cnt))
12721 (when org-highlight-sparse-tree-matches
12722 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12723 (org-show-context 'occur-tree))))
12724 (when org-remove-highlights-with-change
12725 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12726 nil 'local))
12727 (unless org-sparse-tree-open-archived-trees
12728 (org-hide-archived-subtrees (point-min) (point-max)))
12729 (run-hooks 'org-occur-hook)
12730 (if (org-called-interactively-p 'interactive)
12731 (message "%d match(es) for regexp %s" cnt regexp))
12732 cnt))
12734 (defun org-occur-next-match (&optional n reset)
12735 "Function for `next-error-function' to find sparse tree matches.
12736 N is the number of matches to move, when negative move backwards.
12737 RESET is entirely ignored - this function always goes back to the
12738 starting point when no match is found."
12739 (let* ((limit (if (< n 0) (point-min) (point-max)))
12740 (search-func (if (< n 0)
12741 'previous-single-char-property-change
12742 'next-single-char-property-change))
12743 (n (abs n))
12744 (pos (point))
12746 (catch 'exit
12747 (while (setq p1 (funcall search-func (point) 'org-type))
12748 (when (equal p1 limit)
12749 (goto-char pos)
12750 (error "No more matches"))
12751 (when (equal (get-char-property p1 'org-type) 'org-occur)
12752 (setq n (1- n))
12753 (when (= n 0)
12754 (goto-char p1)
12755 (throw 'exit (point))))
12756 (goto-char p1))
12757 (goto-char p1)
12758 (error "No more matches"))))
12760 (defun org-show-context (&optional key)
12761 "Make sure point and context are visible.
12762 How much context is shown depends upon the variables
12763 `org-show-hierarchy-above', `org-show-following-heading',
12764 `org-show-entry-below' and `org-show-siblings'."
12765 (let ((heading-p (org-at-heading-p t))
12766 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12767 (following-p (org-get-alist-option org-show-following-heading key))
12768 (entry-p (org-get-alist-option org-show-entry-below key))
12769 (siblings-p (org-get-alist-option org-show-siblings key)))
12770 (catch 'exit
12771 ;; Show heading or entry text
12772 (if (and heading-p (not entry-p))
12773 (org-flag-heading nil) ; only show the heading
12774 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12775 (org-show-hidden-entry))) ; show entire entry
12776 (when following-p
12777 ;; Show next sibling, or heading below text
12778 (save-excursion
12779 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12780 (org-flag-heading nil))))
12781 (when siblings-p (org-show-siblings))
12782 (when hierarchy-p
12783 ;; show all higher headings, possibly with siblings
12784 (save-excursion
12785 (while (and (condition-case nil
12786 (progn (org-up-heading-all 1) t)
12787 (error nil))
12788 (not (bobp)))
12789 (org-flag-heading nil)
12790 (when siblings-p (org-show-siblings))))))))
12792 (defvar org-reveal-start-hook nil
12793 "Hook run before revealing a location.")
12795 (defun org-reveal (&optional siblings)
12796 "Show current entry, hierarchy above it, and the following headline.
12797 This can be used to show a consistent set of context around locations
12798 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12799 not t for the search context.
12801 With optional argument SIBLINGS, on each level of the hierarchy all
12802 siblings are shown. This repairs the tree structure to what it would
12803 look like when opened with hierarchical calls to `org-cycle'.
12804 With double optional argument \\[universal-argument] \\[universal-argument], \
12805 go to the parent and show the
12806 entire tree."
12807 (interactive "P")
12808 (run-hooks 'org-reveal-start-hook)
12809 (let ((org-show-hierarchy-above t)
12810 (org-show-following-heading t)
12811 (org-show-siblings (if siblings t org-show-siblings)))
12812 (org-show-context nil))
12813 (when (equal siblings '(16))
12814 (save-excursion
12815 (when (org-up-heading-safe)
12816 (org-show-subtree)
12817 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12819 (defun org-highlight-new-match (beg end)
12820 "Highlight from BEG to END and mark the highlight is an occur headline."
12821 (let ((ov (make-overlay beg end)))
12822 (overlay-put ov 'face 'secondary-selection)
12823 (overlay-put ov 'org-type 'org-occur)
12824 (push ov org-occur-highlights)))
12826 (defun org-remove-occur-highlights (&optional beg end noremove)
12827 "Remove the occur highlights from the buffer.
12828 BEG and END are ignored. If NOREMOVE is nil, remove this function
12829 from the `before-change-functions' in the current buffer."
12830 (interactive)
12831 (unless org-inhibit-highlight-removal
12832 (mapc 'delete-overlay org-occur-highlights)
12833 (setq org-occur-highlights nil)
12834 (setq org-occur-parameters nil)
12835 (unless noremove
12836 (remove-hook 'before-change-functions
12837 'org-remove-occur-highlights 'local))))
12839 ;;;; Priorities
12841 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12842 "Regular expression matching the priority indicator.")
12844 (defvar org-remove-priority-next-time nil)
12846 (defun org-priority-up ()
12847 "Increase the priority of the current item."
12848 (interactive)
12849 (org-priority 'up))
12851 (defun org-priority-down ()
12852 "Decrease the priority of the current item."
12853 (interactive)
12854 (org-priority 'down))
12856 (defun org-priority (&optional action)
12857 "Change the priority of an item by ARG.
12858 ACTION can be `set', `up', `down', or a character."
12859 (interactive)
12860 (unless org-enable-priority-commands
12861 (error "Priority commands are disabled"))
12862 (setq action (or action 'set))
12863 (let (current new news have remove)
12864 (save-excursion
12865 (org-back-to-heading t)
12866 (if (looking-at org-priority-regexp)
12867 (setq current (string-to-char (match-string 2))
12868 have t))
12869 (cond
12870 ((eq action 'remove)
12871 (setq remove t new ?\ ))
12872 ((or (eq action 'set)
12873 (if (featurep 'xemacs) (characterp action) (integerp action)))
12874 (if (not (eq action 'set))
12875 (setq new action)
12876 (message "Priority %c-%c, SPC to remove: "
12877 org-highest-priority org-lowest-priority)
12878 (save-match-data
12879 (setq new (read-char-exclusive))))
12880 (if (and (= (upcase org-highest-priority) org-highest-priority)
12881 (= (upcase org-lowest-priority) org-lowest-priority))
12882 (setq new (upcase new)))
12883 (cond ((equal new ?\ ) (setq remove t))
12884 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12885 (error "Priority must be between `%c' and `%c'"
12886 org-highest-priority org-lowest-priority))))
12887 ((eq action 'up)
12888 (setq new (if have
12889 (1- current) ; normal cycling
12890 ;; last priority was empty
12891 (if (eq last-command this-command)
12892 org-lowest-priority ; wrap around empty to lowest
12893 ;; default
12894 (if org-priority-start-cycle-with-default
12895 org-default-priority
12896 (1- org-default-priority))))))
12897 ((eq action 'down)
12898 (setq new (if have
12899 (1+ current) ; normal cycling
12900 ;; last priority was empty
12901 (if (eq last-command this-command)
12902 org-highest-priority ; wrap around empty to highest
12903 ;; default
12904 (if org-priority-start-cycle-with-default
12905 org-default-priority
12906 (1+ org-default-priority))))))
12907 (t (error "Invalid action")))
12908 (if (or (< (upcase new) org-highest-priority)
12909 (> (upcase new) org-lowest-priority))
12910 (if (and (memq action '(up down))
12911 (not have) (not (eq last-command this-command)))
12912 ;; `new' is from default priority
12913 (error
12914 "The default can not be set, see `org-default-priority' why")
12915 ;; normal cycling: `new' is beyond highest/lowest priority
12916 ;; and is wrapped around to the empty priority
12917 (setq remove t)))
12918 (setq news (format "%c" new))
12919 (if have
12920 (if remove
12921 (replace-match "" t t nil 1)
12922 (replace-match news t t nil 2))
12923 (if remove
12924 (error "No priority cookie found in line")
12925 (let ((case-fold-search nil))
12926 (looking-at org-todo-line-regexp))
12927 (if (match-end 2)
12928 (progn
12929 (goto-char (match-end 2))
12930 (insert " [#" news "]"))
12931 (goto-char (match-beginning 3))
12932 (insert "[#" news "] "))))
12933 (org-preserve-lc (org-set-tags nil 'align)))
12934 (if remove
12935 (message "Priority removed")
12936 (message "Priority of current item set to %s" news))))
12938 (defun org-get-priority (s)
12939 "Find priority cookie and return priority."
12940 (if (functionp org-get-priority-function)
12941 (funcall org-get-priority-function)
12942 (save-match-data
12943 (if (not (string-match org-priority-regexp s))
12944 (* 1000 (- org-lowest-priority org-default-priority))
12945 (* 1000 (- org-lowest-priority
12946 (string-to-char (match-string 2 s))))))))
12948 ;;;; Tags
12950 (defvar org-agenda-archives-mode)
12951 (defvar org-map-continue-from nil
12952 "Position from where mapping should continue.
12953 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12955 (defvar org-scanner-tags nil
12956 "The current tag list while the tags scanner is running.")
12957 (defvar org-trust-scanner-tags nil
12958 "Should `org-get-tags-at' use the tags for the scanner.
12959 This is for internal dynamical scoping only.
12960 When this is non-nil, the function `org-get-tags-at' will return the value
12961 of `org-scanner-tags' instead of building the list by itself. This
12962 can lead to large speed-ups when the tags scanner is used in a file with
12963 many entries, and when the list of tags is retrieved, for example to
12964 obtain a list of properties. Building the tags list for each entry in such
12965 a file becomes an N^2 operation - but with this variable set, it scales
12966 as N.")
12968 (defun org-scan-tags (action matcher todo-only &optional start-level)
12969 "Scan headline tags with inheritance and produce output ACTION.
12971 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12972 or `agenda' to produce an entry list for an agenda view. It can also be
12973 a Lisp form or a function that should be called at each matched headline, in
12974 this case the return value is a list of all return values from these calls.
12976 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12977 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12978 only lines with a not-done TODO keyword are included in the output.
12979 This should be the same variable that was scoped into
12980 and set by `org-make-tags-matcher' when it constructed MATCHER.
12982 START-LEVEL can be a string with asterisks, reducing the scope to
12983 headlines matching this string."
12984 (require 'org-agenda)
12985 (let* ((re (concat "^"
12986 (if start-level
12987 ;; Get the correct level to match
12988 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12989 org-outline-regexp)
12990 " *\\(\\<\\("
12991 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12992 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12993 (props (list 'face 'default
12994 'done-face 'org-agenda-done
12995 'undone-face 'default
12996 'mouse-face 'highlight
12997 'org-not-done-regexp org-not-done-regexp
12998 'org-todo-regexp org-todo-regexp
12999 'org-complex-heading-regexp org-complex-heading-regexp
13000 'help-echo
13001 (format "mouse-2 or RET jump to org file %s"
13002 (abbreviate-file-name
13003 (or (buffer-file-name (buffer-base-buffer))
13004 (buffer-name (buffer-base-buffer)))))))
13005 (case-fold-search nil)
13006 (org-map-continue-from nil)
13007 lspos tags tags-list
13008 (tags-alist (list (cons 0 org-file-tags)))
13009 (llast 0) rtn rtn1 level category i txt
13010 todo marker entry priority)
13011 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13012 (setq action (list 'lambda nil action)))
13013 (save-excursion
13014 (goto-char (point-min))
13015 (when (eq action 'sparse-tree)
13016 (org-overview)
13017 (org-remove-occur-highlights))
13018 (while (re-search-forward re nil t)
13019 (setq org-map-continue-from nil)
13020 (catch :skip
13021 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13022 tags (if (match-end 4) (org-match-string-no-properties 4)))
13023 (goto-char (setq lspos (match-beginning 0)))
13024 (setq level (org-reduced-level (funcall outline-level))
13025 category (org-get-category))
13026 (setq i llast llast level)
13027 ;; remove tag lists from same and sublevels
13028 (while (>= i level)
13029 (when (setq entry (assoc i tags-alist))
13030 (setq tags-alist (delete entry tags-alist)))
13031 (setq i (1- i)))
13032 ;; add the next tags
13033 (when tags
13034 (setq tags (org-split-string tags ":")
13035 tags-alist
13036 (cons (cons level tags) tags-alist)))
13037 ;; compile tags for current headline
13038 (setq tags-list
13039 (if org-use-tag-inheritance
13040 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13041 tags)
13042 org-scanner-tags tags-list)
13043 (when org-use-tag-inheritance
13044 (setcdr (car tags-alist)
13045 (mapcar (lambda (x)
13046 (setq x (copy-sequence x))
13047 (org-add-prop-inherited x))
13048 (cdar tags-alist))))
13049 (when (and tags org-use-tag-inheritance
13050 (or (not (eq t org-use-tag-inheritance))
13051 org-tags-exclude-from-inheritance))
13052 ;; selective inheritance, remove uninherited ones
13053 (setcdr (car tags-alist)
13054 (org-remove-uninherited-tags (cdar tags-alist))))
13055 (when (and
13057 ;; eval matcher only when the todo condition is OK
13058 (and (or (not todo-only) (member todo org-not-done-keywords))
13059 (let ((case-fold-search t) (org-trust-scanner-tags t))
13060 (eval matcher)))
13062 ;; Call the skipper, but return t if it does not skip,
13063 ;; so that the `and' form continues evaluating
13064 (progn
13065 (unless (eq action 'sparse-tree) (org-agenda-skip))
13068 ;; Check if timestamps are deselecting this entry
13069 (or (not todo-only)
13070 (and (member todo org-not-done-keywords)
13071 (or (not org-agenda-tags-todo-honor-ignore-options)
13072 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13074 ;; Extra check for the archive tag
13075 ;; FIXME: Does the skipper already do this????
13077 (not (member org-archive-tag tags-list))
13078 ;; we have an archive tag, should we use this anyway?
13079 (or (not org-agenda-skip-archived-trees)
13080 (and (eq action 'agenda) org-agenda-archives-mode))))
13082 ;; select this headline
13084 (cond
13085 ((eq action 'sparse-tree)
13086 (and org-highlight-sparse-tree-matches
13087 (org-get-heading) (match-end 0)
13088 (org-highlight-new-match
13089 (match-beginning 1) (match-end 1)))
13090 (org-show-context 'tags-tree))
13091 ((eq action 'agenda)
13092 (setq txt (org-agenda-format-item
13094 (concat
13095 (if (eq org-tags-match-list-sublevels 'indented)
13096 (make-string (1- level) ?.) "")
13097 (org-get-heading))
13098 category
13099 tags-list)
13100 priority (org-get-priority txt))
13101 (goto-char lspos)
13102 (setq marker (org-agenda-new-marker))
13103 (org-add-props txt props
13104 'org-marker marker 'org-hd-marker marker 'org-category category
13105 'todo-state todo
13106 'priority priority 'type "tagsmatch")
13107 (push txt rtn))
13108 ((functionp action)
13109 (setq org-map-continue-from nil)
13110 (save-excursion
13111 (setq rtn1 (funcall action))
13112 (push rtn1 rtn)))
13113 (t (error "Invalid action")))
13115 ;; if we are to skip sublevels, jump to end of subtree
13116 (unless org-tags-match-list-sublevels
13117 (org-end-of-subtree t)
13118 (backward-char 1))))
13119 ;; Get the correct position from where to continue
13120 (if org-map-continue-from
13121 (goto-char org-map-continue-from)
13122 (and (= (point) lspos) (end-of-line 1)))))
13123 (when (and (eq action 'sparse-tree)
13124 (not org-sparse-tree-open-archived-trees))
13125 (org-hide-archived-subtrees (point-min) (point-max)))
13126 (nreverse rtn)))
13128 (defun org-remove-uninherited-tags (tags)
13129 "Remove all tags that are not inherited from the list TAGS."
13130 (cond
13131 ((eq org-use-tag-inheritance t)
13132 (if org-tags-exclude-from-inheritance
13133 (org-delete-all org-tags-exclude-from-inheritance tags)
13134 tags))
13135 ((not org-use-tag-inheritance) nil)
13136 ((stringp org-use-tag-inheritance)
13137 (delq nil (mapcar
13138 (lambda (x)
13139 (if (and (string-match org-use-tag-inheritance x)
13140 (not (member x org-tags-exclude-from-inheritance)))
13141 x nil))
13142 tags)))
13143 ((listp org-use-tag-inheritance)
13144 (delq nil (mapcar
13145 (lambda (x)
13146 (if (member x org-use-tag-inheritance) x nil))
13147 tags)))))
13149 (defun org-match-sparse-tree (&optional todo-only match)
13150 "Create a sparse tree according to tags string MATCH.
13151 MATCH can contain positive and negative selection of tags, like
13152 \"+WORK+URGENT-WITHBOSS\".
13153 If optional argument TODO-ONLY is non-nil, only select lines that are
13154 also TODO lines."
13155 (interactive "P")
13156 (org-prepare-agenda-buffers (list (current-buffer)))
13157 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13159 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13161 (defvar org-cached-props nil)
13162 (defun org-cached-entry-get (pom property)
13163 (if (or (eq t org-use-property-inheritance)
13164 (and (stringp org-use-property-inheritance)
13165 (string-match org-use-property-inheritance property))
13166 (and (listp org-use-property-inheritance)
13167 (member property org-use-property-inheritance)))
13168 ;; Caching is not possible, check it directly
13169 (org-entry-get pom property 'inherit)
13170 ;; Get all properties, so that we can do complicated checks easily
13171 (cdr (assoc property (or org-cached-props
13172 (setq org-cached-props
13173 (org-entry-properties pom)))))))
13175 (defun org-global-tags-completion-table (&optional files)
13176 "Return the list of all tags in all agenda buffer/files.
13177 Optional FILES argument is a list of files to which can be used
13178 instead of the agenda files."
13179 (save-excursion
13180 (org-uniquify
13181 (delq nil
13182 (apply 'append
13183 (mapcar
13184 (lambda (file)
13185 (set-buffer (find-file-noselect file))
13186 (append (org-get-buffer-tags)
13187 (mapcar (lambda (x) (if (stringp (car-safe x))
13188 (list (car-safe x)) nil))
13189 org-tag-alist)))
13190 (if (and files (car files))
13191 files
13192 (org-agenda-files))))))))
13194 (defun org-make-tags-matcher (match)
13195 "Create the TAGS/TODO matcher form for the selection string MATCH.
13197 The variable `todo-only' is scoped dynamically into this function; it will be
13198 set to t if the matcher restricts matching to TODO entries,
13199 otherwise will not be touched.
13201 Returns a cons of the selection string MATCH and the constructed
13202 lisp form implementing the matcher. The matcher is to be
13203 evaluated at an Org entry, with point on the headline,
13204 and returns t if the entry matches the
13205 selection string MATCH. The returned lisp form references
13206 two variables with information about the entry, which must be
13207 bound around the form's evaluation: todo, the TODO keyword at the
13208 entry (or nil of none); and tags-list, the list of all tags at the
13209 entry including inherited ones. Additionally, the category
13210 of the entry (if any) must be specified as the text property
13211 'org-category on the headline.
13213 See also `org-scan-tags'.
13215 (declare (special todo-only))
13216 (unless (boundp 'todo-only)
13217 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13218 (unless match
13219 ;; Get a new match request, with completion
13220 (let ((org-last-tags-completion-table
13221 (org-global-tags-completion-table)))
13222 (setq match (org-completing-read-no-i
13223 "Match: " 'org-tags-completion-function nil nil nil
13224 'org-tags-history))))
13226 ;; Parse the string and create a lisp form
13227 (let ((match0 match)
13228 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13229 minus tag mm
13230 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13231 orterms term orlist re-p str-p level-p level-op time-p
13232 prop-p pn pv po gv rest)
13233 (if (string-match "/+" match)
13234 ;; match contains also a todo-matching request
13235 (progn
13236 (setq tagsmatch (substring match 0 (match-beginning 0))
13237 todomatch (substring match (match-end 0)))
13238 (if (string-match "^!" todomatch)
13239 (setq todo-only t todomatch (substring todomatch 1)))
13240 (if (string-match "^\\s-*$" todomatch)
13241 (setq todomatch nil)))
13242 ;; only matching tags
13243 (setq tagsmatch match todomatch nil))
13245 ;; Make the tags matcher
13246 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13247 (setq tagsmatcher t)
13248 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13249 (while (setq term (pop orterms))
13250 (while (and (equal (substring term -1) "\\") orterms)
13251 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13252 (while (string-match re term)
13253 (setq rest (substring term (match-end 0))
13254 minus (and (match-end 1)
13255 (equal (match-string 1 term) "-"))
13256 tag (save-match-data (replace-regexp-in-string
13257 "\\\\-" "-"
13258 (match-string 2 term)))
13259 re-p (equal (string-to-char tag) ?{)
13260 level-p (match-end 4)
13261 prop-p (match-end 5)
13262 mm (cond
13263 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13264 (level-p
13265 (setq level-op (org-op-to-function (match-string 3 term)))
13266 `(,level-op level ,(string-to-number
13267 (match-string 4 term))))
13268 (prop-p
13269 (setq pn (match-string 5 term)
13270 po (match-string 6 term)
13271 pv (match-string 7 term)
13272 re-p (equal (string-to-char pv) ?{)
13273 str-p (equal (string-to-char pv) ?\")
13274 time-p (save-match-data
13275 (string-match "^\"[[<].*[]>]\"$" pv))
13276 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13277 (if time-p (setq pv (org-matcher-time pv)))
13278 (setq po (org-op-to-function po (if time-p 'time str-p)))
13279 (cond
13280 ((equal pn "CATEGORY")
13281 (setq gv '(get-text-property (point) 'org-category)))
13282 ((equal pn "TODO")
13283 (setq gv 'todo))
13285 (setq gv `(org-cached-entry-get nil ,pn))))
13286 (if re-p
13287 (if (eq po 'org<>)
13288 `(not (string-match ,pv (or ,gv "")))
13289 `(string-match ,pv (or ,gv "")))
13290 (if str-p
13291 `(,po (or ,gv "") ,pv)
13292 `(,po (string-to-number (or ,gv ""))
13293 ,(string-to-number pv) ))))
13294 (t `(member ,tag tags-list)))
13295 mm (if minus (list 'not mm) mm)
13296 term rest)
13297 (push mm tagsmatcher))
13298 (push (if (> (length tagsmatcher) 1)
13299 (cons 'and tagsmatcher)
13300 (car tagsmatcher))
13301 orlist)
13302 (setq tagsmatcher nil))
13303 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13304 (setq tagsmatcher
13305 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13306 ;; Make the todo matcher
13307 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13308 (setq todomatcher t)
13309 (setq orterms (org-split-string todomatch "|") orlist nil)
13310 (while (setq term (pop orterms))
13311 (while (string-match re term)
13312 (setq minus (and (match-end 1)
13313 (equal (match-string 1 term) "-"))
13314 kwd (match-string 2 term)
13315 re-p (equal (string-to-char kwd) ?{)
13316 term (substring term (match-end 0))
13317 mm (if re-p
13318 `(string-match ,(substring kwd 1 -1) todo)
13319 (list 'equal 'todo kwd))
13320 mm (if minus (list 'not mm) mm))
13321 (push mm todomatcher))
13322 (push (if (> (length todomatcher) 1)
13323 (cons 'and todomatcher)
13324 (car todomatcher))
13325 orlist)
13326 (setq todomatcher nil))
13327 (setq todomatcher (if (> (length orlist) 1)
13328 (cons 'or orlist) (car orlist))))
13330 ;; Return the string and lisp forms of the matcher
13331 (setq matcher (if todomatcher
13332 (list 'and tagsmatcher todomatcher)
13333 tagsmatcher))
13334 (when todo-only
13335 (setq matcher (list 'and '(member todo org-not-done-keywords)
13336 matcher)))
13337 (cons match0 matcher)))
13339 (defun org-op-to-function (op &optional stringp)
13340 "Turn an operator into the appropriate function."
13341 (setq op
13342 (cond
13343 ((equal op "<" ) '(< string< org-time<))
13344 ((equal op ">" ) '(> org-string> org-time>))
13345 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13346 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13347 ((member op '("=" "==")) '(= string= org-time=))
13348 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13349 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13351 (defun org<> (a b) (not (= a b)))
13352 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13353 (defun org-string>= (a b) (not (string< a b)))
13354 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13355 (defun org-string<> (a b) (not (string= a b)))
13356 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13357 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13358 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13359 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13360 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13361 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13362 (defun org-2ft (s)
13363 "Convert S to a floating point time.
13364 If S is already a number, just return it. If it is a string, parse
13365 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13366 (cond
13367 ((numberp s) s)
13368 ((stringp s)
13369 (condition-case nil
13370 (float-time (apply 'encode-time (org-parse-time-string s)))
13371 (error 0.)))
13372 (t 0.)))
13374 (defun org-time-today ()
13375 "Time in seconds today at 0:00.
13376 Returns the float number of seconds since the beginning of the
13377 epoch to the beginning of today (00:00)."
13378 (float-time (apply 'encode-time
13379 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13381 (defun org-matcher-time (s)
13382 "Interpret a time comparison value."
13383 (save-match-data
13384 (cond
13385 ((string= s "<now>") (float-time))
13386 ((string= s "<today>") (org-time-today))
13387 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13388 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13389 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13390 (+ (org-time-today)
13391 (* (string-to-number (match-string 1 s))
13392 (cdr (assoc (match-string 2 s)
13393 '(("d" . 86400.0) ("w" . 604800.0)
13394 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13395 (t (org-2ft s)))))
13397 (defun org-match-any-p (re list)
13398 "Does re match any element of list?"
13399 (setq list (mapcar (lambda (x) (string-match re x)) list))
13400 (delq nil list))
13402 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13403 (defvar org-tags-overlay (make-overlay 1 1))
13404 (org-detach-overlay org-tags-overlay)
13406 (defun org-get-local-tags-at (&optional pos)
13407 "Get a list of tags defined in the current headline."
13408 (org-get-tags-at pos 'local))
13410 (defun org-get-local-tags ()
13411 "Get a list of tags defined in the current headline."
13412 (org-get-tags-at nil 'local))
13414 (defun org-get-tags-at (&optional pos local)
13415 "Get a list of all headline tags applicable at POS.
13416 POS defaults to point. If tags are inherited, the list contains
13417 the targets in the same sequence as the headlines appear, i.e.
13418 the tags of the current headline come last.
13419 When LOCAL is non-nil, only return tags from the current headline,
13420 ignore inherited ones."
13421 (interactive)
13422 (if (and org-trust-scanner-tags
13423 (or (not pos) (equal pos (point)))
13424 (not local))
13425 org-scanner-tags
13426 (let (tags ltags lastpos parent)
13427 (save-excursion
13428 (save-restriction
13429 (widen)
13430 (goto-char (or pos (point)))
13431 (save-match-data
13432 (catch 'done
13433 (condition-case nil
13434 (progn
13435 (org-back-to-heading t)
13436 (while (not (equal lastpos (point)))
13437 (setq lastpos (point))
13438 (when (looking-at
13439 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13440 (setq ltags (org-split-string
13441 (org-match-string-no-properties 1) ":"))
13442 (when parent
13443 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13444 (setq tags (append
13445 (if parent
13446 (org-remove-uninherited-tags ltags)
13447 ltags)
13448 tags)))
13449 (or org-use-tag-inheritance (throw 'done t))
13450 (if local (throw 'done t))
13451 (or (org-up-heading-safe) (error nil))
13452 (setq parent t)))
13453 (error nil)))))
13454 (if local
13455 tags
13456 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13458 (defun org-add-prop-inherited (s)
13459 (add-text-properties 0 (length s) '(inherited t) s)
13462 (defun org-toggle-tag (tag &optional onoff)
13463 "Toggle the tag TAG for the current line.
13464 If ONOFF is `on' or `off', don't toggle but set to this state."
13465 (let (res current)
13466 (save-excursion
13467 (org-back-to-heading t)
13468 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13469 (point-at-eol) t)
13470 (progn
13471 (setq current (match-string 1))
13472 (replace-match ""))
13473 (setq current ""))
13474 (setq current (nreverse (org-split-string current ":")))
13475 (cond
13476 ((eq onoff 'on)
13477 (setq res t)
13478 (or (member tag current) (push tag current)))
13479 ((eq onoff 'off)
13480 (or (not (member tag current)) (setq current (delete tag current))))
13481 (t (if (member tag current)
13482 (setq current (delete tag current))
13483 (setq res t)
13484 (push tag current))))
13485 (end-of-line 1)
13486 (if current
13487 (progn
13488 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13489 (org-set-tags nil t))
13490 (delete-horizontal-space))
13491 (run-hooks 'org-after-tags-change-hook))
13492 res))
13494 (defun org-align-tags-here (to-col)
13495 ;; Assumes that this is a headline
13496 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13497 (beginning-of-line 1)
13498 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13499 (< pos (match-beginning 2)))
13500 (progn
13501 (setq tags-l (- (match-end 2) (match-beginning 2)))
13502 (goto-char (match-beginning 1))
13503 (insert " ")
13504 (delete-region (point) (1+ (match-beginning 2)))
13505 (setq ncol (max (current-column)
13506 (1+ col)
13507 (if (> to-col 0)
13508 to-col
13509 (- (abs to-col) tags-l))))
13510 (setq p (point))
13511 (insert (make-string (- ncol (current-column)) ?\ ))
13512 (setq ncol (current-column))
13513 (when indent-tabs-mode (tabify p (point-at-eol)))
13514 (org-move-to-column (min ncol col) t))
13515 (goto-char pos))))
13517 (defun org-set-tags-command (&optional arg just-align)
13518 "Call the set-tags command for the current entry."
13519 (interactive "P")
13520 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13521 (org-set-tags arg just-align)
13522 (save-excursion
13523 (org-back-to-heading t)
13524 (org-set-tags arg just-align))))
13526 (defun org-set-tags-to (data)
13527 "Set the tags of the current entry to DATA, replacing the current tags.
13528 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13529 If DATA is nil or the empty string, any tags will be removed."
13530 (interactive "sTags: ")
13531 (setq data
13532 (cond
13533 ((eq data nil) "")
13534 ((equal data "") "")
13535 ((stringp data)
13536 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13537 ":"))
13538 ((listp data)
13539 (concat ":" (mapconcat 'identity data ":") ":"))
13540 (t nil)))
13541 (when data
13542 (save-excursion
13543 (org-back-to-heading t)
13544 (when (looking-at org-complex-heading-regexp)
13545 (if (match-end 5)
13546 (progn
13547 (goto-char (match-beginning 5))
13548 (insert data)
13549 (delete-region (point) (point-at-eol))
13550 (org-set-tags nil 'align))
13551 (goto-char (point-at-eol))
13552 (insert " " data)
13553 (org-set-tags nil 'align)))
13554 (beginning-of-line 1)
13555 (if (looking-at ".*?\\([ \t]+\\)$")
13556 (delete-region (match-beginning 1) (match-end 1))))))
13558 (defun org-align-all-tags ()
13559 "Align the tags i all headings."
13560 (interactive)
13561 (save-excursion
13562 (or (ignore-errors (org-back-to-heading t))
13563 (outline-next-heading))
13564 (if (org-at-heading-p)
13565 (org-set-tags t)
13566 (message "No headings"))))
13568 (defvar org-indent-indentation-per-level)
13569 (defun org-set-tags (&optional arg just-align)
13570 "Set the tags for the current headline.
13571 With prefix ARG, realign all tags in headings in the current buffer."
13572 (interactive "P")
13573 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13574 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13575 'region-start-level 'region))
13576 org-loop-over-headlines-in-active-region)
13577 (org-map-entries
13578 ;; We don't use ARG and JUST-ALIGN here these args are not
13579 ;; useful when looping over headlines
13580 `(org-set-tags)
13581 org-loop-over-headlines-in-active-region
13582 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13583 (let* ((re org-outline-regexp-bol)
13584 (current (unless arg (org-get-tags-string)))
13585 (col (current-column))
13586 (org-setting-tags t)
13587 table current-tags inherited-tags ; computed below when needed
13588 tags p0 c0 c1 rpl di tc level)
13589 (if arg
13590 (save-excursion
13591 (goto-char (point-min))
13592 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13593 (while (re-search-forward re nil t)
13594 (org-set-tags nil t)
13595 (end-of-line 1)))
13596 (message "All tags realigned to column %d" org-tags-column))
13597 (if just-align
13598 (setq tags current)
13599 ;; Get a new set of tags from the user
13600 (save-excursion
13601 (setq table (append org-tag-persistent-alist
13602 (or org-tag-alist (org-get-buffer-tags))
13603 (and
13604 org-complete-tags-always-offer-all-agenda-tags
13605 (org-global-tags-completion-table
13606 (org-agenda-files))))
13607 org-last-tags-completion-table table
13608 current-tags (org-split-string current ":")
13609 inherited-tags (nreverse
13610 (nthcdr (length current-tags)
13611 (nreverse (org-get-tags-at))))
13612 tags
13613 (if (or (eq t org-use-fast-tag-selection)
13614 (and org-use-fast-tag-selection
13615 (delq nil (mapcar 'cdr table))))
13616 (org-fast-tag-selection
13617 current-tags inherited-tags table
13618 (if org-fast-tag-selection-include-todo
13619 org-todo-key-alist))
13620 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13621 (org-trim
13622 (org-icompleting-read "Tags: "
13623 'org-tags-completion-function
13624 nil nil current 'org-tags-history))))))
13625 (while (string-match "[-+&]+" tags)
13626 ;; No boolean logic, just a list
13627 (setq tags (replace-match ":" t t tags))))
13629 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13631 (if org-tags-sort-function
13632 (setq tags (mapconcat 'identity
13633 (sort (org-split-string
13634 tags (org-re "[^[:alnum:]_@#%]+"))
13635 org-tags-sort-function) ":")))
13637 (if (string-match "\\`[\t ]*\\'" tags)
13638 (setq tags "")
13639 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13640 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13642 ;; Insert new tags at the correct column
13643 (beginning-of-line 1)
13644 (setq level (or (and (looking-at org-outline-regexp)
13645 (- (match-end 0) (point) 1))
13647 (cond
13648 ((and (equal current "") (equal tags "")))
13649 ((re-search-forward
13650 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13651 (point-at-eol) t)
13652 (if (equal tags "")
13653 (setq rpl "")
13654 (goto-char (match-beginning 0))
13655 (setq c0 (current-column)
13656 ;; compute offset for the case of org-indent-mode active
13657 di (if org-indent-mode
13658 (* (1- org-indent-indentation-per-level) (1- level))
13660 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13661 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13662 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13663 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13664 (replace-match rpl t t)
13665 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13666 tags)
13667 (t (error "Tags alignment failed")))
13668 (org-move-to-column col)
13669 (unless just-align
13670 (run-hooks 'org-after-tags-change-hook))))))
13672 (defun org-change-tag-in-region (beg end tag off)
13673 "Add or remove TAG for each entry in the region.
13674 This works in the agenda, and also in an org-mode buffer."
13675 (interactive
13676 (list (region-beginning) (region-end)
13677 (let ((org-last-tags-completion-table
13678 (if (derived-mode-p 'org-mode)
13679 (org-get-buffer-tags)
13680 (org-global-tags-completion-table))))
13681 (org-icompleting-read
13682 "Tag: " 'org-tags-completion-function nil nil nil
13683 'org-tags-history))
13684 (progn
13685 (message "[s]et or [r]emove? ")
13686 (equal (read-char-exclusive) ?r))))
13687 (if (fboundp 'deactivate-mark) (deactivate-mark))
13688 (let ((agendap (equal major-mode 'org-agenda-mode))
13689 l1 l2 m buf pos newhead (cnt 0))
13690 (goto-char end)
13691 (setq l2 (1- (org-current-line)))
13692 (goto-char beg)
13693 (setq l1 (org-current-line))
13694 (loop for l from l1 to l2 do
13695 (org-goto-line l)
13696 (setq m (get-text-property (point) 'org-hd-marker))
13697 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13698 (and agendap m))
13699 (setq buf (if agendap (marker-buffer m) (current-buffer))
13700 pos (if agendap m (point)))
13701 (with-current-buffer buf
13702 (save-excursion
13703 (save-restriction
13704 (goto-char pos)
13705 (setq cnt (1+ cnt))
13706 (org-toggle-tag tag (if off 'off 'on))
13707 (setq newhead (org-get-heading)))))
13708 (and agendap (org-agenda-change-all-lines newhead m))))
13709 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13711 (defun org-tags-completion-function (string predicate &optional flag)
13712 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13713 (confirm (lambda (x) (stringp (car x)))))
13714 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13715 (setq s1 (match-string 1 string)
13716 s2 (match-string 2 string))
13717 (setq s1 "" s2 string))
13718 (cond
13719 ((eq flag nil)
13720 ;; try completion
13721 (setq rtn (try-completion s2 ctable confirm))
13722 (if (stringp rtn)
13723 (setq rtn
13724 (concat s1 s2 (substring rtn (length s2))
13725 (if (and org-add-colon-after-tag-completion
13726 (assoc rtn ctable))
13727 ":" ""))))
13728 rtn)
13729 ((eq flag t)
13730 ;; all-completions
13731 (all-completions s2 ctable confirm)
13733 ((eq flag 'lambda)
13734 ;; exact match?
13735 (assoc s2 ctable)))
13738 (defun org-fast-tag-insert (kwd tags face &optional end)
13739 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13740 (insert (format "%-12s" (concat kwd ":"))
13741 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13742 (or end "")))
13744 (defun org-fast-tag-show-exit (flag)
13745 (save-excursion
13746 (org-goto-line 3)
13747 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13748 (replace-match ""))
13749 (when flag
13750 (end-of-line 1)
13751 (org-move-to-column (- (window-width) 19) t)
13752 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13754 (defun org-set-current-tags-overlay (current prefix)
13755 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13756 (if (featurep 'xemacs)
13757 (org-overlay-display org-tags-overlay (concat prefix s)
13758 'secondary-selection)
13759 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13760 (org-overlay-display org-tags-overlay (concat prefix s)))))
13762 (defvar org-last-tag-selection-key nil)
13763 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13764 "Fast tag selection with single keys.
13765 CURRENT is the current list of tags in the headline, INHERITED is the
13766 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13767 possibly with grouping information. TODO-TABLE is a similar table with
13768 TODO keywords, should these have keys assigned to them.
13769 If the keys are nil, a-z are automatically assigned.
13770 Returns the new tags string, or nil to not change the current settings."
13771 (let* ((fulltable (append table todo-table))
13772 (maxlen (apply 'max (mapcar
13773 (lambda (x)
13774 (if (stringp (car x)) (string-width (car x)) 0))
13775 fulltable)))
13776 (buf (current-buffer))
13777 (expert (eq org-fast-tag-selection-single-key 'expert))
13778 (buffer-tags nil)
13779 (fwidth (+ maxlen 3 1 3))
13780 (ncol (/ (- (window-width) 4) fwidth))
13781 (i-face 'org-done)
13782 (c-face 'org-todo)
13783 tg cnt e c char c1 c2 ntable tbl rtn
13784 ov-start ov-end ov-prefix
13785 (exit-after-next org-fast-tag-selection-single-key)
13786 (done-keywords org-done-keywords)
13787 groups ingroup)
13788 (save-excursion
13789 (beginning-of-line 1)
13790 (if (looking-at
13791 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13792 (setq ov-start (match-beginning 1)
13793 ov-end (match-end 1)
13794 ov-prefix "")
13795 (setq ov-start (1- (point-at-eol))
13796 ov-end (1+ ov-start))
13797 (skip-chars-forward "^\n\r")
13798 (setq ov-prefix
13799 (concat
13800 (buffer-substring (1- (point)) (point))
13801 (if (> (current-column) org-tags-column)
13803 (make-string (- org-tags-column (current-column)) ?\ ))))))
13804 (move-overlay org-tags-overlay ov-start ov-end)
13805 (save-window-excursion
13806 (if expert
13807 (set-buffer (get-buffer-create " *Org tags*"))
13808 (delete-other-windows)
13809 (split-window-vertically)
13810 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13811 (erase-buffer)
13812 (org-set-local 'org-done-keywords done-keywords)
13813 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13814 (org-fast-tag-insert "Current" current c-face "\n\n")
13815 (org-fast-tag-show-exit exit-after-next)
13816 (org-set-current-tags-overlay current ov-prefix)
13817 (setq tbl fulltable char ?a cnt 0)
13818 (while (setq e (pop tbl))
13819 (cond
13820 ((equal (car e) :startgroup)
13821 (push '() groups) (setq ingroup t)
13822 (when (not (= cnt 0))
13823 (setq cnt 0)
13824 (insert "\n"))
13825 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13826 ((equal (car e) :endgroup)
13827 (setq ingroup nil cnt 0)
13828 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13829 ((equal e '(:newline))
13830 (when (not (= cnt 0))
13831 (setq cnt 0)
13832 (insert "\n")
13833 (setq e (car tbl))
13834 (while (equal (car tbl) '(:newline))
13835 (insert "\n")
13836 (setq tbl (cdr tbl)))))
13838 (setq tg (copy-sequence (car e)) c2 nil)
13839 (if (cdr e)
13840 (setq c (cdr e))
13841 ;; automatically assign a character.
13842 (setq c1 (string-to-char
13843 (downcase (substring
13844 tg (if (= (string-to-char tg) ?@) 1 0)))))
13845 (if (or (rassoc c1 ntable) (rassoc c1 table))
13846 (while (or (rassoc char ntable) (rassoc char table))
13847 (setq char (1+ char)))
13848 (setq c2 c1))
13849 (setq c (or c2 char)))
13850 (if ingroup (push tg (car groups)))
13851 (setq tg (org-add-props tg nil 'face
13852 (cond
13853 ((not (assoc tg table))
13854 (org-get-todo-face tg))
13855 ((member tg current) c-face)
13856 ((member tg inherited) i-face)
13857 (t nil))))
13858 (if (and (= cnt 0) (not ingroup)) (insert " "))
13859 (insert "[" c "] " tg (make-string
13860 (- fwidth 4 (length tg)) ?\ ))
13861 (push (cons tg c) ntable)
13862 (when (= (setq cnt (1+ cnt)) ncol)
13863 (insert "\n")
13864 (if ingroup (insert " "))
13865 (setq cnt 0)))))
13866 (setq ntable (nreverse ntable))
13867 (insert "\n")
13868 (goto-char (point-min))
13869 (if (not expert) (org-fit-window-to-buffer))
13870 (setq rtn
13871 (catch 'exit
13872 (while t
13873 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13874 (if (not groups) "no " "")
13875 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13876 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13877 (setq org-last-tag-selection-key c)
13878 (cond
13879 ((= c ?\r) (throw 'exit t))
13880 ((= c ?!)
13881 (setq groups (not groups))
13882 (goto-char (point-min))
13883 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13884 ((= c ?\C-c)
13885 (if (not expert)
13886 (org-fast-tag-show-exit
13887 (setq exit-after-next (not exit-after-next)))
13888 (setq expert nil)
13889 (delete-other-windows)
13890 (set-window-buffer (split-window-vertically) " *Org tags*")
13891 (org-switch-to-buffer-other-window " *Org tags*")
13892 (org-fit-window-to-buffer)))
13893 ((or (= c ?\C-g)
13894 (and (= c ?q) (not (rassoc c ntable))))
13895 (org-detach-overlay org-tags-overlay)
13896 (setq quit-flag t))
13897 ((= c ?\ )
13898 (setq current nil)
13899 (if exit-after-next (setq exit-after-next 'now)))
13900 ((= c ?\t)
13901 (condition-case nil
13902 (setq tg (org-icompleting-read
13903 "Tag: "
13904 (or buffer-tags
13905 (with-current-buffer buf
13906 (org-get-buffer-tags)))))
13907 (quit (setq tg "")))
13908 (when (string-match "\\S-" tg)
13909 (add-to-list 'buffer-tags (list tg))
13910 (if (member tg current)
13911 (setq current (delete tg current))
13912 (push tg current)))
13913 (if exit-after-next (setq exit-after-next 'now)))
13914 ((setq e (rassoc c todo-table) tg (car e))
13915 (with-current-buffer buf
13916 (save-excursion (org-todo tg)))
13917 (if exit-after-next (setq exit-after-next 'now)))
13918 ((setq e (rassoc c ntable) tg (car e))
13919 (if (member tg current)
13920 (setq current (delete tg current))
13921 (loop for g in groups do
13922 (if (member tg g)
13923 (mapc (lambda (x)
13924 (setq current (delete x current)))
13925 g)))
13926 (push tg current))
13927 (if exit-after-next (setq exit-after-next 'now))))
13929 ;; Create a sorted list
13930 (setq current
13931 (sort current
13932 (lambda (a b)
13933 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13934 (if (eq exit-after-next 'now) (throw 'exit t))
13935 (goto-char (point-min))
13936 (beginning-of-line 2)
13937 (delete-region (point) (point-at-eol))
13938 (org-fast-tag-insert "Current" current c-face)
13939 (org-set-current-tags-overlay current ov-prefix)
13940 (while (re-search-forward
13941 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13942 (setq tg (match-string 1))
13943 (add-text-properties
13944 (match-beginning 1) (match-end 1)
13945 (list 'face
13946 (cond
13947 ((member tg current) c-face)
13948 ((member tg inherited) i-face)
13949 (t (get-text-property (match-beginning 1) 'face))))))
13950 (goto-char (point-min)))))
13951 (org-detach-overlay org-tags-overlay)
13952 (if rtn
13953 (mapconcat 'identity current ":")
13954 nil))))
13956 (defun org-get-tags-string ()
13957 "Get the TAGS string in the current headline."
13958 (unless (org-at-heading-p t)
13959 (error "Not on a heading"))
13960 (save-excursion
13961 (beginning-of-line 1)
13962 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13963 (org-match-string-no-properties 1)
13964 "")))
13966 (defun org-get-tags ()
13967 "Get the list of tags specified in the current headline."
13968 (org-split-string (org-get-tags-string) ":"))
13970 (defun org-get-buffer-tags ()
13971 "Get a table of all tags used in the buffer, for completion."
13972 (let (tags)
13973 (save-excursion
13974 (goto-char (point-min))
13975 (while (re-search-forward
13976 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13977 (when (equal (char-after (point-at-bol 0)) ?*)
13978 (mapc (lambda (x) (add-to-list 'tags x))
13979 (org-split-string (org-match-string-no-properties 1) ":")))))
13980 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13981 (mapcar 'list tags)))
13983 ;;;; The mapping API
13985 ;;;###autoload
13986 (defun org-map-entries (func &optional match scope &rest skip)
13987 "Call FUNC at each headline selected by MATCH in SCOPE.
13989 FUNC is a function or a lisp form. The function will be called without
13990 arguments, with the cursor positioned at the beginning of the headline.
13991 The return values of all calls to the function will be collected and
13992 returned as a list.
13994 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13995 does not need to preserve point. After evaluation, the cursor will be
13996 moved to the end of the line (presumably of the headline of the
13997 processed entry) and search continues from there. Under some
13998 circumstances, this may not produce the wanted results. For example,
13999 if you have removed (e.g. archived) the current (sub)tree it could
14000 mean that the next entry will be skipped entirely. In such cases, you
14001 can specify the position from where search should continue by making
14002 FUNC set the variable `org-map-continue-from' to the desired buffer
14003 position.
14005 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14006 Only headlines that are matched by this query will be considered during
14007 the iteration. When MATCH is nil or t, all headlines will be
14008 visited by the iteration.
14010 SCOPE determines the scope of this command. It can be any of:
14012 nil The current buffer, respecting the restriction if any
14013 tree The subtree started with the entry at point
14014 region The entries within the active region, if any
14015 region-start-level
14016 The entries within the active region, but only those at
14017 the same level than the first one.
14018 file The current buffer, without restriction
14019 file-with-archives
14020 The current buffer, and any archives associated with it
14021 agenda All agenda files
14022 agenda-with-archives
14023 All agenda files with any archive files associated with them
14024 \(file1 file2 ...)
14025 If this is a list, all files in the list will be scanned
14027 The remaining args are treated as settings for the skipping facilities of
14028 the scanner. The following items can be given here:
14030 archive skip trees with the archive tag.
14031 comment skip trees with the COMMENT keyword
14032 function or Emacs Lisp form:
14033 will be used as value for `org-agenda-skip-function', so whenever
14034 the function returns t, FUNC will not be called for that
14035 entry and search will continue from the point where the
14036 function leaves it.
14038 If your function needs to retrieve the tags including inherited tags
14039 at the *current* entry, you can use the value of the variable
14040 `org-scanner-tags' which will be much faster than getting the value
14041 with `org-get-tags-at'. If your function gets properties with
14042 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14043 to t around the call to `org-entry-properties' to get the same speedup.
14044 Note that if your function moves around to retrieve tags and properties at
14045 a *different* entry, you cannot use these techniques."
14046 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14047 (not (org-region-active-p)))
14048 (let* ((org-agenda-archives-mode nil) ; just to make sure
14049 (org-agenda-skip-archived-trees (memq 'archive skip))
14050 (org-agenda-skip-comment-trees (memq 'comment skip))
14051 (org-agenda-skip-function
14052 (car (org-delete-all '(comment archive) skip)))
14053 (org-tags-match-list-sublevels t)
14054 (start-level (eq scope 'region-start-level))
14055 matcher file res
14056 org-todo-keywords-for-agenda
14057 org-done-keywords-for-agenda
14058 org-todo-keyword-alist-for-agenda
14059 org-drawers-for-agenda
14060 org-tag-alist-for-agenda
14061 todo-only)
14063 (cond
14064 ((eq match t) (setq matcher t))
14065 ((eq match nil) (setq matcher t))
14066 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14068 (save-excursion
14069 (save-restriction
14070 (cond ((eq scope 'tree)
14071 (org-back-to-heading t)
14072 (org-narrow-to-subtree)
14073 (setq scope nil))
14074 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14075 (org-region-active-p))
14076 ;; If needed, set start-level to a string like "2"
14077 (when start-level
14078 (save-excursion
14079 (goto-char (region-beginning))
14080 (unless (org-at-heading-p) (outline-next-heading))
14081 (setq start-level (org-current-level))))
14082 (narrow-to-region (region-beginning)
14083 (save-excursion
14084 (goto-char (region-end))
14085 (unless (and (bolp) (org-at-heading-p))
14086 (outline-next-heading))
14087 (point)))
14088 (setq scope nil)))
14090 (if (not scope)
14091 (progn
14092 (org-prepare-agenda-buffers
14093 (list (buffer-file-name (current-buffer))))
14094 (setq res (org-scan-tags func matcher todo-only start-level)))
14095 ;; Get the right scope
14096 (cond
14097 ((and scope (listp scope) (symbolp (car scope)))
14098 (setq scope (eval scope)))
14099 ((eq scope 'agenda)
14100 (setq scope (org-agenda-files t)))
14101 ((eq scope 'agenda-with-archives)
14102 (setq scope (org-agenda-files t))
14103 (setq scope (org-add-archive-files scope)))
14104 ((eq scope 'file)
14105 (setq scope (list (buffer-file-name))))
14106 ((eq scope 'file-with-archives)
14107 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14108 (org-prepare-agenda-buffers scope)
14109 (while (setq file (pop scope))
14110 (with-current-buffer (org-find-base-buffer-visiting file)
14111 (save-excursion
14112 (save-restriction
14113 (widen)
14114 (goto-char (point-min))
14115 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14116 res)))
14118 ;;;; Properties
14120 ;;; Setting and retrieving properties
14122 (defconst org-special-properties
14123 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14124 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14125 "The special properties valid in Org-mode.
14127 These are properties that are not defined in the property drawer,
14128 but in some other way.")
14130 (defconst org-default-properties
14131 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14132 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14133 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14134 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14135 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14136 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14137 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14138 "Some properties that are used by Org-mode for various purposes.
14139 Being in this list makes sure that they are offered for completion.")
14141 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14142 "Regular expression matching the first line of a property drawer.")
14144 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14145 "Regular expression matching the last line of a property drawer.")
14147 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14148 "Regular expression matching the first line of a property drawer.")
14150 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14151 "Regular expression matching the first line of a property drawer.")
14153 (defconst org-property-drawer-re
14154 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14155 org-property-end-re "\\)\n?")
14156 "Matches an entire property drawer.")
14158 (defconst org-clock-drawer-re
14159 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14160 org-property-end-re "\\)\n?")
14161 "Matches an entire clock drawer.")
14163 (defsubst org-re-property (property)
14164 "Return a regexp matching a PROPERTY line.
14165 Match group 1 will be set to the value."
14166 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14168 (defsubst org-re-property-keyword (property)
14169 "Return a regexp matching a PROPERTY line, possibly with no
14170 value for the property."
14171 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14173 (defun org-property-action ()
14174 "Do an action on properties."
14175 (interactive)
14176 (let (c)
14177 (org-at-property-p)
14178 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14179 (setq c (read-char-exclusive))
14180 (cond
14181 ((equal c ?s)
14182 (call-interactively 'org-set-property))
14183 ((equal c ?d)
14184 (call-interactively 'org-delete-property))
14185 ((equal c ?D)
14186 (call-interactively 'org-delete-property-globally))
14187 ((equal c ?c)
14188 (call-interactively 'org-compute-property-at-point))
14189 (t (error "No such property action %c" c)))))
14191 (defun org-inc-effort ()
14192 "Increment the value of the effort property in the current entry."
14193 (interactive)
14194 (org-set-effort nil t))
14196 (defun org-set-effort (&optional value increment)
14197 "Set the effort property of the current entry.
14198 With numerical prefix arg, use the nth allowed value, 0 stands for the
14199 10th allowed value.
14201 When INCREMENT is non-nil, set the property to the next allowed value."
14202 (interactive "P")
14203 (if (equal value 0) (setq value 10))
14204 (let* ((completion-ignore-case t)
14205 (prop org-effort-property)
14206 (cur (org-entry-get nil prop))
14207 (allowed (org-property-get-allowed-values nil prop 'table))
14208 (existing (mapcar 'list (org-property-values prop)))
14210 (val (cond
14211 ((stringp value) value)
14212 ((and allowed (integerp value))
14213 (or (car (nth (1- value) allowed))
14214 (car (org-last allowed))))
14215 ((and allowed increment)
14216 (or (caadr (member (list cur) allowed))
14217 (error "Allowed effort values are not set")))
14218 (allowed
14219 (message "Select 1-9,0, [RET%s]: %s"
14220 (if cur (concat "=" cur) "")
14221 (mapconcat 'car allowed " "))
14222 (setq rpl (read-char-exclusive))
14223 (if (equal rpl ?\r)
14225 (setq rpl (- rpl ?0))
14226 (if (equal rpl 0) (setq rpl 10))
14227 (if (and (> rpl 0) (<= rpl (length allowed)))
14228 (car (nth (1- rpl) allowed))
14229 (org-completing-read "Effort: " allowed nil))))
14231 (let (org-completion-use-ido org-completion-use-iswitchb)
14232 (org-completing-read
14233 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14234 (concat "[" cur "]") "")
14235 ": ")
14236 existing nil nil "" nil cur))))))
14237 (unless (equal (org-entry-get nil prop) val)
14238 (org-entry-put nil prop val))
14239 (message "%s is now %s" prop val)))
14241 (defun org-at-property-p ()
14242 "Is cursor inside a property drawer?"
14243 (save-excursion
14244 (beginning-of-line 1)
14245 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14246 (save-match-data ;; Used by calling procedures
14247 (let ((p (point))
14248 (range (unless (org-before-first-heading-p)
14249 (org-get-property-block))))
14250 (and range (<= (car range) p) (< p (cdr range))))))))
14252 (defun org-get-property-block (&optional beg end force)
14253 "Return the (beg . end) range of the body of the property drawer.
14254 BEG and END can be beginning and end of subtree, if not given
14255 they will be found.
14256 If the drawer does not exist and FORCE is non-nil, create the drawer."
14257 (catch 'exit
14258 (save-excursion
14259 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14260 (end (or end (progn (outline-next-heading) (point)))))
14261 (goto-char beg)
14262 (if (re-search-forward org-property-start-re end t)
14263 (setq beg (1+ (match-end 0)))
14264 (if force
14265 (save-excursion
14266 (org-insert-property-drawer)
14267 (setq end (progn (outline-next-heading) (point))))
14268 (throw 'exit nil))
14269 (goto-char beg)
14270 (if (re-search-forward org-property-start-re end t)
14271 (setq beg (1+ (match-end 0)))))
14272 (if (re-search-forward org-property-end-re end t)
14273 (setq end (match-beginning 0))
14274 (or force (throw 'exit nil))
14275 (goto-char beg)
14276 (setq end beg)
14277 (org-indent-line)
14278 (insert ":END:\n"))
14279 (cons beg end)))))
14281 (defun org-entry-properties (&optional pom which specific)
14282 "Get all properties of the entry at point-or-marker POM.
14283 This includes the TODO keyword, the tags, time strings for deadline,
14284 scheduled, and clocking, and any additional properties defined in the
14285 entry. The return value is an alist, keys may occur multiple times
14286 if the property key was used several times.
14287 POM may also be nil, in which case the current entry is used.
14288 If WHICH is nil or `all', get all properties. If WHICH is
14289 `special' or `standard', only get that subclass. If WHICH
14290 is a string only get exactly this property. SPECIFIC can be a string, the
14291 specific property we are interested in. Specifying it can speed
14292 things up because then unnecessary parsing is avoided."
14293 (setq which (or which 'all))
14294 (org-with-point-at pom
14295 (let ((clockstr (substring org-clock-string 0 -1))
14296 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14297 (case-fold-search nil)
14298 beg end range props sum-props key key1 value string clocksum)
14299 (save-excursion
14300 (when (condition-case nil
14301 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14302 (error nil))
14303 (setq beg (point))
14304 (setq sum-props (get-text-property (point) 'org-summaries))
14305 (setq clocksum (get-text-property (point) :org-clock-minutes))
14306 (outline-next-heading)
14307 (setq end (point))
14308 (when (memq which '(all special))
14309 ;; Get the special properties, like TODO and tags
14310 (goto-char beg)
14311 (when (and (or (not specific) (string= specific "TODO"))
14312 (looking-at org-todo-line-regexp) (match-end 2))
14313 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14314 (when (and (or (not specific) (string= specific "PRIORITY"))
14315 (looking-at org-priority-regexp))
14316 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14317 (when (or (not specific) (string= specific "FILE"))
14318 (push (cons "FILE" buffer-file-name) props))
14319 (when (and (or (not specific) (string= specific "TAGS"))
14320 (setq value (org-get-tags-string))
14321 (string-match "\\S-" value))
14322 (push (cons "TAGS" value) props))
14323 (when (and (or (not specific) (string= specific "ALLTAGS"))
14324 (setq value (org-get-tags-at)))
14325 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14326 ":"))
14327 props))
14328 (when (or (not specific) (string= specific "BLOCKED"))
14329 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14330 (when (or (not specific)
14331 (member specific
14332 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14333 "TIMESTAMP" "TIMESTAMP_IA")))
14334 (catch 'match
14335 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14336 (setq key (if (match-end 1)
14337 (substring (org-match-string-no-properties 1)
14338 0 -1))
14339 string (if (equal key clockstr)
14340 (org-no-properties
14341 (org-trim
14342 (buffer-substring
14343 (match-beginning 3) (goto-char
14344 (point-at-eol)))))
14345 (substring (org-match-string-no-properties 3)
14346 1 -1)))
14347 ;; Get the correct property name from the key. This is
14348 ;; necessary if the user has configured time keywords.
14349 (setq key1 (concat key ":"))
14350 (cond
14351 ((not key)
14352 (setq key
14353 (if (= (char-after (match-beginning 3)) ?\[)
14354 "TIMESTAMP_IA" "TIMESTAMP")))
14355 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14356 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14357 ((equal key1 org-closed-string) (setq key "CLOSED"))
14358 ((equal key1 org-clock-string) (setq key "CLOCK")))
14359 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14360 (progn
14361 (push (cons key string) props)
14362 ;; no need to search further if match is found
14363 (throw 'match t))
14364 (when (or (equal key "CLOCK") (not (assoc key props)))
14365 (push (cons key string) props))))))
14368 (when (memq which '(all standard))
14369 ;; Get the standard properties, like :PROP: ...
14370 (setq range (org-get-property-block beg end))
14371 (when range
14372 (goto-char (car range))
14373 (while (re-search-forward
14374 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14375 (cdr range) t)
14376 (setq key (org-match-string-no-properties 1)
14377 value (org-trim (or (org-match-string-no-properties 2) "")))
14378 (unless (member key excluded)
14379 (push (cons key (or value "")) props)))))
14380 (if clocksum
14381 (push (cons "CLOCKSUM"
14382 (org-columns-number-to-string (/ (float clocksum) 60.)
14383 'add_times))
14384 props))
14385 (unless (assoc "CATEGORY" props)
14386 (push (cons "CATEGORY" (org-get-category)) props))
14387 (append sum-props (nreverse props)))))))
14389 (defun org-entry-get (pom property &optional inherit literal-nil)
14390 "Get value of PROPERTY for entry at point-or-marker POM.
14391 If INHERIT is non-nil and the entry does not have the property,
14392 then also check higher levels of the hierarchy.
14393 If INHERIT is the symbol `selective', use inheritance only if the setting
14394 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14395 If the property is present but empty, the return value is the empty string.
14396 If the property is not present at all, nil is returned.
14398 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14399 do not interpret it as the list atom nil. This is used for inheritance
14400 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14401 (org-with-point-at pom
14402 (if (and inherit (if (eq inherit 'selective)
14403 (org-property-inherit-p property)
14405 (org-entry-get-with-inheritance property literal-nil)
14406 (if (member property org-special-properties)
14407 ;; We need a special property. Use `org-entry-properties' to
14408 ;; retrieve it, but specify the wanted property
14409 (cdr (assoc property (org-entry-properties nil 'special property)))
14410 (let ((range (unless (org-before-first-heading-p)
14411 (org-get-property-block)))
14412 (props (list (or (assoc property org-file-properties)
14413 (assoc property org-global-properties)
14414 (assoc property org-global-properties-fixed))))
14415 val)
14416 (org-flet ((ap (key)
14417 (when (re-search-forward
14418 (org-re-property key) (cdr range) t)
14419 (setq props
14420 (org-update-property-plist
14422 (if (match-end 1)
14423 (org-match-string-no-properties 1) "")
14424 props)))))
14425 (when (and range (goto-char (car range)))
14426 (ap property)
14427 (goto-char (car range))
14428 (while (ap (concat property "+")))
14429 (setq val (cdr (assoc property props)))
14430 (when val (if literal-nil val (org-not-nil val))))))))))
14432 (defun org-property-or-variable-value (var &optional inherit)
14433 "Check if there is a property fixing the value of VAR.
14434 If yes, return this value. If not, return the current value of the variable."
14435 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14436 (if (and prop (stringp prop) (string-match "\\S-" prop))
14437 (read prop)
14438 (symbol-value var))))
14440 (defun org-entry-delete (pom property)
14441 "Delete the property PROPERTY from entry at point-or-marker POM."
14442 (org-with-point-at pom
14443 (if (member property org-special-properties)
14444 nil ; cannot delete these properties.
14445 (let ((range (org-get-property-block)))
14446 (if (and range
14447 (goto-char (car range))
14448 (re-search-forward
14449 (org-re-property property)
14450 (cdr range) t))
14451 (progn
14452 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14454 nil)))))
14456 ;; Multi-values properties are properties that contain multiple values
14457 ;; These values are assumed to be single words, separated by whitespace.
14458 (defun org-entry-add-to-multivalued-property (pom property value)
14459 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14460 (let* ((old (org-entry-get pom property))
14461 (values (and old (org-split-string old "[ \t]"))))
14462 (setq value (org-entry-protect-space value))
14463 (unless (member value values)
14464 (setq values (cons value values))
14465 (org-entry-put pom property
14466 (mapconcat 'identity values " ")))))
14468 (defun org-entry-remove-from-multivalued-property (pom property value)
14469 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14470 (let* ((old (org-entry-get pom property))
14471 (values (and old (org-split-string old "[ \t]"))))
14472 (setq value (org-entry-protect-space value))
14473 (when (member value values)
14474 (setq values (delete value values))
14475 (org-entry-put pom property
14476 (mapconcat 'identity values " ")))))
14478 (defun org-entry-member-in-multivalued-property (pom property value)
14479 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14480 (let* ((old (org-entry-get pom property))
14481 (values (and old (org-split-string old "[ \t]"))))
14482 (setq value (org-entry-protect-space value))
14483 (member value values)))
14485 (defun org-entry-get-multivalued-property (pom property)
14486 "Return a list of values in a multivalued property."
14487 (let* ((value (org-entry-get pom property))
14488 (values (and value (org-split-string value "[ \t]"))))
14489 (mapcar 'org-entry-restore-space values)))
14491 (defun org-entry-put-multivalued-property (pom property &rest values)
14492 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14493 VALUES should be a list of strings. Spaces will be protected."
14494 (org-entry-put pom property
14495 (mapconcat 'org-entry-protect-space values " "))
14496 (let* ((value (org-entry-get pom property))
14497 (values (and value (org-split-string value "[ \t]"))))
14498 (mapcar 'org-entry-restore-space values)))
14500 (defun org-entry-protect-space (s)
14501 "Protect spaces and newline in string S."
14502 (while (string-match " " s)
14503 (setq s (replace-match "%20" t t s)))
14504 (while (string-match "\n" s)
14505 (setq s (replace-match "%0A" t t s)))
14508 (defun org-entry-restore-space (s)
14509 "Restore spaces and newline in string S."
14510 (while (string-match "%20" s)
14511 (setq s (replace-match " " t t s)))
14512 (while (string-match "%0A" s)
14513 (setq s (replace-match "\n" t t s)))
14516 (defvar org-entry-property-inherited-from (make-marker)
14517 "Marker pointing to the entry from where a property was inherited.
14518 Each call to `org-entry-get-with-inheritance' will set this marker to the
14519 location of the entry where the inheritance search matched. If there was
14520 no match, the marker will point nowhere.
14521 Note that also `org-entry-get' calls this function, if the INHERIT flag
14522 is set.")
14524 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14525 "Get entry property, and search higher levels if not present.
14526 The search will stop at the first ancestor which has the property defined.
14527 If the value found is \"nil\", return nil to show that the property
14528 should be considered as undefined (this is the meaning of nil here).
14529 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14530 (move-marker org-entry-property-inherited-from nil)
14531 (let (tmp)
14532 (unless (org-before-first-heading-p)
14533 (save-excursion
14534 (save-restriction
14535 (widen)
14536 (catch 'ex
14537 (while t
14538 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14539 (org-back-to-heading t)
14540 (move-marker org-entry-property-inherited-from (point))
14541 (throw 'ex tmp))
14542 (or (org-up-heading-safe) (throw 'ex nil)))))))
14543 (setq tmp (or tmp
14544 (cdr (assoc property org-file-properties))
14545 (cdr (assoc property org-global-properties))
14546 (cdr (assoc property org-global-properties-fixed))))
14547 (if literal-nil tmp (org-not-nil tmp))))
14549 (defvar org-property-changed-functions nil
14550 "Hook called when the value of a property has changed.
14551 Each hook function should accept two arguments, the name of the property
14552 and the new value.")
14554 (defun org-entry-put (pom property value)
14555 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14556 (org-with-point-at pom
14557 (org-back-to-heading t)
14558 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14559 range)
14560 (cond
14561 ((equal property "TODO")
14562 (when (and (stringp value) (string-match "\\S-" value)
14563 (not (member value org-todo-keywords-1)))
14564 (error "\"%s\" is not a valid TODO state" value))
14565 (if (or (not value)
14566 (not (string-match "\\S-" value)))
14567 (setq value 'none))
14568 (org-todo value)
14569 (org-set-tags nil 'align))
14570 ((equal property "PRIORITY")
14571 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14572 (string-to-char value) ?\ ))
14573 (org-set-tags nil 'align))
14574 ((equal property "SCHEDULED")
14575 (if (re-search-forward org-scheduled-time-regexp end t)
14576 (cond
14577 ((eq value 'earlier) (org-timestamp-change -1 'day))
14578 ((eq value 'later) (org-timestamp-change 1 'day))
14579 (t (call-interactively 'org-schedule)))
14580 (call-interactively 'org-schedule)))
14581 ((equal property "DEADLINE")
14582 (if (re-search-forward org-deadline-time-regexp end t)
14583 (cond
14584 ((eq value 'earlier) (org-timestamp-change -1 'day))
14585 ((eq value 'later) (org-timestamp-change 1 'day))
14586 (t (call-interactively 'org-deadline)))
14587 (call-interactively 'org-deadline)))
14588 ((member property org-special-properties)
14589 (error "The %s property can not yet be set with `org-entry-put'"
14590 property))
14591 (t ; a non-special property
14592 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14593 (setq range (org-get-property-block beg end 'force))
14594 (goto-char (car range))
14595 (if (re-search-forward
14596 (org-re-property-keyword property) (cdr range) t)
14597 (progn
14598 (delete-region (match-beginning 0) (match-end 0))
14599 (goto-char (match-beginning 0)))
14600 (goto-char (cdr range))
14601 (insert "\n")
14602 (backward-char 1)
14603 (org-indent-line))
14604 (insert ":" property ":")
14605 (and value (insert " " value))
14606 (org-indent-line)))))
14607 (run-hook-with-args 'org-property-changed-functions property value)))
14609 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14610 "Get all property keys in the current buffer.
14611 With INCLUDE-SPECIALS, also list the special properties that reflect things
14612 like tags and TODO state.
14613 With INCLUDE-DEFAULTS, also include properties that has special meaning
14614 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14615 and others.
14616 With INCLUDE-COLUMNS, also include property names given in COLUMN
14617 formats in the current buffer."
14618 (let (rtn range cfmt s p)
14619 (save-excursion
14620 (save-restriction
14621 (widen)
14622 (goto-char (point-min))
14623 (while (re-search-forward org-property-start-re nil t)
14624 (setq range (org-get-property-block))
14625 (goto-char (car range))
14626 (while (re-search-forward
14627 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14628 (cdr range) t)
14629 (add-to-list 'rtn (org-match-string-no-properties 1)))
14630 (outline-next-heading))))
14632 (when include-specials
14633 (setq rtn (append org-special-properties rtn)))
14635 (when include-defaults
14636 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14637 (add-to-list 'rtn org-effort-property))
14639 (when include-columns
14640 (save-excursion
14641 (save-restriction
14642 (widen)
14643 (goto-char (point-min))
14644 (while (re-search-forward
14645 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14646 nil t)
14647 (setq cfmt (match-string 2) s 0)
14648 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14649 cfmt s)
14650 (setq s (match-end 0)
14651 p (match-string 1 cfmt))
14652 (unless (or (equal p "ITEM")
14653 (member p org-special-properties))
14654 (add-to-list 'rtn (match-string 1 cfmt))))))))
14656 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14658 (defun org-property-values (key)
14659 "Return a list of all values of property KEY in the current buffer."
14660 (save-excursion
14661 (save-restriction
14662 (widen)
14663 (goto-char (point-min))
14664 (let ((re (org-re-property key))
14665 values)
14666 (while (re-search-forward re nil t)
14667 (add-to-list 'values (org-trim (match-string 1))))
14668 (delete "" values)))))
14670 (defun org-insert-property-drawer ()
14671 "Insert a property drawer into the current entry."
14672 (org-back-to-heading t)
14673 (looking-at org-outline-regexp)
14674 (let ((indent (if org-adapt-indentation
14675 (- (match-end 0) (match-beginning 0))
14677 (beg (point))
14678 (re (concat "^[ \t]*" org-keyword-time-regexp))
14679 end hiddenp)
14680 (outline-next-heading)
14681 (setq end (point))
14682 (goto-char beg)
14683 (while (re-search-forward re end t))
14684 (setq hiddenp (outline-invisible-p))
14685 (end-of-line 1)
14686 (and (equal (char-after) ?\n) (forward-char 1))
14687 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14688 (if (member (match-string 1) '("CLOCK:" ":END:"))
14689 ;; just skip this line
14690 (beginning-of-line 2)
14691 ;; Drawer start, find the end
14692 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14693 (beginning-of-line 1)))
14694 (org-skip-over-state-notes)
14695 (skip-chars-backward " \t\n\r")
14696 (if (eq (char-before) ?*) (forward-char 1))
14697 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14698 (beginning-of-line 0)
14699 (org-indent-to-column indent)
14700 (beginning-of-line 2)
14701 (org-indent-to-column indent)
14702 (beginning-of-line 0)
14703 (if hiddenp
14704 (save-excursion
14705 (org-back-to-heading t)
14706 (hide-entry))
14707 (org-flag-drawer t))))
14709 (defun org-insert-drawer (&optional arg drawer)
14710 "Insert a drawer at point.
14712 Optional argument DRAWER, when non-nil, is a string representing
14713 drawer's name. Otherwise, the user is prompted for a name.
14715 If a region is active, insert the drawer around that region
14716 instead.
14718 Point is left between drawer's boundaries."
14719 (interactive "P")
14720 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14721 "LOGBOOK"))
14722 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14723 ;; internally by Org. They are meant to be inserted
14724 ;; automatically.
14725 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14726 ;; Remove system drawers from list. Note: For some reason,
14727 ;; `org-completing-read' ignores the predicate while
14728 ;; `completing-read' handles it fine.
14729 (drawer (if arg "PROPERTIES"
14730 (or drawer
14731 (completing-read
14732 "Drawer: " org-drawers
14733 (lambda (d) (not (member d system-drawers))))))))
14734 (cond
14735 ;; With C-u, fall back on `org-insert-property-drawer'
14736 (arg (org-insert-property-drawer))
14737 ;; With an active region, insert a drawer at point.
14738 ((not (org-region-active-p))
14739 (progn
14740 (unless (bolp) (insert "\n"))
14741 (insert (format ":%s:\n\n:END:\n" drawer))
14742 (forward-line -2)))
14743 ;; Otherwise, insert the drawer at point
14745 (let ((rbeg (region-beginning))
14746 (rend (copy-marker (region-end))))
14747 (unwind-protect
14748 (progn
14749 (goto-char rbeg)
14750 (beginning-of-line)
14751 (when (save-excursion
14752 (re-search-forward org-outline-regexp-bol rend t))
14753 (error "Drawers cannot contain headlines"))
14754 ;; Position point at the beginning of the first
14755 ;; non-blank line in region. Insert drawer's opening
14756 ;; there, then indent it.
14757 (org-skip-whitespace)
14758 (beginning-of-line)
14759 (insert ":" drawer ":\n")
14760 (forward-line -1)
14761 (indent-for-tab-command)
14762 ;; Move point to the beginning of the first blank line
14763 ;; after the last non-blank line in region. Insert
14764 ;; drawer's closing, then indent it.
14765 (goto-char rend)
14766 (skip-chars-backward " \r\t\n")
14767 (insert "\n:END:")
14768 (indent-for-tab-command)
14769 (unless (eolp) (insert "\n")))
14770 ;; Clear marker, whatever the outcome of insertion is.
14771 (set-marker rend nil)))))))
14773 (defvar org-property-set-functions-alist nil
14774 "Property set function alist.
14775 Each entry should have the following format:
14777 (PROPERTY . READ-FUNCTION)
14779 The read function will be called with the same argument as
14780 `org-completing-read'.")
14782 (defun org-set-property-function (property)
14783 "Get the function that should be used to set PROPERTY.
14784 This is computed according to `org-property-set-functions-alist'."
14785 (or (cdr (assoc property org-property-set-functions-alist))
14786 'org-completing-read))
14788 (defun org-read-property-value (property)
14789 "Read PROPERTY value from user."
14790 (let* ((completion-ignore-case t)
14791 (allowed (org-property-get-allowed-values nil property 'table))
14792 (cur (org-entry-get nil property))
14793 (prompt (concat property " value"
14794 (if (and cur (string-match "\\S-" cur))
14795 (concat " [" cur "]") "") ": "))
14796 (set-function (org-set-property-function property))
14797 (val (if allowed
14798 (funcall set-function prompt allowed nil
14799 (not (get-text-property 0 'org-unrestricted
14800 (caar allowed))))
14801 (let (org-completion-use-ido org-completion-use-iswitchb)
14802 (funcall set-function prompt
14803 (mapcar 'list (org-property-values property))
14804 nil nil "" nil cur)))))
14805 (if (equal val "")
14807 val)))
14809 (defvar org-last-set-property nil)
14810 (defun org-read-property-name ()
14811 "Read a property name."
14812 (let* ((completion-ignore-case t)
14813 (keys (org-buffer-property-keys nil t t))
14814 (default-prop (or (save-excursion
14815 (save-match-data
14816 (beginning-of-line)
14817 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14818 (null (string= (match-string 1) "END"))
14819 (match-string 1))))
14820 org-last-set-property))
14821 (property (org-icompleting-read
14822 (concat "Property"
14823 (if default-prop (concat " [" default-prop "]") "")
14824 ": ")
14825 (mapcar 'list keys)
14826 nil nil nil nil
14827 default-prop
14829 (if (member property keys)
14830 property
14831 (or (cdr (assoc (downcase property)
14832 (mapcar (lambda (x) (cons (downcase x) x))
14833 keys)))
14834 property))))
14836 (defun org-set-property (property value)
14837 "In the current entry, set PROPERTY to VALUE.
14838 When called interactively, this will prompt for a property name, offering
14839 completion on existing and default properties. And then it will prompt
14840 for a value, offering completion either on allowed values (via an inherited
14841 xxx_ALL property) or on existing values in other instances of this property
14842 in the current file."
14843 (interactive (list nil nil))
14844 (let* ((property (or property (org-read-property-name)))
14845 (value (or value (org-read-property-value property)))
14846 (fn (cdr (assoc property org-properties-postprocess-alist))))
14847 (setq org-last-set-property property)
14848 ;; Possibly postprocess the inserted value:
14849 (when fn (setq value (funcall fn value)))
14850 (unless (equal (org-entry-get nil property) value)
14851 (org-entry-put nil property value))))
14853 (defun org-delete-property (property)
14854 "In the current entry, delete PROPERTY."
14855 (interactive
14856 (let* ((completion-ignore-case t)
14857 (prop (org-icompleting-read "Property: "
14858 (org-entry-properties nil 'standard))))
14859 (list prop)))
14860 (message "Property %s %s" property
14861 (if (org-entry-delete nil property)
14862 "deleted"
14863 "was not present in the entry")))
14865 (defun org-delete-property-globally (property)
14866 "Remove PROPERTY globally, from all entries."
14867 (interactive
14868 (let* ((completion-ignore-case t)
14869 (prop (org-icompleting-read
14870 "Globally remove property: "
14871 (mapcar 'list (org-buffer-property-keys)))))
14872 (list prop)))
14873 (save-excursion
14874 (save-restriction
14875 (widen)
14876 (goto-char (point-min))
14877 (let ((cnt 0))
14878 (while (re-search-forward
14879 (org-re-property property)
14880 nil t)
14881 (setq cnt (1+ cnt))
14882 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14883 (message "Property \"%s\" removed from %d entries" property cnt)))))
14885 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14887 (defun org-compute-property-at-point ()
14888 "Compute the property at point.
14889 This looks for an enclosing column format, extracts the operator and
14890 then applies it to the property in the column format's scope."
14891 (interactive)
14892 (unless (org-at-property-p)
14893 (error "Not at a property"))
14894 (let ((prop (org-match-string-no-properties 2)))
14895 (org-columns-get-format-and-top-level)
14896 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14897 (error "No operator defined for property %s" prop))
14898 (org-columns-compute prop)))
14900 (defvar org-property-allowed-value-functions nil
14901 "Hook for functions supplying allowed values for a specific property.
14902 The functions must take a single argument, the name of the property, and
14903 return a flat list of allowed values. If \":ETC\" is one of
14904 the values, this means that these values are intended as defaults for
14905 completion, but that other values should be allowed too.
14906 The functions must return nil if they are not responsible for this
14907 property.")
14909 (defun org-property-get-allowed-values (pom property &optional table)
14910 "Get allowed values for the property PROPERTY.
14911 When TABLE is non-nil, return an alist that can directly be used for
14912 completion."
14913 (let (vals)
14914 (cond
14915 ((equal property "TODO")
14916 (setq vals (org-with-point-at pom
14917 (append org-todo-keywords-1 '("")))))
14918 ((equal property "PRIORITY")
14919 (let ((n org-lowest-priority))
14920 (while (>= n org-highest-priority)
14921 (push (char-to-string n) vals)
14922 (setq n (1- n)))))
14923 ((member property org-special-properties))
14924 ((setq vals (run-hook-with-args-until-success
14925 'org-property-allowed-value-functions property)))
14927 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14928 (when (and vals (string-match "\\S-" vals))
14929 (setq vals (car (read-from-string (concat "(" vals ")"))))
14930 (setq vals (mapcar (lambda (x)
14931 (cond ((stringp x) x)
14932 ((numberp x) (number-to-string x))
14933 ((symbolp x) (symbol-name x))
14934 (t "???")))
14935 vals)))))
14936 (when (member ":ETC" vals)
14937 (setq vals (remove ":ETC" vals))
14938 (org-add-props (car vals) '(org-unrestricted t)))
14939 (if table (mapcar 'list vals) vals)))
14941 (defun org-property-previous-allowed-value (&optional previous)
14942 "Switch to the next allowed value for this property."
14943 (interactive)
14944 (org-property-next-allowed-value t))
14946 (defun org-property-next-allowed-value (&optional previous)
14947 "Switch to the next allowed value for this property."
14948 (interactive)
14949 (unless (org-at-property-p)
14950 (error "Not at a property"))
14951 (let* ((key (match-string 2))
14952 (value (match-string 3))
14953 (allowed (or (org-property-get-allowed-values (point) key)
14954 (and (member value '("[ ]" "[-]" "[X]"))
14955 '("[ ]" "[X]"))))
14956 nval)
14957 (unless allowed
14958 (error "Allowed values for this property have not been defined"))
14959 (if previous (setq allowed (reverse allowed)))
14960 (if (member value allowed)
14961 (setq nval (car (cdr (member value allowed)))))
14962 (setq nval (or nval (car allowed)))
14963 (if (equal nval value)
14964 (error "Only one allowed value for this property"))
14965 (org-at-property-p)
14966 (replace-match (concat " :" key ": " nval) t t)
14967 (org-indent-line)
14968 (beginning-of-line 1)
14969 (skip-chars-forward " \t")
14970 (run-hook-with-args 'org-property-changed-functions key nval)))
14972 (defun org-find-olp (path &optional this-buffer)
14973 "Return a marker pointing to the entry at outline path OLP.
14974 If anything goes wrong, throw an error.
14975 You can wrap this call to catch the error like this:
14977 (condition-case msg
14978 (org-mobile-locate-entry (match-string 4))
14979 (error (nth 1 msg)))
14981 The return value will then be either a string with the error message,
14982 or a marker if everything is OK.
14984 If THIS-BUFFER is set, the outline path does not contain a file,
14985 only headings."
14986 (let* ((file (if this-buffer buffer-file-name (pop path)))
14987 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14988 (level 1)
14989 (lmin 1)
14990 (lmax 1)
14991 limit re end found pos heading cnt flevel)
14992 (unless buffer (error "File not found :%s" file))
14993 (with-current-buffer buffer
14994 (save-excursion
14995 (save-restriction
14996 (widen)
14997 (setq limit (point-max))
14998 (goto-char (point-min))
14999 (while (setq heading (pop path))
15000 (setq re (format org-complex-heading-regexp-format
15001 (regexp-quote heading)))
15002 (setq cnt 0 pos (point))
15003 (while (re-search-forward re end t)
15004 (setq level (- (match-end 1) (match-beginning 1)))
15005 (if (and (>= level lmin) (<= level lmax))
15006 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15007 (when (= cnt 0) (error "Heading not found on level %d: %s"
15008 lmax heading))
15009 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15010 lmax heading))
15011 (goto-char found)
15012 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15013 (setq end (save-excursion (org-end-of-subtree t t))))
15014 (when (org-at-heading-p)
15015 (move-marker (make-marker) (point))))))))
15017 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15018 "Find node HEADING in BUFFER.
15019 Return a marker to the heading if it was found, or nil if not.
15020 If POS-ONLY is set, return just the position instead of a marker.
15022 The heading text must match exact, but it may have a TODO keyword,
15023 a priority cookie and tags in the standard locations."
15024 (with-current-buffer (or buffer (current-buffer))
15025 (save-excursion
15026 (save-restriction
15027 (widen)
15028 (goto-char (point-min))
15029 (let (case-fold-search)
15030 (if (re-search-forward
15031 (format org-complex-heading-regexp-format
15032 (regexp-quote heading)) nil t)
15033 (if pos-only
15034 (match-beginning 0)
15035 (move-marker (make-marker) (match-beginning 0)))))))))
15037 (defun org-find-exact-heading-in-directory (heading &optional dir)
15038 "Find Org node headline HEADING in all .org files in directory DIR.
15039 When the target headline is found, return a marker to this location."
15040 (let ((files (directory-files (or dir default-directory)
15041 nil "\\`[^.#].*\\.org\\'"))
15042 file visiting m buffer)
15043 (catch 'found
15044 (while (setq file (pop files))
15045 (message "trying %s" file)
15046 (setq visiting (org-find-base-buffer-visiting file))
15047 (setq buffer (or visiting (find-file-noselect file)))
15048 (setq m (org-find-exact-headline-in-buffer
15049 heading buffer))
15050 (when (and (not m) (not visiting)) (kill-buffer buffer))
15051 (and m (throw 'found m))))))
15053 (defun org-find-entry-with-id (ident)
15054 "Locate the entry that contains the ID property with exact value IDENT.
15055 IDENT can be a string, a symbol or a number, this function will search for
15056 the string representation of it.
15057 Return the position where this entry starts, or nil if there is no such entry."
15058 (interactive "sID: ")
15059 (let ((id (cond
15060 ((stringp ident) ident)
15061 ((symbol-name ident) (symbol-name ident))
15062 ((numberp ident) (number-to-string ident))
15063 (t (error "IDENT %s must be a string, symbol or number" ident))))
15064 (case-fold-search nil))
15065 (save-excursion
15066 (save-restriction
15067 (widen)
15068 (goto-char (point-min))
15069 (when (re-search-forward
15070 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15071 nil t)
15072 (org-back-to-heading t)
15073 (point))))))
15075 ;;;; Timestamps
15077 (defvar org-last-changed-timestamp nil)
15078 (defvar org-last-inserted-timestamp nil
15079 "The last time stamp inserted with `org-insert-time-stamp'.")
15080 (defvar org-time-was-given) ; dynamically scoped parameter
15081 (defvar org-end-time-was-given) ; dynamically scoped parameter
15082 (defvar org-ts-what) ; dynamically scoped parameter
15084 (defun org-time-stamp (arg &optional inactive)
15085 "Prompt for a date/time and insert a time stamp.
15086 If the user specifies a time like HH:MM or if this command is
15087 called with at least one prefix argument, the time stamp contains
15088 the date and the time. Otherwise, only the date is be included.
15090 All parts of a date not specified by the user is filled in from
15091 the current date/time. So if you just press return without
15092 typing anything, the time stamp will represent the current
15093 date/time.
15095 If there is already a timestamp at the cursor, it will be
15096 modified.
15098 With two universal prefix arguments, insert an active timestamp
15099 with the current time without prompting the user."
15100 (interactive "P")
15101 (let* ((ts nil)
15102 (default-time
15103 ;; Default time is either today, or, when entering a range,
15104 ;; the range start.
15105 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15106 (save-excursion
15107 (re-search-backward
15108 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15109 (- (point) 20) t)))
15110 (apply 'encode-time (org-parse-time-string (match-string 1)))
15111 (current-time)))
15112 (default-input (and ts (org-get-compact-tod ts)))
15113 (repeater (save-excursion
15114 (save-match-data
15115 (beginning-of-line)
15116 (when (re-search-forward
15117 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15118 (save-excursion (progn (end-of-line) (point))) t)
15119 (match-string 0)))))
15120 org-time-was-given org-end-time-was-given time)
15121 (cond
15122 ((and (org-at-timestamp-p t)
15123 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15124 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15125 (insert "--")
15126 (setq time (let ((this-command this-command))
15127 (org-read-date arg 'totime nil nil
15128 default-time default-input inactive)))
15129 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15130 ((org-at-timestamp-p t)
15131 (setq time (let ((this-command this-command))
15132 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15133 (when (org-at-timestamp-p t) ; just to get the match data
15134 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15135 (replace-match "")
15136 (setq org-last-changed-timestamp
15137 (org-insert-time-stamp
15138 time (or org-time-was-given arg)
15139 inactive nil nil (list org-end-time-was-given)))
15140 (when repeater (goto-char (1- (point))) (insert " " repeater)
15141 (setq org-last-changed-timestamp
15142 (concat (substring org-last-inserted-timestamp 0 -1)
15143 " " repeater ">"))))
15144 (message "Timestamp updated"))
15145 ((equal arg '(16))
15146 (org-insert-time-stamp (current-time) t))
15148 (setq time (let ((this-command this-command))
15149 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15150 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15151 nil nil (list org-end-time-was-given))))))
15153 ;; FIXME: can we use this for something else, like computing time differences?
15154 (defun org-get-compact-tod (s)
15155 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15156 (let* ((t1 (match-string 1 s))
15157 (h1 (string-to-number (match-string 2 s)))
15158 (m1 (string-to-number (match-string 3 s)))
15159 (t2 (and (match-end 4) (match-string 5 s)))
15160 (h2 (and t2 (string-to-number (match-string 6 s))))
15161 (m2 (and t2 (string-to-number (match-string 7 s))))
15162 dh dm)
15163 (if (not t2)
15165 (setq dh (- h2 h1) dm (- m2 m1))
15166 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15167 (concat t1 "+" (number-to-string dh)
15168 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15170 (defun org-time-stamp-inactive (&optional arg)
15171 "Insert an inactive time stamp.
15172 An inactive time stamp is enclosed in square brackets instead of angle
15173 brackets. It is inactive in the sense that it does not trigger agenda entries,
15174 does not link to the calendar and cannot be changed with the S-cursor keys.
15175 So these are more for recording a certain time/date."
15176 (interactive "P")
15177 (org-time-stamp arg 'inactive))
15179 (defvar org-date-ovl (make-overlay 1 1))
15180 (overlay-put org-date-ovl 'face 'org-date-selected)
15181 (org-detach-overlay org-date-ovl)
15183 (defvar org-ans1) ; dynamically scoped parameter
15184 (defvar org-ans2) ; dynamically scoped parameter
15186 (defvar org-plain-time-of-day-regexp) ; defined below
15188 (defvar org-overriding-default-time nil) ; dynamically scoped
15189 (defvar org-read-date-overlay nil)
15190 (defvar org-dcst nil) ; dynamically scoped
15191 (defvar org-read-date-history nil)
15192 (defvar org-read-date-final-answer nil)
15193 (defvar org-read-date-analyze-futurep nil)
15194 (defvar org-read-date-analyze-forced-year nil)
15195 (defvar org-read-date-inactive)
15197 (defun org-read-date (&optional org-with-time to-time from-string prompt
15198 default-time default-input inactive)
15199 "Read a date, possibly a time, and make things smooth for the user.
15200 The prompt will suggest to enter an ISO date, but you can also enter anything
15201 which will at least partially be understood by `parse-time-string'.
15202 Unrecognized parts of the date will default to the current day, month, year,
15203 hour and minute. If this command is called to replace a timestamp at point,
15204 or to enter the second timestamp of a range, the default time is taken
15205 from the existing stamp. Furthermore, the command prefers the future,
15206 so if you are giving a date where the year is not given, and the day-month
15207 combination is already past in the current year, it will assume you
15208 mean next year. For details, see the manual. A few examples:
15210 3-2-5 --> 2003-02-05
15211 feb 15 --> currentyear-02-15
15212 2/15 --> currentyear-02-15
15213 sep 12 9 --> 2009-09-12
15214 12:45 --> today 12:45
15215 22 sept 0:34 --> currentyear-09-22 0:34
15216 12 --> currentyear-currentmonth-12
15217 Fri --> nearest Friday (today or later)
15218 etc.
15220 Furthermore you can specify a relative date by giving, as the *first* thing
15221 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15222 change in days weeks, months, years.
15223 With a single plus or minus, the date is relative to today. With a double
15224 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15225 +4d --> four days from today
15226 +4 --> same as above
15227 +2w --> two weeks from today
15228 ++5 --> five days from default date
15230 The function understands only English month and weekday abbreviations.
15232 While prompting, a calendar is popped up - you can also select the
15233 date with the mouse (button 1). The calendar shows a period of three
15234 months. To scroll it to other months, use the keys `>' and `<'.
15235 If you don't like the calendar, turn it off with
15236 \(setq org-read-date-popup-calendar nil)
15238 With optional argument TO-TIME, the date will immediately be converted
15239 to an internal time.
15240 With an optional argument WITH-TIME, the prompt will suggest to also
15241 insert a time. Note that when WITH-TIME is not set, you can still
15242 enter a time, and this function will inform the calling routine about
15243 this change. The calling routine may then choose to change the format
15244 used to insert the time stamp into the buffer to include the time.
15245 With optional argument FROM-STRING, read from this string instead from
15246 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15247 the time/date that is used for everything that is not specified by the
15248 user."
15249 (require 'parse-time)
15250 (let* ((org-time-stamp-rounding-minutes
15251 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15252 (org-dcst org-display-custom-times)
15253 (ct (org-current-time))
15254 (org-def (or org-overriding-default-time default-time ct))
15255 (org-defdecode (decode-time org-def))
15256 (dummy (progn
15257 (when (< (nth 2 org-defdecode) org-extend-today-until)
15258 (setcar (nthcdr 2 org-defdecode) -1)
15259 (setcar (nthcdr 1 org-defdecode) 59)
15260 (setq org-def (apply 'encode-time org-defdecode)
15261 org-defdecode (decode-time org-def)))))
15262 (calendar-frame-setup nil)
15263 (calendar-setup nil)
15264 (calendar-move-hook nil)
15265 (calendar-view-diary-initially-flag nil)
15266 (calendar-view-holidays-initially-flag nil)
15267 (timestr (format-time-string
15268 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15269 (prompt (concat (if prompt (concat prompt " ") "")
15270 (format "Date+time [%s]: " timestr)))
15271 ans (org-ans0 "") org-ans1 org-ans2 final)
15273 (cond
15274 (from-string (setq ans from-string))
15275 (org-read-date-popup-calendar
15276 (save-excursion
15277 (save-window-excursion
15278 (calendar)
15279 (org-eval-in-calendar '(setq cursor-type nil) t)
15280 (unwind-protect
15281 (progn
15282 (calendar-forward-day (- (time-to-days org-def)
15283 (calendar-absolute-from-gregorian
15284 (calendar-current-date))))
15285 (org-eval-in-calendar nil t)
15286 (let* ((old-map (current-local-map))
15287 (map (copy-keymap calendar-mode-map))
15288 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15289 (org-defkey map (kbd "RET") 'org-calendar-select)
15290 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15291 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15292 (org-defkey minibuffer-local-map [(meta shift left)]
15293 (lambda () (interactive)
15294 (org-eval-in-calendar '(calendar-backward-month 1))))
15295 (org-defkey minibuffer-local-map [(meta shift right)]
15296 (lambda () (interactive)
15297 (org-eval-in-calendar '(calendar-forward-month 1))))
15298 (org-defkey minibuffer-local-map [(meta shift up)]
15299 (lambda () (interactive)
15300 (org-eval-in-calendar '(calendar-backward-year 1))))
15301 (org-defkey minibuffer-local-map [(meta shift down)]
15302 (lambda () (interactive)
15303 (org-eval-in-calendar '(calendar-forward-year 1))))
15304 (org-defkey minibuffer-local-map [?\e (shift left)]
15305 (lambda () (interactive)
15306 (org-eval-in-calendar '(calendar-backward-month 1))))
15307 (org-defkey minibuffer-local-map [?\e (shift right)]
15308 (lambda () (interactive)
15309 (org-eval-in-calendar '(calendar-forward-month 1))))
15310 (org-defkey minibuffer-local-map [?\e (shift up)]
15311 (lambda () (interactive)
15312 (org-eval-in-calendar '(calendar-backward-year 1))))
15313 (org-defkey minibuffer-local-map [?\e (shift down)]
15314 (lambda () (interactive)
15315 (org-eval-in-calendar '(calendar-forward-year 1))))
15316 (org-defkey minibuffer-local-map [(shift up)]
15317 (lambda () (interactive)
15318 (org-eval-in-calendar '(calendar-backward-week 1))))
15319 (org-defkey minibuffer-local-map [(shift down)]
15320 (lambda () (interactive)
15321 (org-eval-in-calendar '(calendar-forward-week 1))))
15322 (org-defkey minibuffer-local-map [(shift left)]
15323 (lambda () (interactive)
15324 (org-eval-in-calendar '(calendar-backward-day 1))))
15325 (org-defkey minibuffer-local-map [(shift right)]
15326 (lambda () (interactive)
15327 (org-eval-in-calendar '(calendar-forward-day 1))))
15328 (org-defkey minibuffer-local-map ">"
15329 (lambda () (interactive)
15330 (org-eval-in-calendar '(scroll-calendar-left 1))))
15331 (org-defkey minibuffer-local-map "<"
15332 (lambda () (interactive)
15333 (org-eval-in-calendar '(scroll-calendar-right 1))))
15334 (org-defkey minibuffer-local-map "\C-v"
15335 (lambda () (interactive)
15336 (org-eval-in-calendar
15337 '(calendar-scroll-left-three-months 1))))
15338 (org-defkey minibuffer-local-map "\M-v"
15339 (lambda () (interactive)
15340 (org-eval-in-calendar
15341 '(calendar-scroll-right-three-months 1))))
15342 (run-hooks 'org-read-date-minibuffer-setup-hook)
15343 (unwind-protect
15344 (progn
15345 (use-local-map map)
15346 (setq org-read-date-inactive inactive)
15347 (add-hook 'post-command-hook 'org-read-date-display)
15348 (setq org-ans0 (read-string prompt default-input
15349 'org-read-date-history nil))
15350 ;; org-ans0: from prompt
15351 ;; org-ans1: from mouse click
15352 ;; org-ans2: from calendar motion
15353 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15354 (remove-hook 'post-command-hook 'org-read-date-display)
15355 (use-local-map old-map)
15356 (when org-read-date-overlay
15357 (delete-overlay org-read-date-overlay)
15358 (setq org-read-date-overlay nil)))))
15359 (bury-buffer "*Calendar*")))))
15361 (t ; Naked prompt only
15362 (unwind-protect
15363 (setq ans (read-string prompt default-input
15364 'org-read-date-history timestr))
15365 (when org-read-date-overlay
15366 (delete-overlay org-read-date-overlay)
15367 (setq org-read-date-overlay nil)))))
15369 (setq final (org-read-date-analyze ans org-def org-defdecode))
15371 (when org-read-date-analyze-forced-year
15372 (message "Year was forced into %s"
15373 (if org-read-date-force-compatible-dates
15374 "compatible range (1970-2037)"
15375 "range representable on this machine"))
15376 (ding))
15378 ;; One round trip to get rid of 34th of August and stuff like that....
15379 (setq final (decode-time (apply 'encode-time final)))
15381 (setq org-read-date-final-answer ans)
15383 (if to-time
15384 (apply 'encode-time final)
15385 (if (and (boundp 'org-time-was-given) org-time-was-given)
15386 (format "%04d-%02d-%02d %02d:%02d"
15387 (nth 5 final) (nth 4 final) (nth 3 final)
15388 (nth 2 final) (nth 1 final))
15389 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15391 (defvar org-def)
15392 (defvar org-defdecode)
15393 (defvar org-with-time)
15394 (defun org-read-date-display ()
15395 "Display the current date prompt interpretation in the minibuffer."
15396 (when org-read-date-display-live
15397 (when org-read-date-overlay
15398 (delete-overlay org-read-date-overlay))
15399 (when (minibufferp (current-buffer))
15400 (save-excursion
15401 (end-of-line 1)
15402 (while (not (equal (buffer-substring
15403 (max (point-min) (- (point) 4)) (point))
15404 " "))
15405 (insert " ")))
15406 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15407 " " (or org-ans1 org-ans2)))
15408 (org-end-time-was-given nil)
15409 (f (org-read-date-analyze ans org-def org-defdecode))
15410 (fmts (if org-dcst
15411 org-time-stamp-custom-formats
15412 org-time-stamp-formats))
15413 (fmt (if (or org-with-time
15414 (and (boundp 'org-time-was-given) org-time-was-given))
15415 (cdr fmts)
15416 (car fmts)))
15417 (txt (format-time-string fmt (apply 'encode-time f)))
15418 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15419 (txt (concat "=> " txt)))
15420 (when (and org-end-time-was-given
15421 (string-match org-plain-time-of-day-regexp txt))
15422 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15423 org-end-time-was-given
15424 (substring txt (match-end 0)))))
15425 (when org-read-date-analyze-futurep
15426 (setq txt (concat txt " (=>F)")))
15427 (setq org-read-date-overlay
15428 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15429 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15431 (defun org-read-date-analyze (ans org-def org-defdecode)
15432 "Analyze the combined answer of the date prompt."
15433 ;; FIXME: cleanup and comment
15434 (let ((nowdecode (decode-time (current-time)))
15435 delta deltan deltaw deltadef year month day
15436 hour minute second wday pm h2 m2 tl wday1
15437 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15438 (setq org-read-date-analyze-futurep nil
15439 org-read-date-analyze-forced-year nil)
15440 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15441 (setq ans "+0"))
15443 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15444 (setq ans (replace-match "" t t ans)
15445 deltan (car delta)
15446 deltaw (nth 1 delta)
15447 deltadef (nth 2 delta)))
15449 ;; Check if there is an iso week date in there
15450 ;; If yes, store the info and postpone interpreting it until the rest
15451 ;; of the parsing is done
15452 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15453 (setq iso-year (if (match-end 1)
15454 (org-small-year-to-year
15455 (string-to-number (match-string 1 ans))))
15456 iso-weekday (if (match-end 3)
15457 (string-to-number (match-string 3 ans)))
15458 iso-week (string-to-number (match-string 2 ans)))
15459 (setq ans (replace-match "" t t ans)))
15461 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15462 (when (string-match
15463 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15464 (setq year (if (match-end 2)
15465 (string-to-number (match-string 2 ans))
15466 (progn (setq kill-year t)
15467 (string-to-number (format-time-string "%Y"))))
15468 month (string-to-number (match-string 3 ans))
15469 day (string-to-number (match-string 4 ans)))
15470 (if (< year 100) (setq year (+ 2000 year)))
15471 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15472 t nil ans)))
15474 ;; Help matching dotted european dates
15475 (when (string-match
15476 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15477 (setq year (if (match-end 3)
15478 (string-to-number (match-string 3 ans))
15479 (progn (setq kill-year t)
15480 (string-to-number (format-time-string "%Y"))))
15481 day (string-to-number (match-string 1 ans))
15482 month (string-to-number (match-string 2 ans))
15483 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15484 t nil ans)))
15486 ;; Help matching american dates, like 5/30 or 5/30/7
15487 (when (string-match
15488 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15489 (setq year (if (match-end 4)
15490 (string-to-number (match-string 4 ans))
15491 (progn (setq kill-year t)
15492 (string-to-number (format-time-string "%Y"))))
15493 month (string-to-number (match-string 1 ans))
15494 day (string-to-number (match-string 2 ans)))
15495 (if (< year 100) (setq year (+ 2000 year)))
15496 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15497 t nil ans)))
15498 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15499 ;; If there is a time with am/pm, and *no* time without it, we convert
15500 ;; so that matching will be successful.
15501 (loop for i from 1 to 2 do ; twice, for end time as well
15502 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15503 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15504 (setq hour (string-to-number (match-string 1 ans))
15505 minute (if (match-end 3)
15506 (string-to-number (match-string 3 ans))
15508 pm (equal ?p
15509 (string-to-char (downcase (match-string 4 ans)))))
15510 (if (and (= hour 12) (not pm))
15511 (setq hour 0)
15512 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15513 (setq ans (replace-match (format "%02d:%02d" hour minute)
15514 t t ans))))
15516 ;; Check if a time range is given as a duration
15517 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15518 (setq hour (string-to-number (match-string 1 ans))
15519 h2 (+ hour (string-to-number (match-string 3 ans)))
15520 minute (string-to-number (match-string 2 ans))
15521 m2 (+ minute (if (match-end 5) (string-to-number
15522 (match-string 5 ans))0)))
15523 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15524 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15525 t t ans)))
15527 ;; Check if there is a time range
15528 (when (boundp 'org-end-time-was-given)
15529 (setq org-time-was-given nil)
15530 (when (and (string-match org-plain-time-of-day-regexp ans)
15531 (match-end 8))
15532 (setq org-end-time-was-given (match-string 8 ans))
15533 (setq ans (concat (substring ans 0 (match-beginning 7))
15534 (substring ans (match-end 7))))))
15536 (setq tl (parse-time-string ans)
15537 day (or (nth 3 tl) (nth 3 org-defdecode))
15538 month (or (nth 4 tl)
15539 (if (and org-read-date-prefer-future
15540 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15541 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15542 (nth 4 org-defdecode)))
15543 year (or (and (not kill-year) (nth 5 tl))
15544 (if (and org-read-date-prefer-future
15545 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15546 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15547 (nth 5 org-defdecode)))
15548 hour (or (nth 2 tl) (nth 2 org-defdecode))
15549 minute (or (nth 1 tl) (nth 1 org-defdecode))
15550 second (or (nth 0 tl) 0)
15551 wday (nth 6 tl))
15553 (when (and (eq org-read-date-prefer-future 'time)
15554 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15555 (equal day (nth 3 nowdecode))
15556 (equal month (nth 4 nowdecode))
15557 (equal year (nth 5 nowdecode))
15558 (nth 2 tl)
15559 (or (< (nth 2 tl) (nth 2 nowdecode))
15560 (and (= (nth 2 tl) (nth 2 nowdecode))
15561 (nth 1 tl)
15562 (< (nth 1 tl) (nth 1 nowdecode)))))
15563 (setq day (1+ day)
15564 futurep t))
15566 ;; Special date definitions below
15567 (cond
15568 (iso-week
15569 ;; There was an iso week
15570 (require 'cal-iso)
15571 (setq futurep nil)
15572 (setq year (or iso-year year)
15573 day (or iso-weekday wday 1)
15574 wday nil ; to make sure that the trigger below does not match
15575 iso-date (calendar-gregorian-from-absolute
15576 (calendar-absolute-from-iso
15577 (list iso-week day year))))
15578 ; FIXME: Should we also push ISO weeks into the future?
15579 ; (when (and org-read-date-prefer-future
15580 ; (not iso-year)
15581 ; (< (calendar-absolute-from-gregorian iso-date)
15582 ; (time-to-days (current-time))))
15583 ; (setq year (1+ year)
15584 ; iso-date (calendar-gregorian-from-absolute
15585 ; (calendar-absolute-from-iso
15586 ; (list iso-week day year)))))
15587 (setq month (car iso-date)
15588 year (nth 2 iso-date)
15589 day (nth 1 iso-date)))
15590 (deltan
15591 (setq futurep nil)
15592 (unless deltadef
15593 (let ((now (decode-time (current-time))))
15594 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15595 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15596 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15597 ((equal deltaw "m") (setq month (+ month deltan)))
15598 ((equal deltaw "y") (setq year (+ year deltan)))))
15599 ((and wday (not (nth 3 tl)))
15600 (setq futurep nil)
15601 ;; Weekday was given, but no day, so pick that day in the week
15602 ;; on or after the derived date.
15603 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15604 (unless (equal wday wday1)
15605 (setq day (+ day (% (- wday wday1 -7) 7))))))
15606 (if (and (boundp 'org-time-was-given)
15607 (nth 2 tl))
15608 (setq org-time-was-given t))
15609 (if (< year 100) (setq year (+ 2000 year)))
15610 ;; Check of the date is representable
15611 (if org-read-date-force-compatible-dates
15612 (progn
15613 (if (< year 1970)
15614 (setq year 1970 org-read-date-analyze-forced-year t))
15615 (if (> year 2037)
15616 (setq year 2037 org-read-date-analyze-forced-year t)))
15617 (condition-case nil
15618 (ignore (encode-time second minute hour day month year))
15619 (error
15620 (setq year (nth 5 org-defdecode))
15621 (setq org-read-date-analyze-forced-year t))))
15622 (setq org-read-date-analyze-futurep futurep)
15623 (list second minute hour day month year)))
15625 (defvar parse-time-weekdays)
15626 (defun org-read-date-get-relative (s today default)
15627 "Check string S for special relative date string.
15628 TODAY and DEFAULT are internal times, for today and for a default.
15629 Return shift list (N what def-flag)
15630 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15631 N is the number of WHATs to shift.
15632 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15633 the DEFAULT date rather than TODAY."
15634 (require 'parse-time)
15635 (when (and
15636 (string-match
15637 (concat
15638 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15639 "\\([0-9]+\\)?"
15640 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15641 "\\([ \t]\\|$\\)") s)
15642 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15643 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15644 (string-to-char (substring (match-string 1 s) -1))
15645 ?+))
15646 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15647 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15648 (what (if (match-end 3) (match-string 3 s) "d"))
15649 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15650 (date (if rel default today))
15651 (wday (nth 6 (decode-time date)))
15652 delta)
15653 (if wday1
15654 (progn
15655 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15656 (if (= dir ?-) (setq delta (- delta 7)))
15657 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15658 (list delta "d" rel))
15659 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15661 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15662 "Turn a user-specified date into the internal representation.
15663 The internal representation needed by the calendar is (month day year).
15664 This is a wrapper to handle the brain-dead convention in calendar that
15665 user function argument order change dependent on argument order."
15666 (if (boundp 'calendar-date-style)
15667 (cond
15668 ((eq calendar-date-style 'american)
15669 (list arg1 arg2 arg3))
15670 ((eq calendar-date-style 'european)
15671 (list arg2 arg1 arg3))
15672 ((eq calendar-date-style 'iso)
15673 (list arg2 arg3 arg1)))
15674 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15675 (if (org-bound-and-true-p european-calendar-style)
15676 (list arg2 arg1 arg3)
15677 (list arg1 arg2 arg3)))))
15679 (defun org-eval-in-calendar (form &optional keepdate)
15680 "Eval FORM in the calendar window and return to current window.
15681 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15682 otherwise stick to the current value of `org-ans2'."
15683 (let ((sf (selected-frame))
15684 (sw (selected-window)))
15685 (select-window (get-buffer-window "*Calendar*" t))
15686 (eval form)
15687 (when (and (not keepdate) (calendar-cursor-to-date))
15688 (let* ((date (calendar-cursor-to-date))
15689 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15690 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15691 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15692 (select-window sw)
15693 (org-select-frame-set-input-focus sf)))
15695 (defun org-calendar-select ()
15696 "Return to `org-read-date' with the date currently selected.
15697 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15698 (interactive)
15699 (when (calendar-cursor-to-date)
15700 (let* ((date (calendar-cursor-to-date))
15701 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15702 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15703 (if (active-minibuffer-window) (exit-minibuffer))))
15705 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15706 "Insert a date stamp for the date given by the internal TIME.
15707 WITH-HM means use the stamp format that includes the time of the day.
15708 INACTIVE means use square brackets instead of angular ones, so that the
15709 stamp will not contribute to the agenda.
15710 PRE and POST are optional strings to be inserted before and after the
15711 stamp.
15712 The command returns the inserted time stamp."
15713 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15714 stamp)
15715 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15716 (insert-before-markers (or pre ""))
15717 (when (listp extra)
15718 (setq extra (car extra))
15719 (if (and (stringp extra)
15720 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15721 (setq extra (format "-%02d:%02d"
15722 (string-to-number (match-string 1 extra))
15723 (string-to-number (match-string 2 extra))))
15724 (setq extra nil)))
15725 (when extra
15726 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15727 (insert-before-markers (setq stamp (format-time-string fmt time)))
15728 (insert-before-markers (or post ""))
15729 (setq org-last-inserted-timestamp stamp)))
15731 (defun org-toggle-time-stamp-overlays ()
15732 "Toggle the use of custom time stamp formats."
15733 (interactive)
15734 (setq org-display-custom-times (not org-display-custom-times))
15735 (unless org-display-custom-times
15736 (let ((p (point-min)) (bmp (buffer-modified-p)))
15737 (while (setq p (next-single-property-change p 'display))
15738 (if (and (get-text-property p 'display)
15739 (eq (get-text-property p 'face) 'org-date))
15740 (remove-text-properties
15741 p (setq p (next-single-property-change p 'display))
15742 '(display t))))
15743 (set-buffer-modified-p bmp)))
15744 (if (featurep 'xemacs)
15745 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15746 (org-restart-font-lock)
15747 (setq org-table-may-need-update t)
15748 (if org-display-custom-times
15749 (message "Time stamps are overlaid with custom format")
15750 (message "Time stamp overlays removed")))
15752 (defun org-display-custom-time (beg end)
15753 "Overlay modified time stamp format over timestamp between BEG and END."
15754 (let* ((ts (buffer-substring beg end))
15755 t1 w1 with-hm tf time str w2 (off 0))
15756 (save-match-data
15757 (setq t1 (org-parse-time-string ts t))
15758 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15759 (setq off (- (match-end 0) (match-beginning 0)))))
15760 (setq end (- end off))
15761 (setq w1 (- end beg)
15762 with-hm (and (nth 1 t1) (nth 2 t1))
15763 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15764 time (org-fix-decoded-time t1)
15765 str (org-add-props
15766 (format-time-string
15767 (substring tf 1 -1) (apply 'encode-time time))
15768 nil 'mouse-face 'highlight)
15769 w2 (length str))
15770 (if (not (= w2 w1))
15771 (add-text-properties (1+ beg) (+ 2 beg)
15772 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15773 (if (featurep 'xemacs)
15774 (progn
15775 (put-text-property beg end 'invisible t)
15776 (put-text-property beg end 'end-glyph (make-glyph str)))
15777 (put-text-property beg end 'display str))))
15779 (defun org-translate-time (string)
15780 "Translate all timestamps in STRING to custom format.
15781 But do this only if the variable `org-display-custom-times' is set."
15782 (when org-display-custom-times
15783 (save-match-data
15784 (let* ((start 0)
15785 (re org-ts-regexp-both)
15786 t1 with-hm inactive tf time str beg end)
15787 (while (setq start (string-match re string start))
15788 (setq beg (match-beginning 0)
15789 end (match-end 0)
15790 t1 (save-match-data
15791 (org-parse-time-string (substring string beg end) t))
15792 with-hm (and (nth 1 t1) (nth 2 t1))
15793 inactive (equal (substring string beg (1+ beg)) "[")
15794 tf (funcall (if with-hm 'cdr 'car)
15795 org-time-stamp-custom-formats)
15796 time (org-fix-decoded-time t1)
15797 str (format-time-string
15798 (concat
15799 (if inactive "[" "<") (substring tf 1 -1)
15800 (if inactive "]" ">"))
15801 (apply 'encode-time time))
15802 string (replace-match str t t string)
15803 start (+ start (length str)))))))
15804 string)
15806 (defun org-fix-decoded-time (time)
15807 "Set 0 instead of nil for the first 6 elements of time.
15808 Don't touch the rest."
15809 (let ((n 0))
15810 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15812 (defun org-days-to-time (timestamp-string)
15813 "Difference between TIMESTAMP-STRING and now in days."
15814 (- (time-to-days (org-time-string-to-time timestamp-string))
15815 (time-to-days (current-time))))
15817 (defun org-deadline-close (timestamp-string &optional ndays)
15818 "Is the time in TIMESTAMP-STRING close to the current date?"
15819 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15820 (and (< (org-days-to-time timestamp-string) ndays)
15821 (not (org-entry-is-done-p))))
15823 (defun org-get-wdays (ts)
15824 "Get the deadline lead time appropriate for timestring TS."
15825 (cond
15826 ((<= org-deadline-warning-days 0)
15827 ;; 0 or negative, enforce this value no matter what
15828 (- org-deadline-warning-days))
15829 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15830 ;; lead time is specified.
15831 (floor (* (string-to-number (match-string 1 ts))
15832 (cdr (assoc (match-string 2 ts)
15833 '(("d" . 1) ("w" . 7)
15834 ("m" . 30.4) ("y" . 365.25)))))))
15835 ;; go for the default.
15836 (t org-deadline-warning-days)))
15838 (defun org-calendar-select-mouse (ev)
15839 "Return to `org-read-date' with the date currently selected.
15840 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15841 (interactive "e")
15842 (mouse-set-point ev)
15843 (when (calendar-cursor-to-date)
15844 (let* ((date (calendar-cursor-to-date))
15845 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15846 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15847 (if (active-minibuffer-window) (exit-minibuffer))))
15849 (defun org-check-deadlines (ndays)
15850 "Check if there are any deadlines due or past due.
15851 A deadline is considered due if it happens within `org-deadline-warning-days'
15852 days from today's date. If the deadline appears in an entry marked DONE,
15853 it is not shown. The prefix arg NDAYS can be used to test that many
15854 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15855 (interactive "P")
15856 (let* ((org-warn-days
15857 (cond
15858 ((equal ndays '(4)) 100000)
15859 (ndays (prefix-numeric-value ndays))
15860 (t (abs org-deadline-warning-days))))
15861 (case-fold-search nil)
15862 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15863 (callback
15864 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15866 (message "%d deadlines past-due or due within %d days"
15867 (org-occur regexp nil callback)
15868 org-warn-days)))
15870 (defsubst org-re-timestamp (type)
15871 "Return a regexp for timestamp TYPE.
15872 Allowed values for TYPE are:
15874 all: all timestamps
15875 active: only active timestamps (<...>)
15876 inactive: only inactive timestamps ([...])
15877 scheduled: only scheduled timestamps
15878 deadline: only deadline timestamps
15880 When TYPE is nil, fall back on returning a regexp that matches
15881 both scheduled and deadline timestamps."
15882 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15883 ((eq type 'active) org-ts-regexp)
15884 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15885 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15886 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15887 ((eq type 'scheduled-or-deadline)
15888 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15890 (defun org-check-before-date (date)
15891 "Check if there are deadlines or scheduled entries before DATE."
15892 (interactive (list (org-read-date)))
15893 (let ((case-fold-search nil)
15894 (regexp (org-re-timestamp org-ts-type))
15895 (callback
15896 (lambda () (time-less-p
15897 (org-time-string-to-time (match-string 1))
15898 (org-time-string-to-time date)))))
15899 (message "%d entries before %s"
15900 (org-occur regexp nil callback) date)))
15902 (defun org-check-after-date (date)
15903 "Check if there are deadlines or scheduled entries after DATE."
15904 (interactive (list (org-read-date)))
15905 (let ((case-fold-search nil)
15906 (regexp (org-re-timestamp org-ts-type))
15907 (callback
15908 (lambda () (not
15909 (time-less-p
15910 (org-time-string-to-time (match-string 1))
15911 (org-time-string-to-time date))))))
15912 (message "%d entries after %s"
15913 (org-occur regexp nil callback) date)))
15915 (defun org-check-dates-range (start-date end-date)
15916 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15917 (interactive (list (org-read-date nil nil nil "Range starts")
15918 (org-read-date nil nil nil "Range end")))
15919 (let ((case-fold-search nil)
15920 (regexp (org-re-timestamp org-ts-type))
15921 (callback
15922 (lambda ()
15923 (let ((match (match-string 1)))
15924 (and
15925 (not (time-less-p
15926 (org-time-string-to-time match)
15927 (org-time-string-to-time start-date)))
15928 (time-less-p
15929 (org-time-string-to-time match)
15930 (org-time-string-to-time end-date)))))))
15931 (message "%d entries between %s and %s"
15932 (org-occur regexp nil callback) start-date end-date)))
15934 (defun org-evaluate-time-range (&optional to-buffer)
15935 "Evaluate a time range by computing the difference between start and end.
15936 Normally the result is just printed in the echo area, but with prefix arg
15937 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15938 If the time range is actually in a table, the result is inserted into the
15939 next column.
15940 For time difference computation, a year is assumed to be exactly 365
15941 days in order to avoid rounding problems."
15942 (interactive "P")
15944 (org-clock-update-time-maybe)
15945 (save-excursion
15946 (unless (org-at-date-range-p t)
15947 (goto-char (point-at-bol))
15948 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15949 (if (not (org-at-date-range-p t))
15950 (error "Not at a time-stamp range, and none found in current line")))
15951 (let* ((ts1 (match-string 1))
15952 (ts2 (match-string 2))
15953 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15954 (match-end (match-end 0))
15955 (time1 (org-time-string-to-time ts1))
15956 (time2 (org-time-string-to-time ts2))
15957 (t1 (org-float-time time1))
15958 (t2 (org-float-time time2))
15959 (diff (abs (- t2 t1)))
15960 (negative (< (- t2 t1) 0))
15961 ;; (ys (floor (* 365 24 60 60)))
15962 (ds (* 24 60 60))
15963 (hs (* 60 60))
15964 (fy "%dy %dd %02d:%02d")
15965 (fy1 "%dy %dd")
15966 (fd "%dd %02d:%02d")
15967 (fd1 "%dd")
15968 (fh "%02d:%02d")
15969 y d h m align)
15970 (if havetime
15971 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15973 d (floor (/ diff ds)) diff (mod diff ds)
15974 h (floor (/ diff hs)) diff (mod diff hs)
15975 m (floor (/ diff 60)))
15976 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15978 d (floor (+ (/ diff ds) 0.5))
15979 h 0 m 0))
15980 (if (not to-buffer)
15981 (message "%s" (org-make-tdiff-string y d h m))
15982 (if (org-at-table-p)
15983 (progn
15984 (goto-char match-end)
15985 (setq align t)
15986 (and (looking-at " *|") (goto-char (match-end 0))))
15987 (goto-char match-end))
15988 (if (looking-at
15989 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15990 (replace-match ""))
15991 (if negative (insert " -"))
15992 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15993 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15994 (insert " " (format fh h m))))
15995 (if align (org-table-align))
15996 (message "Time difference inserted")))))
15998 (defun org-make-tdiff-string (y d h m)
15999 (let ((fmt "")
16000 (l nil))
16001 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16002 l (push y l)))
16003 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16004 l (push d l)))
16005 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16006 l (push h l)))
16007 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16008 l (push m l)))
16009 (apply 'format fmt (nreverse l))))
16011 (defun org-time-string-to-time (s &optional buffer pos)
16012 (condition-case errdata
16013 (apply 'encode-time (org-parse-time-string s))
16014 (error (error "Bad timestamp `%s'%s\nError was: %s"
16015 s (if (not (and buffer pos))
16017 (format " at %d in buffer `%s'" pos buffer))
16018 (cdr errdata)))))
16020 (defun org-time-string-to-seconds (s)
16021 (org-float-time (org-time-string-to-time s)))
16023 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16024 "Convert a time stamp to an absolute day number.
16025 If there is a specifier for a cyclic time stamp, get the closest date to
16026 DAYNR.
16027 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16028 The variable date is bound by the calendar when this is called."
16029 (cond
16030 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16031 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16032 daynr
16033 (+ daynr 1000)))
16034 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16035 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16036 (time-to-days (current-time))) (match-string 0 s)
16037 prefer show-all))
16038 (t (time-to-days
16039 (condition-case errdata
16040 (apply 'encode-time (org-parse-time-string s))
16041 (error (error "Bad timestamp `%s'%s\nError was: %s"
16042 s (if (not (and buffer pos))
16044 (format " at %d in buffer `%s'" pos buffer))
16045 (cdr errdata))))))))
16047 (defun org-days-to-iso-week (days)
16048 "Return the iso week number."
16049 (require 'cal-iso)
16050 (car (calendar-iso-from-absolute days)))
16052 (defun org-small-year-to-year (year)
16053 "Convert 2-digit years into 4-digit years.
16054 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16055 The year 2000 cannot be abbreviated. Any year larger than 99
16056 is returned unchanged."
16057 (if (< year 38)
16058 (setq year (+ 2000 year))
16059 (if (< year 100)
16060 (setq year (+ 1900 year))))
16061 year)
16063 (defun org-time-from-absolute (d)
16064 "Return the time corresponding to date D.
16065 D may be an absolute day number, or a calendar-type list (month day year)."
16066 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16067 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16069 (defun org-calendar-holiday ()
16070 "List of holidays, for Diary display in Org-mode."
16071 (require 'holidays)
16072 (let ((hl (funcall
16073 (if (fboundp 'calendar-check-holidays)
16074 'calendar-check-holidays 'check-calendar-holidays) date)))
16075 (if hl (mapconcat 'identity hl "; "))))
16077 (defun org-diary-sexp-entry (sexp entry date)
16078 "Process a SEXP diary ENTRY for DATE."
16079 (require 'diary-lib)
16080 (let ((result (if calendar-debug-sexp
16081 (let ((stack-trace-on-error t))
16082 (eval (car (read-from-string sexp))))
16083 (condition-case nil
16084 (eval (car (read-from-string sexp)))
16085 (error
16086 (beep)
16087 (message "Bad sexp at line %d in %s: %s"
16088 (org-current-line)
16089 (buffer-file-name) sexp)
16090 (sleep-for 2))))))
16091 (cond ((stringp result) (split-string result "; "))
16092 ((and (consp result)
16093 (not (consp (cdr result)))
16094 (stringp (cdr result))) (cdr result))
16095 ((and (consp result)
16096 (stringp (car result))) result)
16097 (result entry)
16098 (t nil))))
16100 (defun org-diary-to-ical-string (frombuf)
16101 "Get iCalendar entries from diary entries in buffer FROMBUF.
16102 This uses the icalendar.el library."
16103 (let* ((tmpdir (if (featurep 'xemacs)
16104 (temp-directory)
16105 temporary-file-directory))
16106 (tmpfile (make-temp-name
16107 (expand-file-name "orgics" tmpdir)))
16108 buf rtn b e)
16109 (with-current-buffer frombuf
16110 (icalendar-export-region (point-min) (point-max) tmpfile)
16111 (setq buf (find-buffer-visiting tmpfile))
16112 (set-buffer buf)
16113 (goto-char (point-min))
16114 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16115 (setq b (match-beginning 0)))
16116 (goto-char (point-max))
16117 (if (re-search-backward "^END:VEVENT" nil t)
16118 (setq e (match-end 0)))
16119 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16120 (kill-buffer buf)
16121 (delete-file tmpfile)
16122 rtn))
16124 (defun org-closest-date (start current change prefer show-all)
16125 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16126 When PREFER is `past', return a date that is either CURRENT or past.
16127 When PREFER is `future', return a date that is either CURRENT or future.
16128 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16129 ;; Make the proper lists from the dates
16130 (catch 'exit
16131 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16132 dn dw sday cday n1 n2 n0
16133 d m y y1 y2 date1 date2 nmonths nm ny m2)
16135 (setq start (org-date-to-gregorian start)
16136 current (org-date-to-gregorian
16137 (if show-all
16138 current
16139 (time-to-days (current-time))))
16140 sday (calendar-absolute-from-gregorian start)
16141 cday (calendar-absolute-from-gregorian current))
16143 (if (<= cday sday) (throw 'exit sday))
16145 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16146 (setq dn (string-to-number (match-string 1 change))
16147 dw (cdr (assoc (match-string 2 change) a1)))
16148 (error "Invalid change specifier: %s" change))
16149 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16150 (cond
16151 ((eq dw 'day)
16152 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16153 n2 (+ n1 dn)))
16154 ((eq dw 'year)
16155 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16156 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16157 (setq date1 (list m d y1)
16158 n1 (calendar-absolute-from-gregorian date1)
16159 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16160 n2 (calendar-absolute-from-gregorian date2)))
16161 ((eq dw 'month)
16162 ;; approx number of month between the two dates
16163 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16164 ;; How often does dn fit in there?
16165 (setq d (nth 1 start) m (car start) y (nth 2 start)
16166 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16167 m (+ m nm)
16168 ny (floor (/ m 12))
16169 y (+ y ny)
16170 m (- m (* ny 12)))
16171 (while (> m 12) (setq m (- m 12) y (1+ y)))
16172 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16173 (setq m2 (+ m dn) y2 y)
16174 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16175 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16176 (while (<= n2 cday)
16177 (setq n1 n2 m m2 y y2)
16178 (setq m2 (+ m dn) y2 y)
16179 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16180 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16181 ;; Make sure n1 is the earlier date
16182 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16183 (if show-all
16184 (cond
16185 ((eq prefer 'past) (if (= cday n2) n2 n1))
16186 ((eq prefer 'future) (if (= cday n1) n1 n2))
16187 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16188 (cond
16189 ((eq prefer 'past) (if (= cday n2) n2 n1))
16190 ((eq prefer 'future) (if (= cday n1) n1 n2))
16191 (t (if (= cday n1) n1 n2)))))))
16193 (defun org-date-to-gregorian (date)
16194 "Turn any specification of DATE into a Gregorian date for the calendar."
16195 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16196 ((and (listp date) (= (length date) 3)) date)
16197 ((stringp date)
16198 (setq date (org-parse-time-string date))
16199 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16200 ((listp date)
16201 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16203 (defun org-parse-time-string (s &optional nodefault)
16204 "Parse the standard Org-mode time string.
16205 This should be a lot faster than the normal `parse-time-string'.
16206 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16207 hour and minute fields will be nil if not given."
16208 (if (string-match org-ts-regexp0 s)
16209 (list 0
16210 (if (or (match-beginning 8) (not nodefault))
16211 (string-to-number (or (match-string 8 s) "0")))
16212 (if (or (match-beginning 7) (not nodefault))
16213 (string-to-number (or (match-string 7 s) "0")))
16214 (string-to-number (match-string 4 s))
16215 (string-to-number (match-string 3 s))
16216 (string-to-number (match-string 2 s))
16217 nil nil nil)
16218 (error "Not a standard Org-mode time string: %s" s)))
16220 (defun org-timestamp-up (&optional arg)
16221 "Increase the date item at the cursor by one.
16222 If the cursor is on the year, change the year. If it is on the month,
16223 the day or the time, change that.
16224 With prefix ARG, change by that many units."
16225 (interactive "p")
16226 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16228 (defun org-timestamp-down (&optional arg)
16229 "Decrease the date item at the cursor by one.
16230 If the cursor is on the year, change the year. If it is on the month,
16231 the day or the time, change that.
16232 With prefix ARG, change by that many units."
16233 (interactive "p")
16234 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16236 (defun org-timestamp-up-day (&optional arg)
16237 "Increase the date in the time stamp by one day.
16238 With prefix ARG, change that many days."
16239 (interactive "p")
16240 (if (and (not (org-at-timestamp-p t))
16241 (org-at-heading-p))
16242 (org-todo 'up)
16243 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16245 (defun org-timestamp-down-day (&optional arg)
16246 "Decrease the date in the time stamp by one day.
16247 With prefix ARG, change that many days."
16248 (interactive "p")
16249 (if (and (not (org-at-timestamp-p t))
16250 (org-at-heading-p))
16251 (org-todo 'down)
16252 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16254 (defun org-at-timestamp-p (&optional inactive-ok)
16255 "Determine if the cursor is in or at a timestamp."
16256 (interactive)
16257 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16258 (pos (point))
16259 (ans (or (looking-at tsr)
16260 (save-excursion
16261 (skip-chars-backward "^[<\n\r\t")
16262 (if (> (point) (point-min)) (backward-char 1))
16263 (and (looking-at tsr)
16264 (> (- (match-end 0) pos) -1))))))
16265 (and ans
16266 (boundp 'org-ts-what)
16267 (setq org-ts-what
16268 (cond
16269 ((= pos (match-beginning 0)) 'bracket)
16270 ;; Point is considered to be "on the bracket" whether
16271 ;; it's really on it or right after it.
16272 ((= pos (1- (match-end 0))) 'bracket)
16273 ((= pos (match-end 0)) 'after)
16274 ((org-pos-in-match-range pos 2) 'year)
16275 ((org-pos-in-match-range pos 3) 'month)
16276 ((org-pos-in-match-range pos 7) 'hour)
16277 ((org-pos-in-match-range pos 8) 'minute)
16278 ((or (org-pos-in-match-range pos 4)
16279 (org-pos-in-match-range pos 5)) 'day)
16280 ((and (> pos (or (match-end 8) (match-end 5)))
16281 (< pos (match-end 0)))
16282 (- pos (or (match-end 8) (match-end 5))))
16283 (t 'day))))
16284 ans))
16286 (defun org-toggle-timestamp-type ()
16287 "Toggle the type (<active> or [inactive]) of a time stamp."
16288 (interactive)
16289 (when (org-at-timestamp-p t)
16290 (let ((beg (match-beginning 0)) (end (match-end 0))
16291 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16292 (save-excursion
16293 (goto-char beg)
16294 (while (re-search-forward "[][<>]" end t)
16295 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16296 t t)))
16297 (message "Timestamp is now %sactive"
16298 (if (equal (char-after beg) ?<) "" "in")))))
16300 (defvar org-clock-history) ; defined in org-clock.el
16301 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16302 (defun org-timestamp-change (n &optional what updown)
16303 "Change the date in the time stamp at point.
16304 The date will be changed by N times WHAT. WHAT can be `day', `month',
16305 `year', `minute', `second'. If WHAT is not given, the cursor position
16306 in the timestamp determines what will be changed."
16307 (let ((origin (point)) origin-cat
16308 with-hm inactive
16309 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16310 org-ts-what
16311 extra rem
16312 ts time time0 fixnext clrgx)
16313 (if (not (org-at-timestamp-p t))
16314 (error "Not at a timestamp"))
16315 (if (and (not what) (eq org-ts-what 'bracket))
16316 (org-toggle-timestamp-type)
16317 ;; Point isn't on brackets. Remember the part of the time-stamp
16318 ;; the point was in. Indeed, size of time-stamps may change,
16319 ;; but point must be kept in the same category nonetheless.
16320 (setq origin-cat org-ts-what)
16321 (if (and (not what) (not (eq org-ts-what 'day))
16322 org-display-custom-times
16323 (get-text-property (point) 'display)
16324 (not (get-text-property (1- (point)) 'display)))
16325 (setq org-ts-what 'day))
16326 (setq org-ts-what (or what org-ts-what)
16327 inactive (= (char-after (match-beginning 0)) ?\[)
16328 ts (match-string 0))
16329 (replace-match "")
16330 (if (string-match
16331 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16333 (setq extra (match-string 1 ts)))
16334 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16335 (setq with-hm t))
16336 (setq time0 (org-parse-time-string ts))
16337 (when (and updown
16338 (eq org-ts-what 'minute)
16339 (not current-prefix-arg))
16340 ;; This looks like s-up and s-down. Change by one rounding step.
16341 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16342 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16343 (setcar (cdr time0) (+ (nth 1 time0)
16344 (if (> n 0) (- rem) (- dm rem))))))
16345 (setq time
16346 (encode-time (or (car time0) 0)
16347 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16348 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16349 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16350 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16351 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16352 (nthcdr 6 time0)))
16353 (when (and (member org-ts-what '(hour minute))
16354 extra
16355 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16356 (setq extra (org-modify-ts-extra
16357 extra
16358 (if (eq org-ts-what 'hour) 2 5)
16359 n dm)))
16360 (when (integerp org-ts-what)
16361 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16362 (if (eq what 'calendar)
16363 (let ((cal-date (org-get-date-from-calendar)))
16364 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16365 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16366 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16367 (setcar time0 (or (car time0) 0))
16368 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16369 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16370 (setq time (apply 'encode-time time0))))
16371 ;; Insert the new time-stamp, and ensure point stays in the same
16372 ;; category as before (i.e. not after the last position in that
16373 ;; category).
16374 (let ((pos (point)))
16375 ;; Stay before inserted string. `save-excursion' is of no use.
16376 (setq org-last-changed-timestamp
16377 (org-insert-time-stamp time with-hm inactive nil nil extra))
16378 (goto-char pos))
16379 (save-match-data
16380 (looking-at org-ts-regexp3)
16381 (goto-char (cond
16382 ;; `day' category ends before `hour' if any, or at
16383 ;; the end of the day name.
16384 ((eq origin-cat 'day)
16385 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16386 ((eq origin-cat 'hour) (min (match-end 7) origin))
16387 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16388 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16389 ;; `year' and `month' have both fixed size: point
16390 ;; couldn't have moved into another part.
16391 (t origin))))
16392 ;; Update clock if on a CLOCK line.
16393 (org-clock-update-time-maybe)
16394 ;; Maybe adjust the closest clock in `org-clock-history'
16395 (when org-clock-adjust-closest
16396 (if (not (and (org-at-clock-log-p)
16397 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16398 org-clock-history))))))
16399 (message "No clock to adjust")
16400 (cond ((save-excursion ; fix previous clock?
16401 (re-search-backward org-ts-regexp0 nil t)
16402 (looking-back (concat org-clock-string " \\[")))
16403 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16404 ((save-excursion ; fix next clock?
16405 (re-search-backward org-ts-regexp0 nil t)
16406 (looking-at (concat org-ts-regexp0 "\\] =>")))
16407 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16408 (save-window-excursion
16409 ;; Find closest clock to point, adjust the previous/next one in history
16410 (let* ((p (save-excursion (org-back-to-heading t)))
16411 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16412 (clfixnth
16413 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16414 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16415 (if (not clfixpos)
16416 (message "No clock to adjust")
16417 (org-goto-marker-or-bmk clfixpos)
16418 (org-show-subtree)
16419 (when (re-search-forward clrgx nil t)
16420 (goto-char (match-beginning 1))
16421 (let (org-clock-adjust-closest)
16422 (org-timestamp-change n org-ts-what updown))
16423 (message "Clock adjusted in %s for heading: %s"
16424 (file-name-nondirectory (buffer-file-name))
16425 (org-get-heading t t))))))))
16426 ;; Try to recenter the calendar window, if any.
16427 (if (and org-calendar-follow-timestamp-change
16428 (get-buffer-window "*Calendar*" t)
16429 (memq org-ts-what '(day month year)))
16430 (org-recenter-calendar (time-to-days time))))))
16432 (defun org-modify-ts-extra (s pos n dm)
16433 "Change the different parts of the lead-time and repeat fields in timestamp."
16434 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16435 ng h m new rem)
16436 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16437 (cond
16438 ((or (org-pos-in-match-range pos 2)
16439 (org-pos-in-match-range pos 3))
16440 (setq m (string-to-number (match-string 3 s))
16441 h (string-to-number (match-string 2 s)))
16442 (if (org-pos-in-match-range pos 2)
16443 (setq h (+ h n))
16444 (setq n (* dm (org-no-warnings (signum n))))
16445 (when (not (= 0 (setq rem (% m dm))))
16446 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16447 (setq m (+ m n)))
16448 (if (< m 0) (setq m (+ m 60) h (1- h)))
16449 (if (> m 59) (setq m (- m 60) h (1+ h)))
16450 (setq h (min 24 (max 0 h)))
16451 (setq ng 1 new (format "-%02d:%02d" h m)))
16452 ((org-pos-in-match-range pos 6)
16453 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16454 ((org-pos-in-match-range pos 5)
16455 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16457 ((org-pos-in-match-range pos 9)
16458 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16459 ((org-pos-in-match-range pos 8)
16460 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16462 (when ng
16463 (setq s (concat
16464 (substring s 0 (match-beginning ng))
16466 (substring s (match-end ng))))))
16469 (defun org-recenter-calendar (date)
16470 "If the calendar is visible, recenter it to DATE."
16471 (let ((cwin (get-buffer-window "*Calendar*" t)))
16472 (when cwin
16473 (let ((calendar-move-hook nil))
16474 (with-selected-window cwin
16475 (calendar-goto-date (if (listp date) date
16476 (calendar-gregorian-from-absolute date))))))))
16478 (defun org-goto-calendar (&optional arg)
16479 "Go to the Emacs calendar at the current date.
16480 If there is a time stamp in the current line, go to that date.
16481 A prefix ARG can be used to force the current date."
16482 (interactive "P")
16483 (let ((tsr org-ts-regexp) diff
16484 (calendar-move-hook nil)
16485 (calendar-view-holidays-initially-flag nil)
16486 (calendar-view-diary-initially-flag nil))
16487 (if (or (org-at-timestamp-p)
16488 (save-excursion
16489 (beginning-of-line 1)
16490 (looking-at (concat ".*" tsr))))
16491 (let ((d1 (time-to-days (current-time)))
16492 (d2 (time-to-days
16493 (org-time-string-to-time (match-string 1)))))
16494 (setq diff (- d2 d1))))
16495 (calendar)
16496 (calendar-goto-today)
16497 (if (and diff (not arg)) (calendar-forward-day diff))))
16499 (defun org-get-date-from-calendar ()
16500 "Return a list (month day year) of date at point in calendar."
16501 (with-current-buffer "*Calendar*"
16502 (save-match-data
16503 (calendar-cursor-to-date))))
16505 (defun org-date-from-calendar ()
16506 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16507 If there is already a time stamp at the cursor position, update it."
16508 (interactive)
16509 (if (org-at-timestamp-p t)
16510 (org-timestamp-change 0 'calendar)
16511 (let ((cal-date (org-get-date-from-calendar)))
16512 (org-insert-time-stamp
16513 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16515 (defun org-minutes-to-hh:mm-string (m)
16516 "Compute H:MM from a number of minutes."
16517 (let ((h (/ m 60)))
16518 (setq m (- m (* 60 h)))
16519 (format org-time-clocksum-format h m)))
16521 (defun org-hh:mm-string-to-minutes (s)
16522 "Convert a string H:MM to a number of minutes.
16523 If the string is just a number, interpret it as minutes.
16524 In fact, the first hh:mm or number in the string will be taken,
16525 there can be extra stuff in the string.
16526 If no number is found, the return value is 0."
16527 (cond
16528 ((integerp s) s)
16529 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16530 (+ (* (string-to-number (match-string 1 s)) 60)
16531 (string-to-number (match-string 2 s))))
16532 ((string-match "\\([0-9]+\\)" s)
16533 (string-to-number (match-string 1 s)))
16534 (t 0)))
16536 (defcustom org-effort-durations
16537 `(("h" . 60)
16538 ("d" . ,(* 60 8))
16539 ("w" . ,(* 60 8 5))
16540 ("m" . ,(* 60 8 5 4))
16541 ("y" . ,(* 60 8 5 40)))
16542 "Conversion factor to minutes for an effort modifier.
16544 Each entry has the form (MODIFIER . MINUTES).
16546 In an effort string, a number followed by MODIFIER is multiplied
16547 by the specified number of MINUTES to obtain an effort in
16548 minutes.
16550 For example, if the value of this variable is ((\"hours\" . 60)), then an
16551 effort string \"2hours\" is equivalent to 120 minutes."
16552 :group 'org-agenda
16553 :version "24.1"
16554 :type '(alist :key-type (string :tag "Modifier")
16555 :value-type (number :tag "Minutes")))
16557 (defun org-duration-string-to-minutes (s &optional output-to-string)
16558 "Convert a duration string S to minutes.
16560 A bare number is interpreted as minutes, modifiers can be set by
16561 customizing `org-effort-durations' (which see).
16563 Entries containing a colon are interpreted as H:MM by
16564 `org-hh:mm-string-to-minutes'."
16565 (let ((result 0)
16566 (re (concat "\\([0-9.]+\\) *\\("
16567 (regexp-opt (mapcar 'car org-effort-durations))
16568 "\\)")))
16569 (while (string-match re s)
16570 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16571 (string-to-number (match-string 1 s))))
16572 (setq s (replace-match "" nil t s)))
16573 (setq result (floor result))
16574 (incf result (org-hh:mm-string-to-minutes s))
16575 (if output-to-string (number-to-string result) result)))
16577 ;;;; Files
16579 (defun org-save-all-org-buffers ()
16580 "Save all Org-mode buffers without user confirmation."
16581 (interactive)
16582 (message "Saving all Org-mode buffers...")
16583 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16584 (when (featurep 'org-id) (org-id-locations-save))
16585 (message "Saving all Org-mode buffers... done"))
16587 (defun org-revert-all-org-buffers ()
16588 "Revert all Org-mode buffers.
16589 Prompt for confirmation when there are unsaved changes.
16590 Be sure you know what you are doing before letting this function
16591 overwrite your changes.
16593 This function is useful in a setup where one tracks org files
16594 with a version control system, to revert on one machine after pulling
16595 changes from another. I believe the procedure must be like this:
16597 1. M-x org-save-all-org-buffers
16598 2. Pull changes from the other machine, resolve conflicts
16599 3. M-x org-revert-all-org-buffers"
16600 (interactive)
16601 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16602 (error "Abort"))
16603 (save-excursion
16604 (save-window-excursion
16605 (mapc
16606 (lambda (b)
16607 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16608 (with-current-buffer b buffer-file-name))
16609 (org-pop-to-buffer-same-window b)
16610 (revert-buffer t 'no-confirm)))
16611 (buffer-list))
16612 (when (and (featurep 'org-id) org-id-track-globally)
16613 (org-id-locations-load)))))
16615 ;;;; Agenda files
16617 ;;;###autoload
16618 (defun org-switchb (&optional arg)
16619 "Switch between Org buffers.
16620 With one prefix argument, restrict available buffers to files.
16621 With two prefix arguments, restrict available buffers to agenda files.
16623 Defaults to `iswitchb' for buffer name completion.
16624 Set `org-completion-use-ido' to make it use ido instead."
16625 (interactive "P")
16626 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16627 ((equal arg '(16)) (org-buffer-list 'agenda))
16628 (t (org-buffer-list))))
16629 (org-completion-use-iswitchb org-completion-use-iswitchb)
16630 (org-completion-use-ido org-completion-use-ido))
16631 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16632 (setq org-completion-use-iswitchb t))
16633 (org-pop-to-buffer-same-window
16634 (org-icompleting-read "Org buffer: "
16635 (mapcar 'list (mapcar 'buffer-name blist))
16636 nil t))))
16638 ;;; Define some older names previously used for this functionality
16639 ;;;###autoload
16640 (defalias 'org-ido-switchb 'org-switchb)
16641 ;;;###autoload
16642 (defalias 'org-iswitchb 'org-switchb)
16644 (defun org-buffer-list (&optional predicate exclude-tmp)
16645 "Return a list of Org buffers.
16646 PREDICATE can be `export', `files' or `agenda'.
16648 export restrict the list to Export buffers.
16649 files restrict the list to buffers visiting Org files.
16650 agenda restrict the list to buffers visiting agenda files.
16652 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16653 (let* ((bfn nil)
16654 (agenda-files (and (eq predicate 'agenda)
16655 (mapcar 'file-truename (org-agenda-files t))))
16656 (filter
16657 (cond
16658 ((eq predicate 'files)
16659 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16660 ((eq predicate 'export)
16661 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16662 ((eq predicate 'agenda)
16663 (lambda (b)
16664 (with-current-buffer b
16665 (and (derived-mode-p 'org-mode)
16666 (setq bfn (buffer-file-name b))
16667 (member (file-truename bfn) agenda-files)))))
16668 (t (lambda (b) (with-current-buffer b
16669 (or (derived-mode-p 'org-mode)
16670 (string-match "\*Org .*Export"
16671 (buffer-name b)))))))))
16672 (delq nil
16673 (mapcar
16674 (lambda(b)
16675 (if (and (funcall filter b)
16676 (or (not exclude-tmp)
16677 (not (string-match "tmp" (buffer-name b)))))
16679 nil))
16680 (buffer-list)))))
16682 (defun org-agenda-files (&optional unrestricted archives)
16683 "Get the list of agenda files.
16684 Optional UNRESTRICTED means return the full list even if a restriction
16685 is currently in place.
16686 When ARCHIVES is t, include all archive files that are really being
16687 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16688 `org-agenda-archives-mode' is t."
16689 (let ((files
16690 (cond
16691 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16692 ((stringp org-agenda-files) (org-read-agenda-file-list))
16693 ((listp org-agenda-files) org-agenda-files)
16694 (t (error "Invalid value of `org-agenda-files'")))))
16695 (setq files (apply 'append
16696 (mapcar (lambda (f)
16697 (if (file-directory-p f)
16698 (directory-files
16699 f t org-agenda-file-regexp)
16700 (list f)))
16701 files)))
16702 (when org-agenda-skip-unavailable-files
16703 (setq files (delq nil
16704 (mapcar (function
16705 (lambda (file)
16706 (and (file-readable-p file) file)))
16707 files))))
16708 (when (or (eq archives t)
16709 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16710 (setq files (org-add-archive-files files)))
16711 files))
16713 (defun org-agenda-file-p (&optional file)
16714 "Return non-nil, if FILE is an agenda file.
16715 If FILE is omitted, use the file associated with the current
16716 buffer."
16717 (member (or file (buffer-file-name))
16718 (org-agenda-files t)))
16720 (defun org-edit-agenda-file-list ()
16721 "Edit the list of agenda files.
16722 Depending on setup, this either uses customize to edit the variable
16723 `org-agenda-files', or it visits the file that is holding the list. In the
16724 latter case, the buffer is set up in a way that saving it automatically kills
16725 the buffer and restores the previous window configuration."
16726 (interactive)
16727 (if (stringp org-agenda-files)
16728 (let ((cw (current-window-configuration)))
16729 (find-file org-agenda-files)
16730 (org-set-local 'org-window-configuration cw)
16731 (org-add-hook 'after-save-hook
16732 (lambda ()
16733 (set-window-configuration
16734 (prog1 org-window-configuration
16735 (kill-buffer (current-buffer))))
16736 (org-install-agenda-files-menu)
16737 (message "New agenda file list installed"))
16738 nil 'local)
16739 (message "%s" (substitute-command-keys
16740 "Edit list and finish with \\[save-buffer]")))
16741 (customize-variable 'org-agenda-files)))
16743 (defun org-store-new-agenda-file-list (list)
16744 "Set new value for the agenda file list and save it correctly."
16745 (if (stringp org-agenda-files)
16746 (let ((fe (org-read-agenda-file-list t)) b u)
16747 (while (setq b (find-buffer-visiting org-agenda-files))
16748 (kill-buffer b))
16749 (with-temp-file org-agenda-files
16750 (insert
16751 (mapconcat
16752 (lambda (f) ;; Keep un-expanded entries.
16753 (if (setq u (assoc f fe))
16754 (cdr u)
16756 list "\n")
16757 "\n")))
16758 (let ((org-mode-hook nil) (org-inhibit-startup t)
16759 (org-insert-mode-line-in-empty-file nil))
16760 (setq org-agenda-files list)
16761 (customize-save-variable 'org-agenda-files org-agenda-files))))
16763 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16764 "Read the list of agenda files from a file.
16765 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16766 filenames, used by `org-store-new-agenda-file-list' to write back
16767 un-expanded file names."
16768 (when (file-directory-p org-agenda-files)
16769 (error "`org-agenda-files' cannot be a single directory"))
16770 (when (stringp org-agenda-files)
16771 (with-temp-buffer
16772 (insert-file-contents org-agenda-files)
16773 (mapcar
16774 (lambda (f)
16775 (let ((e (expand-file-name (substitute-in-file-name f)
16776 org-directory)))
16777 (if pair-with-expansion
16778 (cons e f)
16779 e)))
16780 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16782 ;;;###autoload
16783 (defun org-cycle-agenda-files ()
16784 "Cycle through the files in `org-agenda-files'.
16785 If the current buffer visits an agenda file, find the next one in the list.
16786 If the current buffer does not, find the first agenda file."
16787 (interactive)
16788 (let* ((fs (org-agenda-files t))
16789 (files (append fs (list (car fs))))
16790 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16791 file)
16792 (unless files (error "No agenda files"))
16793 (catch 'exit
16794 (while (setq file (pop files))
16795 (if (equal (file-truename file) tcf)
16796 (when (car files)
16797 (find-file (car files))
16798 (throw 'exit t))))
16799 (find-file (car fs)))
16800 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16802 (defun org-agenda-file-to-front (&optional to-end)
16803 "Move/add the current file to the top of the agenda file list.
16804 If the file is not present in the list, it is added to the front. If it is
16805 present, it is moved there. With optional argument TO-END, add/move to the
16806 end of the list."
16807 (interactive "P")
16808 (let ((org-agenda-skip-unavailable-files nil)
16809 (file-alist (mapcar (lambda (x)
16810 (cons (file-truename x) x))
16811 (org-agenda-files t)))
16812 (ctf (file-truename buffer-file-name))
16813 x had)
16814 (setq x (assoc ctf file-alist) had x)
16816 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16817 (if to-end
16818 (setq file-alist (append (delq x file-alist) (list x)))
16819 (setq file-alist (cons x (delq x file-alist))))
16820 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16821 (org-install-agenda-files-menu)
16822 (message "File %s to %s of agenda file list"
16823 (if had "moved" "added") (if to-end "end" "front"))))
16825 (defun org-remove-file (&optional file)
16826 "Remove current file from the list of files in variable `org-agenda-files'.
16827 These are the files which are being checked for agenda entries.
16828 Optional argument FILE means use this file instead of the current."
16829 (interactive)
16830 (let* ((org-agenda-skip-unavailable-files nil)
16831 (file (or file buffer-file-name))
16832 (true-file (file-truename file))
16833 (afile (abbreviate-file-name file))
16834 (files (delq nil (mapcar
16835 (lambda (x)
16836 (if (equal true-file
16837 (file-truename x))
16838 nil x))
16839 (org-agenda-files t)))))
16840 (if (not (= (length files) (length (org-agenda-files t))))
16841 (progn
16842 (org-store-new-agenda-file-list files)
16843 (org-install-agenda-files-menu)
16844 (message "Removed file: %s" afile))
16845 (message "File was not in list: %s (not removed)" afile))))
16847 (defun org-file-menu-entry (file)
16848 (vector file (list 'find-file file) t))
16850 (defun org-check-agenda-file (file)
16851 "Make sure FILE exists. If not, ask user what to do."
16852 (when (not (file-exists-p file))
16853 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16854 (abbreviate-file-name file))
16855 (let ((r (downcase (read-char-exclusive))))
16856 (cond
16857 ((equal r ?r)
16858 (org-remove-file file)
16859 (throw 'nextfile t))
16860 (t (error "Abort"))))))
16862 (defun org-get-agenda-file-buffer (file)
16863 "Get a buffer visiting FILE. If the buffer needs to be created, add
16864 it to the list of buffers which might be released later."
16865 (let ((buf (org-find-base-buffer-visiting file)))
16866 (if buf
16867 buf ; just return it
16868 ;; Make a new buffer and remember it
16869 (setq buf (find-file-noselect file))
16870 (if buf (push buf org-agenda-new-buffers))
16871 buf)))
16873 (defun org-release-buffers (blist)
16874 "Release all buffers in list, asking the user for confirmation when needed.
16875 When a buffer is unmodified, it is just killed. When modified, it is saved
16876 \(if the user agrees) and then killed."
16877 (let (buf file)
16878 (while (setq buf (pop blist))
16879 (setq file (buffer-file-name buf))
16880 (when (and (buffer-modified-p buf)
16881 file
16882 (y-or-n-p (format "Save file %s? " file)))
16883 (with-current-buffer buf (save-buffer)))
16884 (kill-buffer buf))))
16886 (defun org-prepare-agenda-buffers (files)
16887 "Create buffers for all agenda files, protect archived trees and comments."
16888 (interactive)
16889 (let ((pa '(:org-archived t))
16890 (pc '(:org-comment t))
16891 (pall '(:org-archived t :org-comment t))
16892 (inhibit-read-only t)
16893 (rea (concat ":" org-archive-tag ":"))
16894 bmp file re)
16895 (save-excursion
16896 (save-restriction
16897 (while (setq file (pop files))
16898 (catch 'nextfile
16899 (if (bufferp file)
16900 (set-buffer file)
16901 (org-check-agenda-file file)
16902 (set-buffer (org-get-agenda-file-buffer file)))
16903 (widen)
16904 (setq bmp (buffer-modified-p))
16905 (org-refresh-category-properties)
16906 (setq org-todo-keywords-for-agenda
16907 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16908 (setq org-done-keywords-for-agenda
16909 (append org-done-keywords-for-agenda org-done-keywords))
16910 (setq org-todo-keyword-alist-for-agenda
16911 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16912 (setq org-drawers-for-agenda
16913 (append org-drawers-for-agenda org-drawers))
16914 (setq org-tag-alist-for-agenda
16915 (append org-tag-alist-for-agenda org-tag-alist))
16917 (save-excursion
16918 (remove-text-properties (point-min) (point-max) pall)
16919 (when org-agenda-skip-archived-trees
16920 (goto-char (point-min))
16921 (while (re-search-forward rea nil t)
16922 (if (org-at-heading-p t)
16923 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16924 (goto-char (point-min))
16925 (setq re (format org-heading-keyword-regexp-format
16926 org-comment-string))
16927 (while (re-search-forward re nil t)
16928 (add-text-properties
16929 (match-beginning 0) (org-end-of-subtree t) pc)))
16930 (set-buffer-modified-p bmp)))))
16931 (setq org-todo-keywords-for-agenda
16932 (org-uniquify org-todo-keywords-for-agenda))
16933 (setq org-todo-keyword-alist-for-agenda
16934 (org-uniquify org-todo-keyword-alist-for-agenda)
16935 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16937 ;;;; Embedded LaTeX
16939 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16940 "Keymap for the minor `org-cdlatex-mode'.")
16942 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16943 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16944 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16945 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16946 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16948 (defvar org-cdlatex-texmathp-advice-is-done nil
16949 "Flag remembering if we have applied the advice to texmathp already.")
16951 (define-minor-mode org-cdlatex-mode
16952 "Toggle the minor `org-cdlatex-mode'.
16953 This mode supports entering LaTeX environment and math in LaTeX fragments
16954 in Org-mode.
16955 \\{org-cdlatex-mode-map}"
16956 nil " OCDL" nil
16957 (when org-cdlatex-mode
16958 (require 'cdlatex)
16959 (run-hooks 'cdlatex-mode-hook)
16960 (cdlatex-compute-tables))
16961 (unless org-cdlatex-texmathp-advice-is-done
16962 (setq org-cdlatex-texmathp-advice-is-done t)
16963 (defadvice texmathp (around org-math-always-on activate)
16964 "Always return t in org-mode buffers.
16965 This is because we want to insert math symbols without dollars even outside
16966 the LaTeX math segments. If Orgmode thinks that point is actually inside
16967 an embedded LaTeX fragment, let texmathp do its job.
16968 \\[org-cdlatex-mode-map]"
16969 (interactive)
16970 (let (p)
16971 (cond
16972 ((not (derived-mode-p 'org-mode)) ad-do-it)
16973 ((eq this-command 'cdlatex-math-symbol)
16974 (setq ad-return-value t
16975 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16977 (let ((p (org-inside-LaTeX-fragment-p)))
16978 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16979 (setq ad-return-value t
16980 texmathp-why '("Org-mode embedded math" . 0))
16981 (if p ad-do-it)))))))))
16983 (defun turn-on-org-cdlatex ()
16984 "Unconditionally turn on `org-cdlatex-mode'."
16985 (org-cdlatex-mode 1))
16987 (defun org-inside-LaTeX-fragment-p ()
16988 "Test if point is inside a LaTeX fragment.
16989 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16990 sequence appearing also before point.
16991 Even though the matchers for math are configurable, this function assumes
16992 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16993 delimiters are skipped when they have been removed by customization.
16994 The return value is nil, or a cons cell with the delimiter and the
16995 position of this delimiter.
16997 This function does a reasonably good job, but can locally be fooled by
16998 for example currency specifications. For example it will assume being in
16999 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17000 fragments that are properly closed, but during editing, we have to live
17001 with the uncertainty caused by missing closing delimiters. This function
17002 looks only before point, not after."
17003 (catch 'exit
17004 (let ((pos (point))
17005 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17006 (lim (progn
17007 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17008 (point)))
17009 dd-on str (start 0) m re)
17010 (goto-char pos)
17011 (when dodollar
17012 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17013 re (nth 1 (assoc "$" org-latex-regexps)))
17014 (while (string-match re str start)
17015 (cond
17016 ((= (match-end 0) (length str))
17017 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17018 ((= (match-end 0) (- (length str) 5))
17019 (throw 'exit nil))
17020 (t (setq start (match-end 0))))))
17021 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17022 (goto-char pos)
17023 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17024 (and (match-beginning 2) (throw 'exit nil))
17025 ;; count $$
17026 (while (re-search-backward "\\$\\$" lim t)
17027 (setq dd-on (not dd-on)))
17028 (goto-char pos)
17029 (if dd-on (cons "$$" m))))))
17031 (defun org-inside-latex-macro-p ()
17032 "Is point inside a LaTeX macro or its arguments?"
17033 (save-match-data
17034 (org-in-regexp
17035 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17037 (defun org-try-cdlatex-tab ()
17038 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17039 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17040 - inside a LaTeX fragment, or
17041 - after the first word in a line, where an abbreviation expansion could
17042 insert a LaTeX environment."
17043 (when org-cdlatex-mode
17044 (cond
17045 ;; Before any word on the line: No expansion possible.
17046 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17047 ;; Just after first word on the line: Expand it. Make sure it
17048 ;; cannot happen on headlines, though.
17049 ((save-excursion
17050 (skip-chars-backward "a-zA-Z0-9*")
17051 (skip-chars-backward " \t")
17052 (and (bolp) (not (org-at-heading-p))))
17053 (cdlatex-tab) t)
17054 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17056 (defun org-cdlatex-underscore-caret (&optional arg)
17057 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17058 Revert to the normal definition outside of these fragments."
17059 (interactive "P")
17060 (if (org-inside-LaTeX-fragment-p)
17061 (call-interactively 'cdlatex-sub-superscript)
17062 (let (org-cdlatex-mode)
17063 (call-interactively (key-binding (vector last-input-event))))))
17065 (defun org-cdlatex-math-modify (&optional arg)
17066 "Execute `cdlatex-math-modify' in LaTeX fragments.
17067 Revert to the normal definition outside of these fragments."
17068 (interactive "P")
17069 (if (org-inside-LaTeX-fragment-p)
17070 (call-interactively 'cdlatex-math-modify)
17071 (let (org-cdlatex-mode)
17072 (call-interactively (key-binding (vector last-input-event))))))
17074 (defvar org-latex-fragment-image-overlays nil
17075 "List of overlays carrying the images of latex fragments.")
17076 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17078 (defun org-remove-latex-fragment-image-overlays ()
17079 "Remove all overlays with LaTeX fragment images in current buffer."
17080 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17081 (setq org-latex-fragment-image-overlays nil))
17083 (defun org-preview-latex-fragment (&optional subtree)
17084 "Preview the LaTeX fragment at point, or all locally or globally.
17085 If the cursor is in a LaTeX fragment, create the image and overlay
17086 it over the source code. If there is no fragment at point, display
17087 all fragments in the current text, from one headline to the next. With
17088 prefix SUBTREE, display all fragments in the current subtree. With a
17089 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17090 the cursor is before the first headline,
17091 display all fragments in the buffer.
17092 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17093 (interactive "P")
17094 (unless buffer-file-name
17095 (error "Can't preview LaTeX fragment in a non-file buffer"))
17096 (org-remove-latex-fragment-image-overlays)
17097 (save-excursion
17098 (save-restriction
17099 (let (beg end at msg)
17100 (cond
17101 ((or (equal subtree '(16))
17102 (not (save-excursion
17103 (re-search-backward org-outline-regexp-bol nil t))))
17104 (setq beg (point-min) end (point-max)
17105 msg "Creating images for buffer...%s"))
17106 ((equal subtree '(4))
17107 (org-back-to-heading)
17108 (setq beg (point) end (org-end-of-subtree t)
17109 msg "Creating images for subtree...%s"))
17111 (if (setq at (org-inside-LaTeX-fragment-p))
17112 (goto-char (max (point-min) (- (cdr at) 2)))
17113 (org-back-to-heading))
17114 (setq beg (point) end (progn (outline-next-heading) (point))
17115 msg (if at "Creating image...%s"
17116 "Creating images for entry...%s"))))
17117 (message msg "")
17118 (narrow-to-region beg end)
17119 (goto-char beg)
17120 (org-format-latex
17121 (concat "ltxpng/" (file-name-sans-extension
17122 (file-name-nondirectory
17123 buffer-file-name)))
17124 default-directory 'overlays msg at 'forbuffer
17125 org-latex-create-formula-image-program)
17126 (message msg "done. Use `C-c C-c' to remove images.")))))
17128 (defvar org-latex-regexps
17129 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17130 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17131 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17132 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17133 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17134 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17135 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17136 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17137 "Regular expressions for matching embedded LaTeX.")
17139 (defvar org-export-have-math nil) ;; dynamic scoping
17140 (defun org-format-latex (prefix &optional dir overlays msg at
17141 forbuffer processing-type)
17142 "Replace LaTeX fragments with links to an image, and produce images.
17143 Some of the options can be changed using the variable
17144 `org-format-latex-options'."
17145 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17146 (let* ((prefixnodir (file-name-nondirectory prefix))
17147 (absprefix (expand-file-name prefix dir))
17148 (todir (file-name-directory absprefix))
17149 (opt org-format-latex-options)
17150 (matchers (plist-get opt :matchers))
17151 (re-list org-latex-regexps)
17152 (org-format-latex-header-extra
17153 (plist-get (org-infile-export-plist) :latex-header-extra))
17154 (cnt 0) txt hash link beg end re e checkdir
17155 executables-checked string
17156 m n block-type block linkfile movefile ov)
17157 ;; Check the different regular expressions
17158 (while (setq e (pop re-list))
17159 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17160 block (if block-type "\n\n" ""))
17161 (when (member m matchers)
17162 (goto-char (point-min))
17163 (while (re-search-forward re nil t)
17164 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17165 (not (get-text-property (match-beginning n)
17166 'org-protected))
17167 (or (not overlays)
17168 (not (eq (get-char-property (match-beginning n)
17169 'org-overlay-type)
17170 'org-latex-overlay))))
17171 (setq org-export-have-math t)
17172 (cond
17173 ((eq processing-type 'verbatim)
17174 ;; Leave the text verbatim, just protect it
17175 (add-text-properties (match-beginning n) (match-end n)
17176 '(org-protected t)))
17177 ((eq processing-type 'mathjax)
17178 ;; Prepare for MathJax processing
17179 (setq string (match-string n))
17180 (if (member m '("$" "$1"))
17181 (save-excursion
17182 (delete-region (match-beginning n) (match-end n))
17183 (goto-char (match-beginning n))
17184 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17185 "\\)")
17186 '(org-protected t))))
17187 (add-text-properties (match-beginning n) (match-end n)
17188 '(org-protected t))))
17189 ((or (eq processing-type 'dvipng)
17190 (eq processing-type 'imagemagick))
17191 ;; Process to an image
17192 (setq txt (match-string n)
17193 beg (match-beginning n) end (match-end n)
17194 cnt (1+ cnt))
17195 (let (print-length print-level) ; make sure full list is printed
17196 (setq hash (sha1 (prin1-to-string
17197 (list org-format-latex-header
17198 org-format-latex-header-extra
17199 org-export-latex-default-packages-alist
17200 org-export-latex-packages-alist
17201 org-format-latex-options
17202 forbuffer txt)))
17203 linkfile (format "%s_%s.png" prefix hash)
17204 movefile (format "%s_%s.png" absprefix hash)))
17205 (setq link (concat block "[[file:" linkfile "]]" block))
17206 (if msg (message msg cnt))
17207 (goto-char beg)
17208 (unless checkdir ; make sure the directory exists
17209 (setq checkdir t)
17210 (or (file-directory-p todir) (make-directory todir t)))
17211 (cond
17212 ((eq processing-type 'dvipng)
17213 (unless executables-checked
17214 (org-check-external-command
17215 "latex" "needed to convert LaTeX fragments to images")
17216 (org-check-external-command
17217 "dvipng" "needed to convert LaTeX fragments to images")
17218 (setq executables-checked t))
17219 (unless (file-exists-p movefile)
17220 (org-create-formula-image-with-dvipng
17221 txt movefile opt forbuffer)))
17222 ((eq processing-type 'imagemagick)
17223 (unless executables-checked
17224 (org-check-external-command
17225 "convert" "you need to install imagemagick")
17226 (setq executables-checked t))
17227 (unless (file-exists-p movefile)
17228 (org-create-formula-image-with-imagemagick
17229 txt movefile opt forbuffer))))
17230 (if overlays
17231 (progn
17232 (mapc (lambda (o)
17233 (if (eq (overlay-get o 'org-overlay-type)
17234 'org-latex-overlay)
17235 (delete-overlay o)))
17236 (overlays-in beg end))
17237 (setq ov (make-overlay beg end))
17238 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17239 (if (featurep 'xemacs)
17240 (progn
17241 (overlay-put ov 'invisible t)
17242 (overlay-put
17243 ov 'end-glyph
17244 (make-glyph (vector 'png :file movefile))))
17245 (overlay-put
17246 ov 'display
17247 (list 'image :type 'png :file movefile :ascent 'center)))
17248 (push ov org-latex-fragment-image-overlays)
17249 (goto-char end))
17250 (delete-region beg end)
17251 (insert (org-add-props link
17252 (list 'org-latex-src
17253 (replace-regexp-in-string
17254 "\"" "" txt)
17255 'org-latex-src-embed-type
17256 (if block-type 'paragraph 'character))))))
17257 ((eq processing-type 'mathml)
17258 ;; Process to MathML
17259 (unless executables-checked
17260 (unless (save-match-data (org-format-latex-mathml-available-p))
17261 (error "LaTeX to MathML converter not configured"))
17262 (setq executables-checked t))
17263 (setq txt (match-string n)
17264 beg (match-beginning n) end (match-end n)
17265 cnt (1+ cnt))
17266 (if msg (message msg cnt))
17267 (goto-char beg)
17268 (delete-region beg end)
17269 (insert (org-format-latex-as-mathml
17270 txt block-type prefix dir)))
17272 (error "Unknown conversion type %s for latex fragments"
17273 processing-type)))))))))
17275 (defun org-create-math-formula (latex-frag &optional mathml-file)
17276 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17277 Use `org-latex-to-mathml-convert-command'. If the conversion is
17278 sucessful, return the portion between \"<math...> </math>\"
17279 elements otherwise return nil. When MATHML-FILE is specified,
17280 write the results in to that file. When invoked as an
17281 interactive command, prompt for LATEX-FRAG, with initial value
17282 set to the current active region and echo the results for user
17283 inspection."
17284 (interactive (list (let ((frag (when (region-active-p)
17285 (buffer-substring-no-properties
17286 (region-beginning) (region-end)))))
17287 (read-string "LaTeX Fragment: " frag nil frag))))
17288 (unless latex-frag (error "Invalid latex-frag"))
17289 (let* ((tmp-in-file (file-relative-name
17290 (make-temp-name (expand-file-name "ltxmathml-in"))))
17291 (ignore (write-region latex-frag nil tmp-in-file))
17292 (tmp-out-file (file-relative-name
17293 (make-temp-name (expand-file-name "ltxmathml-out"))))
17294 (cmd (format-spec
17295 org-latex-to-mathml-convert-command
17296 `((?j . ,(shell-quote-argument
17297 (expand-file-name org-latex-to-mathml-jar-file)))
17298 (?I . ,(shell-quote-argument tmp-in-file))
17299 (?o . ,(shell-quote-argument tmp-out-file)))))
17300 mathml shell-command-output)
17301 (when (org-called-interactively-p 'any)
17302 (unless (org-format-latex-mathml-available-p)
17303 (error "LaTeX to MathML converter not configured")))
17304 (message "Running %s" cmd)
17305 (setq shell-command-output (shell-command-to-string cmd))
17306 (setq mathml
17307 (when (file-readable-p tmp-out-file)
17308 (with-current-buffer (find-file-noselect tmp-out-file t)
17309 (goto-char (point-min))
17310 (when (re-search-forward
17311 (concat
17312 (regexp-quote
17313 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17314 "\\(.\\|\n\\)*"
17315 (regexp-quote "</math>")) nil t)
17316 (prog1 (match-string 0) (kill-buffer))))))
17317 (cond
17318 (mathml
17319 (setq mathml
17320 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17321 (when mathml-file
17322 (write-region mathml nil mathml-file))
17323 (when (org-called-interactively-p 'any)
17324 (message mathml)))
17325 ((message "LaTeX to MathML conversion failed")
17326 (message shell-command-output)))
17327 (delete-file tmp-in-file)
17328 (when (file-exists-p tmp-out-file)
17329 (delete-file tmp-out-file))
17330 mathml))
17332 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17333 prefix &optional dir)
17334 "Use `org-create-math-formula' but check local cache first."
17335 (let* ((absprefix (expand-file-name prefix dir))
17336 (print-length nil) (print-level nil)
17337 (formula-id (concat
17338 "formula-"
17339 (sha1
17340 (prin1-to-string
17341 (list latex-frag
17342 org-latex-to-mathml-convert-command)))))
17343 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17344 (formula-cache-dir (file-name-directory formula-cache)))
17346 (unless (file-directory-p formula-cache-dir)
17347 (make-directory formula-cache-dir t))
17349 (unless (file-exists-p formula-cache)
17350 (org-create-math-formula latex-frag formula-cache))
17352 (if (file-exists-p formula-cache)
17353 ;; Successful conversion. Return the link to MathML file.
17354 (org-add-props
17355 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17356 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17357 'org-latex-src-embed-type (if latex-frag-type
17358 'paragraph 'character)))
17359 ;; Failed conversion. Return the LaTeX fragment verbatim
17360 (add-text-properties
17361 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17362 latex-frag)))
17364 ;; This function borrows from Ganesh Swami's latex2png.el
17365 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17366 "This calls dvipng."
17367 (require 'org-latex)
17368 (let* ((tmpdir (if (featurep 'xemacs)
17369 (temp-directory)
17370 temporary-file-directory))
17371 (texfilebase (make-temp-name
17372 (expand-file-name "orgtex" tmpdir)))
17373 (texfile (concat texfilebase ".tex"))
17374 (dvifile (concat texfilebase ".dvi"))
17375 (pngfile (concat texfilebase ".png"))
17376 (fnh (if (featurep 'xemacs)
17377 (font-height (face-font 'default))
17378 (face-attribute 'default :height nil)))
17379 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17380 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17381 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17382 "Black"))
17383 (bg (or (plist-get options (if buffer :background :html-background))
17384 "Transparent")))
17385 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17386 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17387 (with-temp-file texfile
17388 (insert (org-splice-latex-header
17389 org-format-latex-header
17390 org-export-latex-default-packages-alist
17391 org-export-latex-packages-alist t
17392 org-format-latex-header-extra))
17393 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17394 (require 'org-latex)
17395 (org-export-latex-fix-inputenc))
17396 (let ((dir default-directory))
17397 (condition-case nil
17398 (progn
17399 (cd tmpdir)
17400 (call-process "latex" nil nil nil texfile))
17401 (error nil))
17402 (cd dir))
17403 (if (not (file-exists-p dvifile))
17404 (progn (message "Failed to create dvi file from %s" texfile) nil)
17405 (condition-case nil
17406 (if (featurep 'xemacs)
17407 (call-process "dvipng" nil nil nil
17408 "-fg" fg "-bg" bg
17409 "-T" "tight"
17410 "-o" pngfile
17411 dvifile)
17412 (call-process "dvipng" nil nil nil
17413 "-fg" fg "-bg" bg
17414 "-D" dpi
17415 ;;"-x" scale "-y" scale
17416 "-T" "tight"
17417 "-o" pngfile
17418 dvifile))
17419 (error nil))
17420 (if (not (file-exists-p pngfile))
17421 (if org-format-latex-signal-error
17422 (error "Failed to create png file from %s" texfile)
17423 (message "Failed to create png file from %s" texfile)
17424 nil)
17425 ;; Use the requested file name and clean up
17426 (copy-file pngfile tofile 'replace)
17427 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17428 (if (file-exists-p (concat texfilebase e))
17429 (delete-file (concat texfilebase e))))
17430 pngfile))))
17432 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17433 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17434 "This calls convert, which is included into imagemagick."
17435 (require 'org-latex)
17436 (let* ((tmpdir (if (featurep 'xemacs)
17437 (temp-directory)
17438 temporary-file-directory))
17439 (texfilebase (make-temp-name
17440 (expand-file-name "orgtex" tmpdir)))
17441 (texfile (concat texfilebase ".tex"))
17442 (pdffile (concat texfilebase ".pdf"))
17443 (pngfile (concat texfilebase ".png"))
17444 (fnh (if (featurep 'xemacs)
17445 (font-height (face-font 'default))
17446 (face-attribute 'default :height nil)))
17447 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17448 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17449 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17450 "black"))
17451 (bg (or (plist-get options (if buffer :background :html-background))
17452 "white")))
17453 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17454 (setq fg (org-latex-color-format fg)))
17455 (if (eq bg 'default) (setq bg (org-latex-color :background))
17456 (setq bg (org-latex-color-format
17457 (if (string= bg "Transparent")(setq bg "white")))))
17458 (with-temp-file texfile
17459 (insert (org-splice-latex-header
17460 org-format-latex-header
17461 org-export-latex-default-packages-alist
17462 org-export-latex-packages-alist t
17463 org-format-latex-header-extra))
17464 (insert "\n\\begin{document}\n"
17465 "\\definecolor{fg}{rgb}{" fg "}\n"
17466 "\\definecolor{bg}{rgb}{" bg "}\n"
17467 "\n\\pagecolor{bg}\n"
17468 "\n{\\color{fg}\n"
17469 string
17470 "\n}\n"
17471 "\n\\end{document}\n" )
17472 (require 'org-latex)
17473 (org-export-latex-fix-inputenc))
17474 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17475 (condition-case nil
17476 (progn
17477 (cd tmpdir)
17478 (setq cmds org-latex-to-pdf-process)
17479 (while cmds
17480 (setq latex-frags-cmds (pop cmds))
17481 (if (listp latex-frags-cmds)
17482 (setq cmds nil)
17483 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17484 (while latex-frags-cmds
17485 (setq cmd (pop latex-frags-cmds))
17486 (while (string-match "%b" cmd)
17487 (setq cmd (replace-match
17488 (save-match-data
17489 (shell-quote-argument texfile))
17490 t t cmd)))
17491 (while (string-match "%f" cmd)
17492 (setq cmd (replace-match
17493 (save-match-data
17494 (shell-quote-argument (file-name-nondirectory texfile)))
17495 t t cmd)))
17496 (while (string-match "%o" cmd)
17497 (setq cmd (replace-match
17498 (save-match-data
17499 (shell-quote-argument (file-name-directory texfile)))
17500 t t cmd)))
17501 (setq cmd (split-string cmd))
17502 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17503 (error nil))
17504 (cd dir))
17505 (if (not (file-exists-p pdffile))
17506 (progn (message "Failed to create pdf file from %s" texfile) nil)
17507 (condition-case nil
17508 (if (featurep 'xemacs)
17509 (call-process "convert" nil nil nil
17510 "-density" "96"
17511 "-trim"
17512 "-antialias"
17513 pdffile
17514 "-quality" "100"
17515 ;; "-sharpen" "0x1.0"
17516 pngfile)
17517 (call-process "convert" nil nil nil
17518 "-density" dpi
17519 "-trim"
17520 "-antialias"
17521 pdffile
17522 "-quality" "100"
17523 ; "-sharpen" "0x1.0"
17524 pngfile))
17525 (error nil))
17526 (if (not (file-exists-p pngfile))
17527 (if org-format-latex-signal-error
17528 (error "Failed to create png file from %s" texfile)
17529 (message "Failed to create png file from %s" texfile)
17530 nil)
17531 ;; Use the requested file name and clean up
17532 (copy-file pngfile tofile 'replace)
17533 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17534 (if (file-exists-p (concat texfilebase e))
17535 (delete-file (concat texfilebase e))))
17536 pngfile))))
17538 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17539 "Fill a LaTeX header template TPL.
17540 In the template, the following place holders will be recognized:
17542 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17543 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17544 [PACKAGES] \\usepackage statements for PKG
17545 [NO-PACKAGES] do not include PKG
17546 [EXTRA] the string EXTRA
17547 [NO-EXTRA] do not include EXTRA
17549 For backward compatibility, if both the positive and the negative place
17550 holder is missing, the positive one (without the \"NO-\") will be
17551 assumed to be present at the end of the template.
17552 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17553 EXTRA is a string.
17554 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17555 (let (rpl (end ""))
17556 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17557 (setq rpl (if (or (match-end 1) (not def-pkg))
17558 "" (org-latex-packages-to-string def-pkg snippets-p t))
17559 tpl (replace-match rpl t t tpl))
17560 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17562 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17563 (setq rpl (if (or (match-end 1) (not pkg))
17564 "" (org-latex-packages-to-string pkg snippets-p t))
17565 tpl (replace-match rpl t t tpl))
17566 (if pkg (setq end
17567 (concat end "\n"
17568 (org-latex-packages-to-string pkg snippets-p)))))
17570 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17571 (setq rpl (if (or (match-end 1) (not extra))
17572 "" (concat extra "\n"))
17573 tpl (replace-match rpl t t tpl))
17574 (if (and extra (string-match "\\S-" extra))
17575 (setq end (concat end "\n" extra))))
17577 (if (string-match "\\S-" end)
17578 (concat tpl "\n" end)
17579 tpl)))
17581 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17582 "Turn an alist of packages into a string with the \\usepackage macros."
17583 (setq pkg (mapconcat (lambda(p)
17584 (cond
17585 ((stringp p) p)
17586 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17587 (format "%% Package %s omitted" (cadr p)))
17588 ((equal "" (car p))
17589 (format "\\usepackage{%s}" (cadr p)))
17591 (format "\\usepackage[%s]{%s}"
17592 (car p) (cadr p)))))
17594 "\n"))
17595 (if newline (concat pkg "\n") pkg))
17597 (defun org-dvipng-color (attr)
17598 "Return a RGB color specification for dvipng."
17599 (apply 'format "rgb %s %s %s"
17600 (mapcar 'org-normalize-color
17601 (if (featurep 'xemacs)
17602 (color-rgb-components
17603 (face-property 'default
17604 (cond ((eq attr :foreground) 'foreground)
17605 ((eq attr :background) 'background))))
17606 (color-values (face-attribute 'default attr nil))))))
17608 (defun org-latex-color (attr)
17609 "Return a RGB color for the LaTeX color package."
17610 (apply 'format "%s,%s,%s"
17611 (mapcar 'org-normalize-color
17612 (if (featurep 'xemacs)
17613 (color-rgb-components
17614 (face-property 'default
17615 (cond ((eq attr :foreground) 'foreground)
17616 ((eq attr :background) 'background))))
17617 (color-values (face-attribute 'default attr nil))))))
17619 (defun org-latex-color-format (color-name)
17620 "Convert COLOR-NAME to a RGB color value."
17621 (apply 'format "%s,%s,%s"
17622 (mapcar 'org-normalize-color
17623 (color-values color-name))))
17625 (defun org-normalize-color (value)
17626 "Return string to be used as color value for an RGB component."
17627 (format "%g" (/ value 65535.0)))
17629 ;; Image display
17632 (defvar org-inline-image-overlays nil)
17633 (make-variable-buffer-local 'org-inline-image-overlays)
17635 (defun org-toggle-inline-images (&optional include-linked)
17636 "Toggle the display of inline images.
17637 INCLUDE-LINKED is passed to `org-display-inline-images'."
17638 (interactive "P")
17639 (if org-inline-image-overlays
17640 (progn
17641 (org-remove-inline-images)
17642 (message "Inline image display turned off"))
17643 (org-display-inline-images include-linked)
17644 (if org-inline-image-overlays
17645 (message "%d images displayed inline"
17646 (length org-inline-image-overlays))
17647 (message "No images to display inline"))))
17649 (defun org-display-inline-images (&optional include-linked refresh beg end)
17650 "Display inline images.
17651 Normally only links without a description part are inlined, because this
17652 is how it will work for export. When INCLUDE-LINKED is set, also links
17653 with a description part will be inlined. This can be nice for a quick
17654 look at those images, but it does not reflect what exported files will look
17655 like.
17656 When REFRESH is set, refresh existing images between BEG and END.
17657 This will create new image displays only if necessary.
17658 BEG and END default to the buffer boundaries."
17659 (interactive "P")
17660 (unless refresh
17661 (org-remove-inline-images)
17662 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17663 (save-excursion
17664 (save-restriction
17665 (widen)
17666 (setq beg (or beg (point-min)) end (or end (point-max)))
17667 (goto-char beg)
17668 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17669 (substring (org-image-file-name-regexp) 0 -2)
17670 "\\)\\]" (if include-linked "" "\\]")))
17671 old file ov img)
17672 (while (re-search-forward re end t)
17673 (setq old (get-char-property-and-overlay (match-beginning 1)
17674 'org-image-overlay))
17675 (setq file (expand-file-name
17676 (concat (or (match-string 3) "") (match-string 4))))
17677 (when (file-exists-p file)
17678 (if (and (car-safe old) refresh)
17679 (image-refresh (overlay-get (cdr old) 'display))
17680 (setq img (save-match-data (create-image file)))
17681 (when img
17682 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17683 (overlay-put ov 'display img)
17684 (overlay-put ov 'face 'default)
17685 (overlay-put ov 'org-image-overlay t)
17686 (overlay-put ov 'modification-hooks
17687 (list 'org-display-inline-modification-hook))
17688 (push ov org-inline-image-overlays)))))))))
17690 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17691 "Remove inline-display overlay if a corresponding region is modified."
17692 (let ((inhibit-modification-hooks t))
17693 (when (and ov after)
17694 (delete ov org-inline-image-overlays)
17695 (delete-overlay ov))))
17697 (defun org-remove-inline-images ()
17698 "Remove inline display of images."
17699 (interactive)
17700 (mapc 'delete-overlay org-inline-image-overlays)
17701 (setq org-inline-image-overlays nil))
17703 ;;;; Key bindings
17705 ;; Outline functions from `outline-mode-prefix-map'
17706 ;; that can be remapped in Org:
17707 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17708 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17709 (define-key org-mode-map [remap outline-forward-same-level]
17710 'org-forward-same-level)
17711 (define-key org-mode-map [remap outline-backward-same-level]
17712 'org-backward-same-level)
17713 (define-key org-mode-map [remap show-branches]
17714 'org-kill-note-or-show-branches)
17715 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17716 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17717 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17719 ;; Outline functions from `outline-mode-prefix-map' that can not
17720 ;; be remapped in Org:
17722 ;; - the column "key binding" shows whether the Outline function is still
17723 ;; available in Org mode on the same key that it has been bound to in
17724 ;; Outline mode:
17725 ;; - "overridden": key used for a different functionality in Org mode
17726 ;; - else: key still bound to the same Outline function in Org mode
17728 ;; | Outline function | key binding | Org replacement |
17729 ;; |------------------------------------+-------------+-----------------------|
17730 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17731 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17732 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17733 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17734 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17735 ;; | `show-entry' | overridden | no replacement |
17736 ;; | `show-children' | `C-c C-i' | visibility cycling |
17737 ;; | `show-branches' | `C-c C-k' | still same function |
17738 ;; | `show-subtree' | overridden | visibility cycling |
17739 ;; | `show-all' | overridden | no replacement |
17740 ;; | `hide-subtree' | overridden | visibility cycling |
17741 ;; | `hide-body' | overridden | no replacement |
17742 ;; | `hide-entry' | overridden | visibility cycling |
17743 ;; | `hide-leaves' | overridden | no replacement |
17744 ;; | `hide-sublevels' | overridden | no replacement |
17745 ;; | `hide-other' | overridden | no replacement |
17747 ;; Make `C-c C-x' a prefix key
17748 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17750 ;; TAB key with modifiers
17751 (org-defkey org-mode-map "\C-i" 'org-cycle)
17752 (org-defkey org-mode-map [(tab)] 'org-cycle)
17753 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17754 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17755 ;; The following line is necessary under Suse GNU/Linux
17756 (unless (featurep 'xemacs)
17757 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17758 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17759 (define-key org-mode-map [backtab] 'org-shifttab)
17761 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17762 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17763 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17765 ;; Cursor keys with modifiers
17766 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17767 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17768 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17769 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17771 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17772 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17773 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17774 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17776 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17777 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17778 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17779 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17781 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17782 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17783 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17784 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17786 ;; Babel keys
17787 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17788 (mapc (lambda (pair)
17789 (define-key org-babel-map (car pair) (cdr pair)))
17790 org-babel-key-bindings)
17792 ;;; Extra keys for tty access.
17793 ;; We only set them when really needed because otherwise the
17794 ;; menus don't show the simple keys
17796 (when (or org-use-extra-keys
17797 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17798 (not window-system))
17799 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17800 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17801 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17802 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17803 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17804 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17805 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17806 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17807 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17808 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17809 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17810 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17811 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17812 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17813 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17814 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17815 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17816 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17817 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17818 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17819 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17820 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17821 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17822 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17823 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17824 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17825 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17826 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17828 ;; All the other keys
17830 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17831 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17832 (if (boundp 'narrow-map)
17833 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17834 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17835 (if (boundp 'narrow-map)
17836 (org-defkey narrow-map "b" 'org-narrow-to-block)
17837 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17838 (if (boundp 'narrow-map)
17839 (org-defkey narrow-map "e" 'org-narrow-to-element)
17840 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17841 (org-defkey org-mode-map "\C-\M-t" 'org-element-transpose)
17842 (org-defkey org-mode-map "\C-\M-f" 'org-element-forward)
17843 (org-defkey org-mode-map "\C-\M-b" 'org-element-backward)
17844 (org-defkey org-mode-map "\C-\M-u" 'org-element-up)
17845 (org-defkey org-mode-map "\C-\M-d" 'org-element-down)
17846 (org-defkey org-mode-map "\C-\M-t" 'org-element-transpose)
17847 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17848 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17849 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17850 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17851 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17852 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17853 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17854 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17855 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17856 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17857 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17858 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17859 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17860 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17861 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17862 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17863 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17864 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17865 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17866 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17867 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17868 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17869 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17870 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17871 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17872 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17873 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17874 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17875 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17876 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17877 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17878 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17879 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17880 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17881 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17882 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17883 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17884 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17885 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17886 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17887 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17888 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17889 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17890 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17891 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17892 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17893 (org-defkey org-mode-map "\C-c^" 'org-sort)
17894 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17895 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17896 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17897 (org-defkey org-mode-map "\C-m" 'org-return)
17898 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17899 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17900 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17901 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17902 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17903 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17904 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17905 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17906 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17907 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17908 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17909 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17910 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17911 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17912 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17913 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17914 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17915 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17916 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17917 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17918 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17919 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17920 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17922 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17923 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17924 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17925 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17927 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17928 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17929 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17930 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
17931 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17932 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17933 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17934 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17935 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17936 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17937 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17938 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17939 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17940 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17941 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17942 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17943 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
17944 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17945 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17946 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17947 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17949 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17950 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17951 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17952 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17953 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17955 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17957 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17959 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17960 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17962 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17965 (when (featurep 'xemacs)
17966 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17969 (defconst org-speed-commands-default
17971 ("Outline Navigation")
17972 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17973 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17974 ("f" . (org-speed-move-safe 'org-forward-same-level))
17975 ("b" . (org-speed-move-safe 'org-backward-same-level))
17976 ("u" . (org-speed-move-safe 'outline-up-heading))
17977 ("j" . org-goto)
17978 ("g" . (org-refile t))
17979 ("Outline Visibility")
17980 ("c" . org-cycle)
17981 ("C" . org-shifttab)
17982 (" " . org-display-outline-path)
17983 (":" . org-columns)
17984 ("Outline Structure Editing")
17985 ("U" . org-shiftmetaup)
17986 ("D" . org-shiftmetadown)
17987 ("r" . org-metaright)
17988 ("l" . org-metaleft)
17989 ("R" . org-shiftmetaright)
17990 ("L" . org-shiftmetaleft)
17991 ("i" . (progn (forward-char 1) (call-interactively
17992 'org-insert-heading-respect-content)))
17993 ("^" . org-sort)
17994 ("w" . org-refile)
17995 ("a" . org-archive-subtree-default-with-confirmation)
17996 ("." . org-mark-subtree)
17997 ("#" . org-toggle-comment)
17998 ("Clock Commands")
17999 ("I" . org-clock-in)
18000 ("O" . org-clock-out)
18001 ("Meta Data Editing")
18002 ("t" . org-todo)
18003 ("0" . (org-priority ?\ ))
18004 ("1" . (org-priority ?A))
18005 ("2" . (org-priority ?B))
18006 ("3" . (org-priority ?C))
18007 (";" . org-set-tags-command)
18008 ("e" . org-set-effort)
18009 ("E" . org-inc-effort)
18010 ("Agenda Views etc")
18011 ("v" . org-agenda)
18012 ("/" . org-sparse-tree)
18013 ("Misc")
18014 ("o" . org-open-at-point)
18015 ("?" . org-speed-command-help)
18016 ("<" . (org-agenda-set-restriction-lock 'subtree))
18017 (">" . (org-agenda-remove-restriction-lock))
18019 "The default speed commands.")
18021 (defun org-print-speed-command (e)
18022 (if (> (length (car e)) 1)
18023 (progn
18024 (princ "\n")
18025 (princ (car e))
18026 (princ "\n")
18027 (princ (make-string (length (car e)) ?-))
18028 (princ "\n"))
18029 (princ (car e))
18030 (princ " ")
18031 (if (symbolp (cdr e))
18032 (princ (symbol-name (cdr e)))
18033 (prin1 (cdr e)))
18034 (princ "\n")))
18036 (defun org-speed-command-help ()
18037 "Show the available speed commands."
18038 (interactive)
18039 (if (not org-use-speed-commands)
18040 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18041 (with-output-to-temp-buffer "*Help*"
18042 (princ "User-defined Speed commands\n===========================\n")
18043 (mapc 'org-print-speed-command org-speed-commands-user)
18044 (princ "\n")
18045 (princ "Built-in Speed commands\n=======================\n")
18046 (mapc 'org-print-speed-command org-speed-commands-default))
18047 (with-current-buffer "*Help*"
18048 (setq truncate-lines t))))
18050 (defun org-speed-move-safe (cmd)
18051 "Execute CMD, but make sure that the cursor always ends up in a headline.
18052 If not, return to the original position and throw an error."
18053 (interactive)
18054 (let ((pos (point)))
18055 (call-interactively cmd)
18056 (unless (and (bolp) (org-at-heading-p))
18057 (goto-char pos)
18058 (error "Boundary reached while executing %s" cmd))))
18060 (defvar org-self-insert-command-undo-counter 0)
18062 (defvar org-table-auto-blank-field) ; defined in org-table.el
18063 (defvar org-speed-command nil)
18065 (defun org-speed-command-default-hook (keys)
18066 "Hook for activating single-letter speed commands.
18067 `org-speed-commands-default' specifies a minimal command set.
18068 Use `org-speed-commands-user' for further customization."
18069 (when (or (and (bolp) (looking-at org-outline-regexp))
18070 (and (functionp org-use-speed-commands)
18071 (funcall org-use-speed-commands)))
18072 (cdr (assoc keys (append org-speed-commands-user
18073 org-speed-commands-default)))))
18075 (defun org-babel-speed-command-hook (keys)
18076 "Hook for activating single-letter code block commands."
18077 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18078 (cdr (assoc keys org-babel-key-bindings))))
18080 (defcustom org-speed-command-hook
18081 '(org-speed-command-default-hook org-babel-speed-command-hook)
18082 "Hook for activating speed commands at strategic locations.
18083 Hook functions are called in sequence until a valid handler is
18084 found.
18086 Each hook takes a single argument, a user-pressed command key
18087 which is also a `self-insert-command' from the global map.
18089 Within the hook, examine the cursor position and the command key
18090 and return nil or a valid handler as appropriate. Handler could
18091 be one of an interactive command, a function, or a form.
18093 Set `org-use-speed-commands' to non-nil value to enable this
18094 hook. The default setting is `org-speed-command-default-hook'."
18095 :group 'org-structure
18096 :version "24.1"
18097 :type 'hook)
18099 (defun org-self-insert-command (N)
18100 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18101 If the cursor is in a table looking at whitespace, the whitespace is
18102 overwritten, and the table is not marked as requiring realignment."
18103 (interactive "p")
18104 (org-check-before-invisible-edit 'insert)
18105 (cond
18106 ((and org-use-speed-commands
18107 (setq org-speed-command
18108 (run-hook-with-args-until-success
18109 'org-speed-command-hook (this-command-keys))))
18110 (cond
18111 ((commandp org-speed-command)
18112 (setq this-command org-speed-command)
18113 (call-interactively org-speed-command))
18114 ((functionp org-speed-command)
18115 (funcall org-speed-command))
18116 ((and org-speed-command (listp org-speed-command))
18117 (eval org-speed-command))
18118 (t (let (org-use-speed-commands)
18119 (call-interactively 'org-self-insert-command)))))
18120 ((and
18121 (org-table-p)
18122 (progn
18123 ;; check if we blank the field, and if that triggers align
18124 (and (featurep 'org-table) org-table-auto-blank-field
18125 (member last-command
18126 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18127 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18128 ;; got extra space, this field does not determine column width
18129 (let (org-table-may-need-update) (org-table-blank-field))
18130 ;; no extra space, this field may determine column width
18131 (org-table-blank-field)))
18133 (eq N 1)
18134 (looking-at "[^|\n]* |"))
18135 (let (org-table-may-need-update)
18136 (goto-char (1- (match-end 0)))
18137 (backward-delete-char 1)
18138 (goto-char (match-beginning 0))
18139 (self-insert-command N)))
18141 (setq org-table-may-need-update t)
18142 (self-insert-command N)
18143 (org-fix-tags-on-the-fly)
18144 (if org-self-insert-cluster-for-undo
18145 (if (not (eq last-command 'org-self-insert-command))
18146 (setq org-self-insert-command-undo-counter 1)
18147 (if (>= org-self-insert-command-undo-counter 20)
18148 (setq org-self-insert-command-undo-counter 1)
18149 (and (> org-self-insert-command-undo-counter 0)
18150 buffer-undo-list (listp buffer-undo-list)
18151 (not (cadr buffer-undo-list)) ; remove nil entry
18152 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18153 (setq org-self-insert-command-undo-counter
18154 (1+ org-self-insert-command-undo-counter))))))))
18156 (defun org-check-before-invisible-edit (kind)
18157 "Check is editing if kind KIND would be dangerous with invisible text around.
18158 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18159 ;; First, try to get out of here as quickly as possible, to reduce overhead
18160 (if (and org-catch-invisible-edits
18161 (or (not (boundp 'visible-mode)) (not visible-mode))
18162 (or (get-char-property (point) 'invisible)
18163 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18164 ;; OK, we need to take a closer look
18165 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18166 (invisible-before-point (if (bobp) nil (get-char-property
18167 (1- (point)) 'invisible)))
18168 (border-and-ok-direction
18170 ;; Check if we are acting predictably before invisible text
18171 (and invisible-at-point (not invisible-before-point)
18172 (memq kind '(insert delete-backward)))
18173 ;; Check if we are acting predictably after invisible text
18174 ;; This works not well, and I have turned it off. It seems
18175 ;; better to always show and stop after invisible text.
18176 ;; (and (not invisible-at-point) invisible-before-point
18177 ;; (memq kind '(insert delete)))
18180 (when (or (memq invisible-at-point '(outline org-hide-block))
18181 (memq invisible-before-point '(outline org-hide-block)))
18182 (if (eq org-catch-invisible-edits 'error)
18183 (error "Editing in invisible areas is prohibited - make visible first"))
18184 ;; Make the area visible
18185 (save-excursion
18186 (if invisible-before-point
18187 (goto-char (previous-single-char-property-change
18188 (point) 'invisible)))
18189 (org-cycle))
18190 (cond
18191 ((eq org-catch-invisible-edits 'show)
18192 ;; That's it, we do the edit after showing
18193 (message
18194 "Unfolding invisible region around point before editing")
18195 (sit-for 1))
18196 ((and (eq org-catch-invisible-edits 'smart)
18197 border-and-ok-direction)
18198 (message "Unfolding invisible region around point before editing"))
18200 ;; Don't do the edit, make the user repeat it in full visibility
18201 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18203 (defun org-fix-tags-on-the-fly ()
18204 (when (and (equal (char-after (point-at-bol)) ?*)
18205 (org-at-heading-p))
18206 (org-align-tags-here org-tags-column)))
18208 (defun org-delete-backward-char (N)
18209 "Like `delete-backward-char', insert whitespace at field end in tables.
18210 When deleting backwards, in tables this function will insert whitespace in
18211 front of the next \"|\" separator, to keep the table aligned. The table will
18212 still be marked for re-alignment if the field did fill the entire column,
18213 because, in this case the deletion might narrow the column."
18214 (interactive "p")
18215 (org-check-before-invisible-edit 'delete-backward)
18216 (if (and (org-table-p)
18217 (eq N 1)
18218 (string-match "|" (buffer-substring (point-at-bol) (point)))
18219 (looking-at ".*?|"))
18220 (let ((pos (point))
18221 (noalign (looking-at "[^|\n\r]* |"))
18222 (c org-table-may-need-update))
18223 (backward-delete-char N)
18224 (if (not overwrite-mode)
18225 (progn
18226 (skip-chars-forward "^|")
18227 (insert " ")
18228 (goto-char (1- pos))))
18229 ;; noalign: if there were two spaces at the end, this field
18230 ;; does not determine the width of the column.
18231 (if noalign (setq org-table-may-need-update c)))
18232 (backward-delete-char N)
18233 (org-fix-tags-on-the-fly)))
18235 (defun org-delete-char (N)
18236 "Like `delete-char', but insert whitespace at field end in tables.
18237 When deleting characters, in tables this function will insert whitespace in
18238 front of the next \"|\" separator, to keep the table aligned. The table will
18239 still be marked for re-alignment if the field did fill the entire column,
18240 because, in this case the deletion might narrow the column."
18241 (interactive "p")
18242 (org-check-before-invisible-edit 'delete)
18243 (if (and (org-table-p)
18244 (not (bolp))
18245 (not (= (char-after) ?|))
18246 (eq N 1))
18247 (if (looking-at ".*?|")
18248 (let ((pos (point))
18249 (noalign (looking-at "[^|\n\r]* |"))
18250 (c org-table-may-need-update))
18251 (replace-match (concat
18252 (substring (match-string 0) 1 -1)
18253 " |"))
18254 (goto-char pos)
18255 ;; noalign: if there were two spaces at the end, this field
18256 ;; does not determine the width of the column.
18257 (if noalign (setq org-table-may-need-update c)))
18258 (delete-char N))
18259 (delete-char N)
18260 (org-fix-tags-on-the-fly)))
18262 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18263 (put 'org-self-insert-command 'delete-selection t)
18264 (put 'orgtbl-self-insert-command 'delete-selection t)
18265 (put 'org-delete-char 'delete-selection 'supersede)
18266 (put 'org-delete-backward-char 'delete-selection 'supersede)
18267 (put 'org-yank 'delete-selection 'yank)
18269 ;; Make `flyspell-mode' delay after some commands
18270 (put 'org-self-insert-command 'flyspell-delayed t)
18271 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18272 (put 'org-delete-char 'flyspell-delayed t)
18273 (put 'org-delete-backward-char 'flyspell-delayed t)
18275 ;; Make pabbrev-mode expand after org-mode commands
18276 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18277 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18279 ;; How to do this: Measure non-white length of current string
18280 ;; If equal to column width, we should realign.
18282 (defun org-remap (map &rest commands)
18283 "In MAP, remap the functions given in COMMANDS.
18284 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18285 (let (new old)
18286 (while commands
18287 (setq old (pop commands) new (pop commands))
18288 (if (fboundp 'command-remapping)
18289 (org-defkey map (vector 'remap old) new)
18290 (substitute-key-definition old new map global-map)))))
18292 (when (eq org-enable-table-editor 'optimized)
18293 ;; If the user wants maximum table support, we need to hijack
18294 ;; some standard editing functions
18295 (org-remap org-mode-map
18296 'self-insert-command 'org-self-insert-command
18297 'delete-char 'org-delete-char
18298 'delete-backward-char 'org-delete-backward-char)
18299 (org-defkey org-mode-map "|" 'org-force-self-insert))
18301 (defvar org-ctrl-c-ctrl-c-hook nil
18302 "Hook for functions attaching themselves to `C-c C-c'.
18304 This can be used to add additional functionality to the C-c C-c
18305 key which executes context-dependent commands. This hook is run
18306 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18307 run after the last test.
18309 Each function will be called with no arguments. The function
18310 must check if the context is appropriate for it to act. If yes,
18311 it should do its thing and then return a non-nil value. If the
18312 context is wrong, just do nothing and return nil.")
18314 (defvar org-ctrl-c-ctrl-c-final-hook nil
18315 "Hook for functions attaching themselves to `C-c C-c'.
18317 This can be used to add additional functionality to the C-c C-c
18318 key which executes context-dependent commands. This hook is run
18319 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18320 before the first test.
18322 Each function will be called with no arguments. The function
18323 must check if the context is appropriate for it to act. If yes,
18324 it should do its thing and then return a non-nil value. If the
18325 context is wrong, just do nothing and return nil.")
18327 (defvar org-tab-first-hook nil
18328 "Hook for functions to attach themselves to TAB.
18329 See `org-ctrl-c-ctrl-c-hook' for more information.
18330 This hook runs as the first action when TAB is pressed, even before
18331 `org-cycle' messes around with the `outline-regexp' to cater for
18332 inline tasks and plain list item folding.
18333 If any function in this hook returns t, any other actions that
18334 would have been caused by TAB (such as table field motion or visibility
18335 cycling) will not occur.")
18337 (defvar org-tab-after-check-for-table-hook nil
18338 "Hook for functions to attach themselves to TAB.
18339 See `org-ctrl-c-ctrl-c-hook' for more information.
18340 This hook runs after it has been established that the cursor is not in a
18341 table, but before checking if the cursor is in a headline or if global cycling
18342 should be done.
18343 If any function in this hook returns t, not other actions like visibility
18344 cycling will be done.")
18346 (defvar org-tab-after-check-for-cycling-hook nil
18347 "Hook for functions to attach themselves to TAB.
18348 See `org-ctrl-c-ctrl-c-hook' for more information.
18349 This hook runs after it has been established that not table field motion and
18350 not visibility should be done because of current context. This is probably
18351 the place where a package like yasnippets can hook in.")
18353 (defvar org-tab-before-tab-emulation-hook nil
18354 "Hook for functions to attach themselves to TAB.
18355 See `org-ctrl-c-ctrl-c-hook' for more information.
18356 This hook runs after every other options for TAB have been exhausted, but
18357 before indentation and \t insertion takes place.")
18359 (defvar org-metaleft-hook nil
18360 "Hook for functions attaching themselves to `M-left'.
18361 See `org-ctrl-c-ctrl-c-hook' for more information.")
18362 (defvar org-metaright-hook nil
18363 "Hook for functions attaching themselves to `M-right'.
18364 See `org-ctrl-c-ctrl-c-hook' for more information.")
18365 (defvar org-metaup-hook nil
18366 "Hook for functions attaching themselves to `M-up'.
18367 See `org-ctrl-c-ctrl-c-hook' for more information.")
18368 (defvar org-metadown-hook nil
18369 "Hook for functions attaching themselves to `M-down'.
18370 See `org-ctrl-c-ctrl-c-hook' for more information.")
18371 (defvar org-shiftmetaleft-hook nil
18372 "Hook for functions attaching themselves to `M-S-left'.
18373 See `org-ctrl-c-ctrl-c-hook' for more information.")
18374 (defvar org-shiftmetaright-hook nil
18375 "Hook for functions attaching themselves to `M-S-right'.
18376 See `org-ctrl-c-ctrl-c-hook' for more information.")
18377 (defvar org-shiftmetaup-hook nil
18378 "Hook for functions attaching themselves to `M-S-up'.
18379 See `org-ctrl-c-ctrl-c-hook' for more information.")
18380 (defvar org-shiftmetadown-hook nil
18381 "Hook for functions attaching themselves to `M-S-down'.
18382 See `org-ctrl-c-ctrl-c-hook' for more information.")
18383 (defvar org-metareturn-hook nil
18384 "Hook for functions attaching themselves to `M-RET'.
18385 See `org-ctrl-c-ctrl-c-hook' for more information.")
18386 (defvar org-shiftup-hook nil
18387 "Hook for functions attaching themselves to `S-up'.
18388 See `org-ctrl-c-ctrl-c-hook' for more information.")
18389 (defvar org-shiftup-final-hook nil
18390 "Hook for functions attaching themselves to `S-up'.
18391 This one runs after all other options except shift-select have been excluded.
18392 See `org-ctrl-c-ctrl-c-hook' for more information.")
18393 (defvar org-shiftdown-hook nil
18394 "Hook for functions attaching themselves to `S-down'.
18395 See `org-ctrl-c-ctrl-c-hook' for more information.")
18396 (defvar org-shiftdown-final-hook nil
18397 "Hook for functions attaching themselves to `S-down'.
18398 This one runs after all other options except shift-select have been excluded.
18399 See `org-ctrl-c-ctrl-c-hook' for more information.")
18400 (defvar org-shiftleft-hook nil
18401 "Hook for functions attaching themselves to `S-left'.
18402 See `org-ctrl-c-ctrl-c-hook' for more information.")
18403 (defvar org-shiftleft-final-hook nil
18404 "Hook for functions attaching themselves to `S-left'.
18405 This one runs after all other options except shift-select have been excluded.
18406 See `org-ctrl-c-ctrl-c-hook' for more information.")
18407 (defvar org-shiftright-hook nil
18408 "Hook for functions attaching themselves to `S-right'.
18409 See `org-ctrl-c-ctrl-c-hook' for more information.")
18410 (defvar org-shiftright-final-hook nil
18411 "Hook for functions attaching themselves to `S-right'.
18412 This one runs after all other options except shift-select have been excluded.
18413 See `org-ctrl-c-ctrl-c-hook' for more information.")
18415 (defun org-modifier-cursor-error ()
18416 "Throw an error, a modified cursor command was applied in wrong context."
18417 (error "This command is active in special context like tables, headlines or items"))
18419 (defun org-shiftselect-error ()
18420 "Throw an error because Shift-Cursor command was applied in wrong context."
18421 (if (and (boundp 'shift-select-mode) shift-select-mode)
18422 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18423 (error "This command works only in special context like headlines or timestamps")))
18425 (defun org-call-for-shift-select (cmd)
18426 (let ((this-command-keys-shift-translated t))
18427 (call-interactively cmd)))
18429 (defun org-shifttab (&optional arg)
18430 "Global visibility cycling or move to previous table field.
18431 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18432 on context.
18433 See the individual commands for more information."
18434 (interactive "P")
18435 (cond
18436 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18437 ((integerp arg)
18438 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18439 (message "Content view to level: %d" arg)
18440 (org-content (prefix-numeric-value arg2))
18441 (setq org-cycle-global-status 'overview)))
18442 (t (call-interactively 'org-global-cycle))))
18444 (defun org-shiftmetaleft ()
18445 "Promote subtree or delete table column.
18446 Calls `org-promote-subtree', `org-outdent-item-tree', or
18447 `org-table-delete-column', depending on context. See the
18448 individual commands for more information."
18449 (interactive)
18450 (cond
18451 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18452 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18453 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18454 ((if (not (org-region-active-p)) (org-at-item-p)
18455 (save-excursion (goto-char (region-beginning))
18456 (org-at-item-p)))
18457 (call-interactively 'org-outdent-item-tree))
18458 (t (org-modifier-cursor-error))))
18460 (defun org-shiftmetaright ()
18461 "Demote subtree or insert table column.
18462 Calls `org-demote-subtree', `org-indent-item-tree', or
18463 `org-table-insert-column', depending on context. See the
18464 individual commands for more information."
18465 (interactive)
18466 (cond
18467 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18468 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18469 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18470 ((if (not (org-region-active-p)) (org-at-item-p)
18471 (save-excursion (goto-char (region-beginning))
18472 (org-at-item-p)))
18473 (call-interactively 'org-indent-item-tree))
18474 (t (org-modifier-cursor-error))))
18476 (defun org-shiftmetaup (&optional arg)
18477 "Move subtree up or kill table row.
18478 Calls `org-move-subtree-up' or `org-table-kill-row' or
18479 `org-move-item-up' or `org-timestamp-up', depending on context.
18480 See the individual commands for more information."
18481 (interactive "P")
18482 (cond
18483 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18484 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18485 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18486 ((org-at-item-p) (call-interactively 'org-move-item-up))
18487 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18488 (call-interactively 'org-timestamp-up)))
18489 (t (org-modifier-cursor-error))))
18491 (defun org-shiftmetadown (&optional arg)
18492 "Move subtree down or insert table row.
18493 Calls `org-move-subtree-down' or `org-table-insert-row' or
18494 `org-move-item-down' or `org-timestamp-up', depending on context.
18495 See the individual commands for more information."
18496 (interactive "P")
18497 (cond
18498 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18499 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18500 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18501 ((org-at-item-p) (call-interactively 'org-move-item-down))
18502 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18503 (call-interactively 'org-timestamp-down)))
18504 (t (org-modifier-cursor-error))))
18506 (defsubst org-hidden-tree-error ()
18507 (error
18508 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18510 (defun org-metaleft (&optional arg)
18511 "Promote heading or move table column to left.
18512 Calls `org-do-promote' or `org-table-move-column', depending on context.
18513 With no specific context, calls the Emacs default `backward-word'.
18514 See the individual commands for more information."
18515 (interactive "P")
18516 (cond
18517 ((run-hook-with-args-until-success 'org-metaleft-hook))
18518 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18519 ((org-with-limited-levels
18520 (or (org-at-heading-p)
18521 (and (org-region-active-p)
18522 (save-excursion
18523 (goto-char (region-beginning))
18524 (org-at-heading-p)))))
18525 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18526 (call-interactively 'org-do-promote))
18527 ;; At an inline task.
18528 ((org-at-heading-p)
18529 (call-interactively 'org-inlinetask-promote))
18530 ((or (org-at-item-p)
18531 (and (org-region-active-p)
18532 (save-excursion
18533 (goto-char (region-beginning))
18534 (org-at-item-p))))
18535 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18536 (call-interactively 'org-outdent-item))
18537 (t (call-interactively 'backward-word))))
18539 (defun org-metaright (&optional arg)
18540 "Demote a subtree, a list item or move table column to right.
18541 In front of a drawer or a block keyword, indent it correctly.
18542 With no specific context, calls the Emacs default `forward-word'.
18543 See the individual commands for more information."
18544 (interactive "P")
18545 (cond
18546 ((run-hook-with-args-until-success 'org-metaright-hook))
18547 ((org-at-table-p) (call-interactively 'org-table-move-column))
18548 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18549 ((org-at-block-p) (call-interactively 'org-indent-block))
18550 ((org-with-limited-levels
18551 (or (org-at-heading-p)
18552 (and (org-region-active-p)
18553 (save-excursion
18554 (goto-char (region-beginning))
18555 (org-at-heading-p)))))
18556 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18557 (call-interactively 'org-do-demote))
18558 ;; At an inline task.
18559 ((org-at-heading-p)
18560 (call-interactively 'org-inlinetask-demote))
18561 ((or (org-at-item-p)
18562 (and (org-region-active-p)
18563 (save-excursion
18564 (goto-char (region-beginning))
18565 (org-at-item-p))))
18566 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18567 (call-interactively 'org-indent-item))
18568 (t (call-interactively 'forward-word))))
18570 (defun org-check-for-hidden (what)
18571 "Check if there are hidden headlines/items in the current visual line.
18572 WHAT can be either `headlines' or `items'. If the current line is
18573 an outline or item heading and it has a folded subtree below it,
18574 this function returns t, nil otherwise."
18575 (let ((re (cond
18576 ((eq what 'headlines) org-outline-regexp-bol)
18577 ((eq what 'items) (org-item-beginning-re))
18578 (t (error "This should not happen"))))
18579 beg end)
18580 (save-excursion
18581 (catch 'exit
18582 (unless (org-region-active-p)
18583 (setq beg (point-at-bol))
18584 (beginning-of-line 2)
18585 (while (and (not (eobp)) ;; this is like `next-line'
18586 (get-char-property (1- (point)) 'invisible))
18587 (beginning-of-line 2))
18588 (setq end (point))
18589 (goto-char beg)
18590 (goto-char (point-at-eol))
18591 (setq end (max end (point)))
18592 (while (re-search-forward re end t)
18593 (if (get-char-property (match-beginning 0) 'invisible)
18594 (throw 'exit t))))
18595 nil))))
18597 (defun org-metaup (&optional arg)
18598 "Move subtree up or move table row up.
18599 Calls `org-move-subtree-up' or `org-table-move-row' or
18600 `org-move-item-up', depending on context. See the individual commands
18601 for more information."
18602 (interactive "P")
18603 (cond
18604 ((run-hook-with-args-until-success 'org-metaup-hook))
18605 ((org-region-active-p)
18606 (let* ((a (min (region-beginning) (region-end)))
18607 (b (1- (max (region-beginning) (region-end))))
18608 (c (save-excursion (goto-char a)
18609 (move-beginning-of-line 0)))
18610 (d (save-excursion (goto-char a)
18611 (move-end-of-line 0) (point))))
18612 (transpose-regions a b c d)
18613 (goto-char c)))
18614 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18615 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18616 ((org-at-item-p) (call-interactively 'org-move-item-up))
18617 (t (org-element-drag-backward))))
18619 (defun org-metadown (&optional arg)
18620 "Move subtree down or move table row down.
18621 Calls `org-move-subtree-down' or `org-table-move-row' or
18622 `org-move-item-down', depending on context. See the individual
18623 commands for more information."
18624 (interactive "P")
18625 (cond
18626 ((run-hook-with-args-until-success 'org-metadown-hook))
18627 ((org-region-active-p)
18628 (let* ((a (min (region-beginning) (region-end)))
18629 (b (max (region-beginning) (region-end)))
18630 (c (save-excursion (goto-char b)
18631 (move-beginning-of-line 1)))
18632 (d (save-excursion (goto-char b)
18633 (move-end-of-line 1) (1+ (point)))))
18634 (transpose-regions a b c d)
18635 (goto-char d)))
18636 ((org-at-table-p) (call-interactively 'org-table-move-row))
18637 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18638 ((org-at-item-p) (call-interactively 'org-move-item-down))
18639 (t (org-element-drag-forward))))
18641 (defun org-shiftup (&optional arg)
18642 "Increase item in timestamp or increase priority of current headline.
18643 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18644 depending on context. See the individual commands for more information."
18645 (interactive "P")
18646 (cond
18647 ((run-hook-with-args-until-success 'org-shiftup-hook))
18648 ((and org-support-shift-select (org-region-active-p))
18649 (org-call-for-shift-select 'previous-line))
18650 ((org-at-timestamp-p t)
18651 (call-interactively (if org-edit-timestamp-down-means-later
18652 'org-timestamp-down 'org-timestamp-up)))
18653 ((and (not (eq org-support-shift-select 'always))
18654 org-enable-priority-commands
18655 (org-at-heading-p))
18656 (call-interactively 'org-priority-up))
18657 ((and (not org-support-shift-select) (org-at-item-p))
18658 (call-interactively 'org-previous-item))
18659 ((org-clocktable-try-shift 'up arg))
18660 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18661 (org-support-shift-select
18662 (org-call-for-shift-select 'previous-line))
18663 (t (org-shiftselect-error))))
18665 (defun org-shiftdown (&optional arg)
18666 "Decrease item in timestamp or decrease priority of current headline.
18667 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18668 depending on context. See the individual commands for more information."
18669 (interactive "P")
18670 (cond
18671 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18672 ((and org-support-shift-select (org-region-active-p))
18673 (org-call-for-shift-select 'next-line))
18674 ((org-at-timestamp-p t)
18675 (call-interactively (if org-edit-timestamp-down-means-later
18676 'org-timestamp-up 'org-timestamp-down)))
18677 ((and (not (eq org-support-shift-select 'always))
18678 org-enable-priority-commands
18679 (org-at-heading-p))
18680 (call-interactively 'org-priority-down))
18681 ((and (not org-support-shift-select) (org-at-item-p))
18682 (call-interactively 'org-next-item))
18683 ((org-clocktable-try-shift 'down arg))
18684 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18685 (org-support-shift-select
18686 (org-call-for-shift-select 'next-line))
18687 (t (org-shiftselect-error))))
18689 (defun org-shiftright (&optional arg)
18690 "Cycle the thing at point or in the current line, depending on context.
18691 Depending on context, this does one of the following:
18693 - switch a timestamp at point one day into the future
18694 - on a headline, switch to the next TODO keyword.
18695 - on an item, switch entire list to the next bullet type
18696 - on a property line, switch to the next allowed value
18697 - on a clocktable definition line, move time block into the future"
18698 (interactive "P")
18699 (cond
18700 ((run-hook-with-args-until-success 'org-shiftright-hook))
18701 ((and org-support-shift-select (org-region-active-p))
18702 (org-call-for-shift-select 'forward-char))
18703 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18704 ((and (not (eq org-support-shift-select 'always))
18705 (org-at-heading-p))
18706 (let ((org-inhibit-logging
18707 (not org-treat-S-cursor-todo-selection-as-state-change))
18708 (org-inhibit-blocking
18709 (not org-treat-S-cursor-todo-selection-as-state-change)))
18710 (org-call-with-arg 'org-todo 'right)))
18711 ((or (and org-support-shift-select
18712 (not (eq org-support-shift-select 'always))
18713 (org-at-item-bullet-p))
18714 (and (not org-support-shift-select) (org-at-item-p)))
18715 (org-call-with-arg 'org-cycle-list-bullet nil))
18716 ((and (not (eq org-support-shift-select 'always))
18717 (org-at-property-p))
18718 (call-interactively 'org-property-next-allowed-value))
18719 ((org-clocktable-try-shift 'right arg))
18720 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18721 (org-support-shift-select
18722 (org-call-for-shift-select 'forward-char))
18723 (t (org-shiftselect-error))))
18725 (defun org-shiftleft (&optional arg)
18726 "Cycle the thing at point or in the current line, depending on context.
18727 Depending on context, this does one of the following:
18729 - switch a timestamp at point one day into the past
18730 - on a headline, switch to the previous TODO keyword.
18731 - on an item, switch entire list to the previous bullet type
18732 - on a property line, switch to the previous allowed value
18733 - on a clocktable definition line, move time block into the past"
18734 (interactive "P")
18735 (cond
18736 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18737 ((and org-support-shift-select (org-region-active-p))
18738 (org-call-for-shift-select 'backward-char))
18739 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18740 ((and (not (eq org-support-shift-select 'always))
18741 (org-at-heading-p))
18742 (let ((org-inhibit-logging
18743 (not org-treat-S-cursor-todo-selection-as-state-change))
18744 (org-inhibit-blocking
18745 (not org-treat-S-cursor-todo-selection-as-state-change)))
18746 (org-call-with-arg 'org-todo 'left)))
18747 ((or (and org-support-shift-select
18748 (not (eq org-support-shift-select 'always))
18749 (org-at-item-bullet-p))
18750 (and (not org-support-shift-select) (org-at-item-p)))
18751 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18752 ((and (not (eq org-support-shift-select 'always))
18753 (org-at-property-p))
18754 (call-interactively 'org-property-previous-allowed-value))
18755 ((org-clocktable-try-shift 'left arg))
18756 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18757 (org-support-shift-select
18758 (org-call-for-shift-select 'backward-char))
18759 (t (org-shiftselect-error))))
18761 (defun org-shiftcontrolright ()
18762 "Switch to next TODO set."
18763 (interactive)
18764 (cond
18765 ((and org-support-shift-select (org-region-active-p))
18766 (org-call-for-shift-select 'forward-word))
18767 ((and (not (eq org-support-shift-select 'always))
18768 (org-at-heading-p))
18769 (org-call-with-arg 'org-todo 'nextset))
18770 (org-support-shift-select
18771 (org-call-for-shift-select 'forward-word))
18772 (t (org-shiftselect-error))))
18774 (defun org-shiftcontrolleft ()
18775 "Switch to previous TODO set."
18776 (interactive)
18777 (cond
18778 ((and org-support-shift-select (org-region-active-p))
18779 (org-call-for-shift-select 'backward-word))
18780 ((and (not (eq org-support-shift-select 'always))
18781 (org-at-heading-p))
18782 (org-call-with-arg 'org-todo 'previousset))
18783 (org-support-shift-select
18784 (org-call-for-shift-select 'backward-word))
18785 (t (org-shiftselect-error))))
18787 (defun org-shiftcontrolup ()
18788 "Change timestamps synchronously up in CLOCK log lines."
18789 (interactive)
18790 (cond ((and (not org-support-shift-select)
18791 (org-at-clock-log-p)
18792 (org-at-timestamp-p t))
18793 (org-clock-timestamps-up))
18794 (t (org-shiftselect-error))))
18796 (defun org-shiftcontroldown ()
18797 "Change timestamps synchronously down in CLOCK log lines."
18798 (interactive)
18799 (cond ((and (not org-support-shift-select)
18800 (org-at-clock-log-p)
18801 (org-at-timestamp-p t))
18802 (org-clock-timestamps-down))
18803 (t (org-shiftselect-error))))
18805 (defun org-ctrl-c-ret ()
18806 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18807 (interactive)
18808 (cond
18809 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18810 (t (call-interactively 'org-insert-heading))))
18812 (defun org-find-visible ()
18813 (let ((s (point)))
18814 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18815 (get-char-property s 'invisible)))
18817 (defun org-find-invisible ()
18818 (let ((s (point)))
18819 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18820 (not (get-char-property s 'invisible))))
18823 (defun org-copy-visible (beg end)
18824 "Copy the visible parts of the region."
18825 (interactive "r")
18826 (let (snippets s)
18827 (save-excursion
18828 (save-restriction
18829 (narrow-to-region beg end)
18830 (setq s (goto-char (point-min)))
18831 (while (not (= (point) (point-max)))
18832 (goto-char (org-find-invisible))
18833 (push (buffer-substring s (point)) snippets)
18834 (setq s (goto-char (org-find-visible))))))
18835 (kill-new (apply 'concat (nreverse snippets)))))
18837 (defun org-copy-special ()
18838 "Copy region in table or copy current subtree.
18839 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18840 See the individual commands for more information."
18841 (interactive)
18842 (call-interactively
18843 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18845 (defun org-cut-special ()
18846 "Cut region in table or cut current subtree.
18847 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18848 See the individual commands for more information."
18849 (interactive)
18850 (call-interactively
18851 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18853 (defun org-paste-special (arg)
18854 "Paste rectangular region into table, or past subtree relative to level.
18855 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18856 See the individual commands for more information."
18857 (interactive "P")
18858 (if (org-at-table-p)
18859 (org-table-paste-rectangle)
18860 (org-paste-subtree arg)))
18862 (defun org-edit-special (&optional arg)
18863 "Call a special editor for the stuff at point.
18864 When at a table, call the formula editor with `org-table-edit-formulas'.
18865 When at the first line of an src example, call `org-edit-src-code'.
18866 When in an #+include line, visit the include file. Otherwise call
18867 `ffap' to visit the file at point."
18868 (interactive)
18869 ;; possibly prep session before editing source
18870 (when arg
18871 (let* ((info (org-babel-get-src-block-info))
18872 (lang (nth 0 info))
18873 (params (nth 2 info))
18874 (session (cdr (assoc :session params))))
18875 (when (and info session) ;; we are in a source-code block with a session
18876 (funcall
18877 (intern (concat "org-babel-prep-session:" lang)) session params))))
18878 (cond ;; proceed with `org-edit-special'
18879 ((save-excursion
18880 (beginning-of-line 1)
18881 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18882 (find-file (org-trim (match-string 1))))
18883 ((org-edit-src-code))
18884 ((org-edit-fixed-width-region))
18885 ((org-at-table.el-p)
18886 (org-edit-src-code))
18887 ((or (org-at-table-p)
18888 (save-excursion
18889 (beginning-of-line 1)
18890 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18891 (call-interactively 'org-table-edit-formulas))
18892 (t (call-interactively 'ffap))))
18894 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18895 (defun org-ctrl-c-ctrl-c (&optional arg)
18896 "Set tags in headline, or update according to changed information at point.
18898 This command does many different things, depending on context:
18900 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18901 this is what we do.
18903 - If the cursor is on a statistics cookie, update it.
18905 - If the cursor is in a headline, prompt for tags and insert them
18906 into the current line, aligned to `org-tags-column'. When called
18907 with prefix arg, realign all tags in the current buffer.
18909 - If the cursor is in one of the special #+KEYWORD lines, this
18910 triggers scanning the buffer for these lines and updating the
18911 information.
18913 - If the cursor is inside a table, realign the table. This command
18914 works even if the automatic table editor has been turned off.
18916 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18917 the entire table.
18919 - If the cursor is at a footnote reference or definition, jump to
18920 the corresponding definition or references, respectively.
18922 - If the cursor is a the beginning of a dynamic block, update it.
18924 - If the current buffer is a capture buffer, close note and file it.
18926 - If the cursor is on a <<<target>>>, update radio targets and
18927 corresponding links in this buffer.
18929 - If the cursor is on a numbered item in a plain list, renumber the
18930 ordered list.
18932 - If the cursor is on a checkbox, toggle it.
18934 - If the cursor is on a code block, evaluate it. The variable
18935 `org-confirm-babel-evaluate' can be used to control prompting
18936 before code block evaluation, by default every code block
18937 evaluation requires confirmation. Code block evaluation can be
18938 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18939 (interactive "P")
18940 (let ((org-enable-table-editor t))
18941 (cond
18942 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18943 org-occur-highlights
18944 org-latex-fragment-image-overlays)
18945 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18946 (org-remove-occur-highlights)
18947 (org-remove-latex-fragment-image-overlays)
18948 (message "Temporary highlights/overlays removed from current buffer"))
18949 ((and (local-variable-p 'org-finish-function (current-buffer))
18950 (fboundp org-finish-function))
18951 (funcall org-finish-function))
18952 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18953 ((org-in-regexp org-ts-regexp-both)
18954 (org-timestamp-change 0 'day))
18955 ((or (looking-at org-property-start-re)
18956 (org-at-property-p))
18957 (call-interactively 'org-property-action))
18958 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18959 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18960 (or (org-at-heading-p) (org-at-item-p)))
18961 (call-interactively 'org-update-statistics-cookies))
18962 ((org-at-heading-p) (call-interactively 'org-set-tags))
18963 ((org-at-table.el-p)
18964 (message "Use C-c ' to edit table.el tables"))
18965 ((org-at-table-p)
18966 (org-table-maybe-eval-formula)
18967 (if arg
18968 (call-interactively 'org-table-recalculate)
18969 (org-table-maybe-recalculate-line))
18970 (call-interactively 'org-table-align)
18971 (orgtbl-send-table 'maybe))
18972 ((or (org-footnote-at-reference-p)
18973 (org-footnote-at-definition-p))
18974 (call-interactively 'org-footnote-action))
18975 ((org-at-item-checkbox-p)
18976 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18977 ;; list only if at top item.
18978 (let* ((cbox (match-string 1))
18979 (struct (org-list-struct))
18980 (old-struct (copy-tree struct))
18981 (parents (org-list-parents-alist struct))
18982 (orderedp (org-entry-get nil "ORDERED"))
18983 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18984 block-item)
18985 ;; Use a light version of `org-toggle-checkbox' to avoid
18986 ;; computing list structure twice.
18987 (let ((new-box (cond
18988 ((equal arg '(16)) "[-]")
18989 ((equal arg '(4)) nil)
18990 ((equal "[X]" cbox) "[ ]")
18991 (t "[X]"))))
18992 (if (and firstp arg)
18993 ;; If at first item of sub-list, remove check-box from
18994 ;; every item at the same level.
18995 (mapc
18996 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18997 (org-list-get-all-items
18998 (point-at-bol) struct (org-list-prevs-alist struct)))
18999 (org-list-set-checkbox (point-at-bol) struct new-box)))
19000 ;; Replicate `org-list-write-struct', while grabbing a return
19001 ;; value from `org-list-struct-fix-box'.
19002 (org-list-struct-fix-ind struct parents 2)
19003 (org-list-struct-fix-item-end struct)
19004 (let ((prevs (org-list-prevs-alist struct)))
19005 (org-list-struct-fix-bul struct prevs)
19006 (org-list-struct-fix-ind struct parents)
19007 (setq block-item
19008 (org-list-struct-fix-box struct parents prevs orderedp)))
19009 (org-list-struct-apply-struct struct old-struct)
19010 (org-update-checkbox-count-maybe)
19011 (when block-item
19012 (message
19013 "Checkboxes were removed due to unchecked box at line %d"
19014 (org-current-line block-item)))
19015 (when firstp (org-list-send-list 'maybe))))
19016 ((org-at-item-p)
19017 ;; Cursor at an item: repair list. Do checkbox related actions
19018 ;; only if function was called with an argument. Send list only
19019 ;; if at top item.
19020 (let* ((struct (org-list-struct))
19021 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19022 old-struct)
19023 (when arg
19024 (setq old-struct (copy-tree struct))
19025 (if firstp
19026 ;; If at first item of sub-list, add check-box to every
19027 ;; item at the same level.
19028 (mapc
19029 (lambda (pos)
19030 (unless (org-list-get-checkbox pos struct)
19031 (org-list-set-checkbox pos struct "[ ]")))
19032 (org-list-get-all-items
19033 (point-at-bol) struct (org-list-prevs-alist struct)))
19034 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19035 (org-list-write-struct
19036 struct (org-list-parents-alist struct) old-struct)
19037 (when arg (org-update-checkbox-count-maybe))
19038 (when firstp (org-list-send-list 'maybe))))
19039 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19040 ;; Dynamic block
19041 (beginning-of-line 1)
19042 (save-excursion (org-update-dblock)))
19043 ((save-excursion
19044 (let ((case-fold-search t))
19045 (beginning-of-line 1)
19046 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19047 (cond
19048 ((or (equal (match-string 1) "TBLFM")
19049 (equal (match-string 1) "tblfm"))
19050 ;; Recalculate the table before this line
19051 (save-excursion
19052 (beginning-of-line 1)
19053 (skip-chars-backward " \r\n\t")
19054 (if (org-at-table-p)
19055 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19057 (let ((org-inhibit-startup-visibility-stuff t)
19058 (org-startup-align-all-tables nil))
19059 (when (boundp 'org-table-coordinate-overlays)
19060 (mapc 'delete-overlay org-table-coordinate-overlays)
19061 (setq org-table-coordinate-overlays nil))
19062 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19063 (message "Local setup has been refreshed"))))
19064 ((org-clock-update-time-maybe))
19066 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19067 (error "C-c C-c can do nothing useful at this location"))))))
19069 (defun org-mode-restart ()
19070 "Restart Org-mode, to scan again for special lines.
19071 Also updates the keyword regular expressions."
19072 (interactive)
19073 (org-mode)
19074 (message "Org-mode restarted"))
19076 (defun org-kill-note-or-show-branches ()
19077 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19078 (interactive)
19079 (if (not org-finish-function)
19080 (progn
19081 (hide-subtree)
19082 (call-interactively 'show-branches))
19083 (let ((org-note-abort t))
19084 (funcall org-finish-function))))
19086 (defun org-return (&optional indent)
19087 "Goto next table row or insert a newline.
19088 Calls `org-table-next-row' or `newline', depending on context.
19089 See the individual commands for more information."
19090 (interactive)
19091 (let (org-ts-what)
19092 (cond
19093 ((or (bobp) (org-in-src-block-p))
19094 (if indent (newline-and-indent) (newline)))
19095 ((org-at-table-p)
19096 (org-table-justify-field-maybe)
19097 (call-interactively 'org-table-next-row))
19098 ;; when `newline-and-indent' is called within a list, make sure
19099 ;; text moved stays inside the item.
19100 ((and (org-in-item-p) indent)
19101 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19102 (progn
19103 (save-match-data (newline))
19104 (org-indent-line-to (length (match-string 0))))
19105 (let ((ind (org-get-indentation)))
19106 (newline)
19107 (if (org-looking-back org-list-end-re)
19108 (org-indent-line)
19109 (org-indent-line-to ind)))))
19110 ((and org-return-follows-link
19111 (org-at-timestamp-p t)
19112 (not (eq org-ts-what 'after)))
19113 (org-follow-timestamp-link))
19114 ((and org-return-follows-link
19115 (let ((tprop (get-text-property (point) 'face)))
19116 (or (eq tprop 'org-link)
19117 (and (listp tprop) (memq 'org-link tprop)))))
19118 (call-interactively 'org-open-at-point))
19119 ((and (org-at-heading-p)
19120 (looking-at
19121 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19122 (org-show-entry)
19123 (end-of-line 1)
19124 (newline))
19125 (t (if indent (newline-and-indent) (newline))))))
19127 (defun org-return-indent ()
19128 "Goto next table row or insert a newline and indent.
19129 Calls `org-table-next-row' or `newline-and-indent', depending on
19130 context. See the individual commands for more information."
19131 (interactive)
19132 (org-return t))
19134 (defun org-ctrl-c-star ()
19135 "Compute table, or change heading status of lines.
19136 Calls `org-table-recalculate' or `org-toggle-heading',
19137 depending on context."
19138 (interactive)
19139 (cond
19140 ((org-at-table-p)
19141 (call-interactively 'org-table-recalculate))
19143 ;; Convert all lines in region to list items
19144 (call-interactively 'org-toggle-heading))))
19146 (defun org-ctrl-c-minus ()
19147 "Insert separator line in table or modify bullet status of line.
19148 Also turns a plain line or a region of lines into list items.
19149 Calls `org-table-insert-hline', `org-toggle-item', or
19150 `org-cycle-list-bullet', depending on context."
19151 (interactive)
19152 (cond
19153 ((org-at-table-p)
19154 (call-interactively 'org-table-insert-hline))
19155 ((org-region-active-p)
19156 (call-interactively 'org-toggle-item))
19157 ((org-in-item-p)
19158 (call-interactively 'org-cycle-list-bullet))
19160 (call-interactively 'org-toggle-item))))
19162 (defun org-toggle-item (arg)
19163 "Convert headings or normal lines to items, items to normal lines.
19164 If there is no active region, only the current line is considered.
19166 If the first non blank line in the region is an headline, convert
19167 all headlines to items, shifting text accordingly.
19169 If it is an item, convert all items to normal lines.
19171 If it is normal text, change region into an item. With a prefix
19172 argument ARG, change each line in region into an item."
19173 (interactive "P")
19174 (let ((shift-text
19175 (function
19176 ;; Shift text in current section to IND, from point to END.
19177 ;; The function leaves point to END line.
19178 (lambda (ind end)
19179 (let ((min-i 1000) (end (copy-marker end)))
19180 ;; First determine the minimum indentation (MIN-I) of
19181 ;; the text.
19182 (save-excursion
19183 (catch 'exit
19184 (while (< (point) end)
19185 (let ((i (org-get-indentation)))
19186 (cond
19187 ;; Skip blank lines and inline tasks.
19188 ((looking-at "^[ \t]*$"))
19189 ((looking-at org-outline-regexp-bol))
19190 ;; We can't find less than 0 indentation.
19191 ((zerop i) (throw 'exit (setq min-i 0)))
19192 ((< i min-i) (setq min-i i))))
19193 (forward-line))))
19194 ;; Then indent each line so that a line indented to
19195 ;; MIN-I becomes indented to IND. Ignore blank lines
19196 ;; and inline tasks in the process.
19197 (let ((delta (- ind min-i)))
19198 (while (< (point) end)
19199 (unless (or (looking-at "^[ \t]*$")
19200 (looking-at org-outline-regexp-bol))
19201 (org-indent-line-to (+ (org-get-indentation) delta)))
19202 (forward-line)))))))
19203 (skip-blanks
19204 (function
19205 ;; Return beginning of first non-blank line, starting from
19206 ;; line at POS.
19207 (lambda (pos)
19208 (save-excursion
19209 (goto-char pos)
19210 (skip-chars-forward " \r\t\n")
19211 (point-at-bol)))))
19212 beg end)
19213 ;; Determine boundaries of changes.
19214 (if (org-region-active-p)
19215 (setq beg (funcall skip-blanks (region-beginning))
19216 end (copy-marker (region-end)))
19217 (setq beg (funcall skip-blanks (point-at-bol))
19218 end (copy-marker (point-at-eol))))
19219 ;; Depending on the starting line, choose an action on the text
19220 ;; between BEG and END.
19221 (org-with-limited-levels
19222 (save-excursion
19223 (goto-char beg)
19224 (cond
19225 ;; Case 1. Start at an item: de-itemize. Note that it only
19226 ;; happens when a region is active: `org-ctrl-c-minus'
19227 ;; would call `org-cycle-list-bullet' otherwise.
19228 ((org-at-item-p)
19229 (while (< (point) end)
19230 (when (org-at-item-p)
19231 (skip-chars-forward " \t")
19232 (delete-region (point) (match-end 0)))
19233 (forward-line)))
19234 ;; Case 2. Start at an heading: convert to items.
19235 ((org-at-heading-p)
19236 (let* ((bul (org-list-bullet-string "-"))
19237 (bul-len (length bul))
19238 ;; Indentation of the first heading. It should be
19239 ;; relative to the indentation of its parent, if any.
19240 (start-ind (save-excursion
19241 (cond
19242 ((not org-adapt-indentation) 0)
19243 ((not (outline-previous-heading)) 0)
19244 (t (length (match-string 0))))))
19245 ;; Level of first heading. Further headings will be
19246 ;; compared to it to determine hierarchy in the list.
19247 (ref-level (org-reduced-level (org-outline-level))))
19248 (while (< (point) end)
19249 (let* ((level (org-reduced-level (org-outline-level)))
19250 (delta (max 0 (- level ref-level))))
19251 ;; If current headline is less indented than the first
19252 ;; one, set it as reference, in order to preserve
19253 ;; subtrees.
19254 (when (< level ref-level) (setq ref-level level))
19255 (replace-match bul t t)
19256 (org-indent-line-to (+ start-ind (* delta bul-len)))
19257 ;; Ensure all text down to END (or SECTION-END) belongs
19258 ;; to the newly created item.
19259 (let ((section-end (save-excursion
19260 (or (outline-next-heading) (point)))))
19261 (forward-line)
19262 (funcall shift-text
19263 (+ start-ind (* (1+ delta) bul-len))
19264 (min end section-end)))))))
19265 ;; Case 3. Normal line with ARG: turn each non-item line into
19266 ;; an item.
19267 (arg
19268 (while (< (point) end)
19269 (unless (or (org-at-heading-p) (org-at-item-p))
19270 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19271 (replace-match
19272 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19273 (forward-line)))
19274 ;; Case 4. Normal line without ARG: make the first line of
19275 ;; region an item, and shift indentation of others
19276 ;; lines to set them as item's body.
19277 (t (let* ((bul (org-list-bullet-string "-"))
19278 (bul-len (length bul))
19279 (ref-ind (org-get-indentation)))
19280 (skip-chars-forward " \t")
19281 (insert bul)
19282 (forward-line)
19283 (while (< (point) end)
19284 ;; Ensure that lines less indented than first one
19285 ;; still get included in item body.
19286 (funcall shift-text
19287 (+ ref-ind bul-len)
19288 (min end (save-excursion (or (outline-next-heading)
19289 (point)))))
19290 (forward-line)))))))))
19292 (defun org-toggle-heading (&optional nstars)
19293 "Convert headings to normal text, or items or text to headings.
19294 If there is no active region, only the current line is considered.
19296 With a \\[universal-argument] prefix, convert the whole list at
19297 point into heading.
19299 In a region:
19301 - If the first non blank line is an headline, remove the stars
19302 from all headlines in the region.
19304 - If it is a normal line turn each and every normal line (i.e. not an
19305 heading or an item) in the region into a heading.
19307 - If it is a plain list item, turn all plain list items into headings.
19309 When converting a line into a heading, the number of stars is chosen
19310 such that the lines become children of the current entry. However,
19311 when a prefix argument is given, its value determines the number of
19312 stars to add."
19313 (interactive "P")
19314 (let ((skip-blanks
19315 (function
19316 ;; Return beginning of first non-blank line, starting from
19317 ;; line at POS.
19318 (lambda (pos)
19319 (save-excursion
19320 (goto-char pos)
19321 (while (org-at-comment-p) (forward-line))
19322 (skip-chars-forward " \r\t\n")
19323 (point-at-bol)))))
19324 beg end toggled)
19325 ;; Determine boundaries of changes. If a universal prefix has
19326 ;; been given, put the list in a region. If region ends at a bol,
19327 ;; do not consider the last line to be in the region.
19329 (when (and current-prefix-arg (org-at-item-p))
19330 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19331 (org-mark-list))
19333 (if (org-region-active-p)
19334 (setq beg (funcall skip-blanks (region-beginning))
19335 end (copy-marker (save-excursion
19336 (goto-char (region-end))
19337 (if (bolp) (point) (point-at-eol)))))
19338 (setq beg (funcall skip-blanks (point-at-bol))
19339 end (copy-marker (point-at-eol))))
19340 ;; Ensure inline tasks don't count as headings.
19341 (org-with-limited-levels
19342 (save-excursion
19343 (goto-char beg)
19344 (cond
19345 ;; Case 1. Started at an heading: de-star headings.
19346 ((org-at-heading-p)
19347 (while (< (point) end)
19348 (when (org-at-heading-p t)
19349 (looking-at org-outline-regexp) (replace-match "")
19350 (setq toggled t))
19351 (forward-line)))
19352 ;; Case 2. Started at an item: change items into headlines.
19353 ;; One star will be added by `org-list-to-subtree'.
19354 ((org-at-item-p)
19355 (let* ((stars (make-string
19356 (if nstars
19357 ;; subtract the star that will be added again by
19358 ;; `org-list-to-subtree'
19359 (1- (prefix-numeric-value current-prefix-arg))
19360 (or (org-current-level) 0))
19361 ?*))
19362 (add-stars
19363 (cond (nstars "") ; stars from prefix only
19364 ((equal stars "") "") ; before first heading
19365 (org-odd-levels-only "*") ; inside heading, odd
19366 (t "")))) ; inside heading, oddeven
19367 (while (< (point) end)
19368 (when (org-at-item-p)
19369 ;; Pay attention to cases when region ends before list.
19370 (let* ((struct (org-list-struct))
19371 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19372 (save-restriction
19373 (narrow-to-region (point) list-end)
19374 (insert
19375 (org-list-to-subtree
19376 (org-list-parse-list t)
19377 '(:istart (concat stars add-stars (funcall get-stars depth))
19378 :icount (concat stars add-stars (funcall get-stars depth)))))))
19379 (setq toggled t))
19380 (forward-line))))
19381 ;; Case 3. Started at normal text: make every line an heading,
19382 ;; skipping headlines and items.
19383 (t (let* ((stars (make-string
19384 (if nstars
19385 (prefix-numeric-value current-prefix-arg)
19386 (or (org-current-level) 0))
19387 ?*))
19388 (add-stars
19389 (cond (nstars "") ; stars from prefix only
19390 ((equal stars "") "*") ; before first heading
19391 (org-odd-levels-only "**") ; inside heading, odd
19392 (t "*"))) ; inside heading, oddeven
19393 (rpl (concat stars add-stars " ")))
19394 (while (< (point) end)
19395 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19396 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19397 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19398 (forward-line)))))))
19399 (unless toggled (message "Cannot toggle heading from here"))))
19401 (defun org-meta-return (&optional arg)
19402 "Insert a new heading or wrap a region in a table.
19403 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19404 See the individual commands for more information."
19405 (interactive "P")
19406 (cond
19407 ((run-hook-with-args-until-success 'org-metareturn-hook))
19408 ((or (org-at-drawer-p) (org-at-property-p))
19409 (newline-and-indent))
19410 ((org-at-table-p)
19411 (call-interactively 'org-table-wrap-region))
19412 (t (call-interactively 'org-insert-heading))))
19414 ;;; Menu entries
19416 ;; Define the Org-mode menus
19417 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19418 '("Tbl"
19419 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19420 ["Next Field" org-cycle (org-at-table-p)]
19421 ["Previous Field" org-shifttab (org-at-table-p)]
19422 ["Next Row" org-return (org-at-table-p)]
19423 "--"
19424 ["Blank Field" org-table-blank-field (org-at-table-p)]
19425 ["Edit Field" org-table-edit-field (org-at-table-p)]
19426 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19427 "--"
19428 ("Column"
19429 ["Move Column Left" org-metaleft (org-at-table-p)]
19430 ["Move Column Right" org-metaright (org-at-table-p)]
19431 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19432 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19433 ("Row"
19434 ["Move Row Up" org-metaup (org-at-table-p)]
19435 ["Move Row Down" org-metadown (org-at-table-p)]
19436 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19437 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19438 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19439 "--"
19440 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19441 ("Rectangle"
19442 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19443 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19444 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19445 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19446 "--"
19447 ("Calculate"
19448 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19449 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19450 ["Edit Formulas" org-edit-special (org-at-table-p)]
19451 "--"
19452 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19453 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19454 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19455 "--"
19456 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19457 "--"
19458 ["Sum Column/Rectangle" org-table-sum
19459 (or (org-at-table-p) (org-region-active-p))]
19460 ["Which Column?" org-table-current-column (org-at-table-p)])
19461 ["Debug Formulas"
19462 org-table-toggle-formula-debugger
19463 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19464 ["Show Col/Row Numbers"
19465 org-table-toggle-coordinate-overlays
19466 :style toggle
19467 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19468 "--"
19469 ["Create" org-table-create (and (not (org-at-table-p))
19470 org-enable-table-editor)]
19471 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19472 ["Import from File" org-table-import (not (org-at-table-p))]
19473 ["Export to File" org-table-export (org-at-table-p)]
19474 "--"
19475 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19477 (easy-menu-define org-org-menu org-mode-map "Org menu"
19478 '("Org"
19479 ("Show/Hide"
19480 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19481 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19482 ["Sparse Tree..." org-sparse-tree t]
19483 ["Reveal Context" org-reveal t]
19484 ["Show All" show-all t]
19485 "--"
19486 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19487 "--"
19488 ["New Heading" org-insert-heading t]
19489 ("Navigate Headings"
19490 ["Up" outline-up-heading t]
19491 ["Next" outline-next-visible-heading t]
19492 ["Previous" outline-previous-visible-heading t]
19493 ["Next Same Level" outline-forward-same-level t]
19494 ["Previous Same Level" outline-backward-same-level t]
19495 "--"
19496 ["Jump" org-goto t])
19497 ("Edit Structure"
19498 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19499 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19500 "--"
19501 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19502 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19503 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19504 "--"
19505 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19506 "--"
19507 ["Copy visible text" org-copy-visible t]
19508 "--"
19509 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19510 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19511 ["Demote Heading" org-metaright (not (org-at-table-p))]
19512 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19513 "--"
19514 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19515 "--"
19516 ["Convert to odd levels" org-convert-to-odd-levels t]
19517 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19518 ("Editing"
19519 ["Emphasis..." org-emphasize t]
19520 ["Edit Source Example" org-edit-special t]
19521 "--"
19522 ["Footnote new/jump" org-footnote-action t]
19523 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19524 ("Archive"
19525 ["Archive (default method)" org-archive-subtree-default t]
19526 "--"
19527 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19528 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19529 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19531 "--"
19532 ("Hyperlinks"
19533 ["Store Link (Global)" org-store-link t]
19534 ["Find existing link to here" org-occur-link-in-agenda-files t]
19535 ["Insert Link" org-insert-link t]
19536 ["Follow Link" org-open-at-point t]
19537 "--"
19538 ["Next link" org-next-link t]
19539 ["Previous link" org-previous-link t]
19540 "--"
19541 ["Descriptive Links"
19542 org-toggle-link-display
19543 :style radio
19544 :selected org-descriptive-links
19546 ["Literal Links"
19547 org-toggle-link-display
19548 :style radio
19549 :selected (not org-descriptive-links)])
19550 "--"
19551 ("TODO Lists"
19552 ["TODO/DONE/-" org-todo t]
19553 ("Select keyword"
19554 ["Next keyword" org-shiftright (org-at-heading-p)]
19555 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19556 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19557 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19558 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19559 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19560 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19561 "--"
19562 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19563 :selected org-enforce-todo-dependencies :style toggle :active t]
19564 "Settings for tree at point"
19565 ["Do Children sequentially" org-toggle-ordered-property :style radio
19566 :selected (org-entry-get nil "ORDERED")
19567 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19568 ["Do Children parallel" org-toggle-ordered-property :style radio
19569 :selected (not (org-entry-get nil "ORDERED"))
19570 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19571 "--"
19572 ["Set Priority" org-priority t]
19573 ["Priority Up" org-shiftup t]
19574 ["Priority Down" org-shiftdown t]
19575 "--"
19576 ["Get news from all feeds" org-feed-update-all t]
19577 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19578 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19579 ("TAGS and Properties"
19580 ["Set Tags" org-set-tags-command t]
19581 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19582 "--"
19583 ["Set property" org-set-property t]
19584 ["Column view of properties" org-columns t]
19585 ["Insert Column View DBlock" org-insert-columns-dblock t])
19586 ("Dates and Scheduling"
19587 ["Timestamp" org-time-stamp t]
19588 ["Timestamp (inactive)" org-time-stamp-inactive t]
19589 ("Change Date"
19590 ["1 Day Later" org-shiftright t]
19591 ["1 Day Earlier" org-shiftleft t]
19592 ["1 ... Later" org-shiftup t]
19593 ["1 ... Earlier" org-shiftdown t])
19594 ["Compute Time Range" org-evaluate-time-range t]
19595 ["Schedule Item" org-schedule t]
19596 ["Deadline" org-deadline t]
19597 "--"
19598 ["Custom time format" org-toggle-time-stamp-overlays
19599 :style radio :selected org-display-custom-times]
19600 "--"
19601 ["Goto Calendar" org-goto-calendar t]
19602 ["Date from Calendar" org-date-from-calendar t]
19603 "--"
19604 ["Start/Restart Timer" org-timer-start t]
19605 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19606 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19607 ["Insert Timer String" org-timer t]
19608 ["Insert Timer Item" org-timer-item t])
19609 ("Logging work"
19610 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19611 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19612 ["Clock out" org-clock-out t]
19613 ["Clock cancel" org-clock-cancel t]
19614 "--"
19615 ["Mark as default task" org-clock-mark-default-task t]
19616 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19617 ["Goto running clock" org-clock-goto t]
19618 "--"
19619 ["Display times" org-clock-display t]
19620 ["Create clock table" org-clock-report t]
19621 "--"
19622 ["Record DONE time"
19623 (progn (setq org-log-done (not org-log-done))
19624 (message "Switching to %s will %s record a timestamp"
19625 (car org-done-keywords)
19626 (if org-log-done "automatically" "not")))
19627 :style toggle :selected org-log-done])
19628 "--"
19629 ["Agenda Command..." org-agenda t]
19630 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19631 ("File List for Agenda")
19632 ("Special views current file"
19633 ["TODO Tree" org-show-todo-tree t]
19634 ["Check Deadlines" org-check-deadlines t]
19635 ["Timeline" org-timeline t]
19636 ["Tags/Property tree" org-match-sparse-tree t])
19637 "--"
19638 ["Export/Publish..." org-export t]
19639 ("LaTeX"
19640 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19641 :selected org-cdlatex-mode]
19642 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19643 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19644 ["Modify math symbol" org-cdlatex-math-modify
19645 (org-inside-LaTeX-fragment-p)]
19646 ["Insert citation" org-reftex-citation t]
19647 "--"
19648 ["Template for BEAMER" (progn (require 'org-beamer)
19649 (org-insert-beamer-options-template)) t])
19650 "--"
19651 ("MobileOrg"
19652 ["Push Files and Views" org-mobile-push t]
19653 ["Get Captured and Flagged" org-mobile-pull t]
19654 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19655 "--"
19656 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19657 "--"
19658 ("Documentation"
19659 ["Show Version" org-version t]
19660 ["Info Documentation" org-info t])
19661 ("Customize"
19662 ["Browse Org Group" org-customize t]
19663 "--"
19664 ["Expand This Menu" org-create-customize-menu
19665 (fboundp 'customize-menu-create)])
19666 ["Send bug report" org-submit-bug-report t]
19667 "--"
19668 ("Refresh/Reload"
19669 ["Refresh setup current buffer" org-mode-restart t]
19670 ["Reload Org (after update)" org-reload t]
19671 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19674 (defun org-info (&optional node)
19675 "Read documentation for Org-mode in the info system.
19676 With optional NODE, go directly to that node."
19677 (interactive)
19678 (info (format "(org)%s" (or node ""))))
19680 ;;;###autoload
19681 (defun org-submit-bug-report ()
19682 "Submit a bug report on Org-mode via mail.
19684 Don't hesitate to report any problems or inaccurate documentation.
19686 If you don't have setup sending mail from (X)Emacs, please copy the
19687 output buffer into your mail program, as it gives us important
19688 information about your Org-mode version and configuration."
19689 (interactive)
19690 (require 'reporter)
19691 (org-load-modules-maybe)
19692 (org-require-autoloaded-modules)
19693 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19694 (reporter-submit-bug-report
19695 "emacs-orgmode@gnu.org"
19696 (org-version nil 'full)
19697 (let (list)
19698 (save-window-excursion
19699 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19700 (delete-other-windows)
19701 (erase-buffer)
19702 (insert "You are about to submit a bug report to the Org-mode mailing list.
19704 We would like to add your full Org-mode and Outline configuration to the
19705 bug report. This greatly simplifies the work of the maintainer and
19706 other experts on the mailing list.
19708 HOWEVER, some variables you have customized may contain private
19709 information. The names of customers, colleagues, or friends, might
19710 appear in the form of file names, tags, todo states, or search strings.
19711 If you answer yes to the prompt, you might want to check and remove
19712 such private information before sending the email.")
19713 (add-text-properties (point-min) (point-max) '(face org-warning))
19714 (when (yes-or-no-p "Include your Org-mode configuration ")
19715 (mapatoms
19716 (lambda (v)
19717 (and (boundp v)
19718 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19719 (or (and (symbol-value v)
19720 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19721 (and
19722 (get v 'custom-type) (get v 'standard-value)
19723 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19724 (push v list)))))
19725 (kill-buffer (get-buffer "*Warn about privacy*"))
19726 list))
19727 nil nil
19728 "Remember to cover the basics, that is, what you expected to happen and
19729 what in fact did happen. You don't know how to make a good report? See
19731 http://orgmode.org/manual/Feedback.html#Feedback
19733 Your bug report will be posted to the Org-mode mailing list.
19734 ------------------------------------------------------------------------")
19735 (save-excursion
19736 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19737 (replace-match "\\1Bug: \\3 [\\2]")))))
19740 (defun org-install-agenda-files-menu ()
19741 (let ((bl (buffer-list)))
19742 (save-excursion
19743 (while bl
19744 (set-buffer (pop bl))
19745 (if (derived-mode-p 'org-mode) (setq bl nil)))
19746 (when (derived-mode-p 'org-mode)
19747 (easy-menu-change
19748 '("Org") "File List for Agenda"
19749 (append
19750 (list
19751 ["Edit File List" (org-edit-agenda-file-list) t]
19752 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19753 ["Remove Current File from List" org-remove-file t]
19754 ["Cycle through agenda files" org-cycle-agenda-files t]
19755 ["Occur in all agenda files" org-occur-in-agenda-files t]
19756 "--")
19757 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19759 ;;;; Documentation
19761 ;;;###autoload
19762 (defun org-require-autoloaded-modules ()
19763 (interactive)
19764 (mapc 'require
19765 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19766 org-docbook org-exp org-html org-icalendar
19767 org-id org-latex
19768 org-publish org-remember org-table
19769 org-timer org-xoxo)))
19771 ;;;###autoload
19772 (defun org-reload (&optional uncompiled)
19773 "Reload all org lisp files.
19774 With prefix arg UNCOMPILED, load the uncompiled versions."
19775 (interactive "P")
19776 (require 'find-func)
19777 (let* ((file-re "^org\\(-.*\\)?\\.el")
19778 (dir-org (file-name-directory (org-find-library-dir "org")))
19779 (dir-org-contrib (ignore-errors
19780 (file-name-directory
19781 (org-find-library-dir "org-contribdir"))))
19782 (babel-files
19783 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19784 (append (list nil "comint" "eval" "exp" "keys"
19785 "lob" "ref" "table" "tangle")
19786 (delq nil
19787 (mapcar
19788 (lambda (lang)
19789 (when (cdr lang) (symbol-name (car lang))))
19790 org-babel-load-languages)))))
19791 (files
19792 (append babel-files
19793 (and dir-org-contrib
19794 (directory-files dir-org-contrib t file-re))
19795 (directory-files dir-org t file-re)))
19796 (remove-re (concat (if (featurep 'xemacs)
19797 "org-colview" "org-colview-xemacs")
19798 "\\'")))
19799 (setq files (mapcar 'file-name-sans-extension files))
19800 (setq files (mapcar
19801 (lambda (x) (if (string-match remove-re x) nil x))
19802 files))
19803 (setq files (delq nil files))
19804 (mapc
19805 (lambda (f)
19806 (when (featurep (intern (file-name-nondirectory f)))
19807 (if (and (not uncompiled)
19808 (file-exists-p (concat f ".elc")))
19809 (load (concat f ".elc") nil nil 'nosuffix)
19810 (load (concat f ".el") nil nil 'nosuffix))))
19811 files)
19812 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19813 (org-version nil 'full 'message))
19815 ;;;###autoload
19816 (defun org-customize ()
19817 "Call the customize function with org as argument."
19818 (interactive)
19819 (org-load-modules-maybe)
19820 (org-require-autoloaded-modules)
19821 (customize-browse 'org))
19823 (defun org-create-customize-menu ()
19824 "Create a full customization menu for Org-mode, insert it into the menu."
19825 (interactive)
19826 (org-load-modules-maybe)
19827 (org-require-autoloaded-modules)
19828 (if (fboundp 'customize-menu-create)
19829 (progn
19830 (easy-menu-change
19831 '("Org") "Customize"
19832 `(["Browse Org group" org-customize t]
19833 "--"
19834 ,(customize-menu-create 'org)
19835 ["Set" Custom-set t]
19836 ["Save" Custom-save t]
19837 ["Reset to Current" Custom-reset-current t]
19838 ["Reset to Saved" Custom-reset-saved t]
19839 ["Reset to Standard Settings" Custom-reset-standard t]))
19840 (message "\"Org\"-menu now contains full customization menu"))
19841 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19843 ;;;; Miscellaneous stuff
19845 ;;; Generally useful functions
19847 (defun org-get-at-bol (property)
19848 "Get text property PROPERTY at beginning of line."
19849 (get-text-property (point-at-bol) property))
19851 (defun org-find-text-property-in-string (prop s)
19852 "Return the first non-nil value of property PROP in string S."
19853 (or (get-text-property 0 prop s)
19854 (get-text-property (or (next-single-property-change 0 prop s) 0)
19855 prop s)))
19857 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19858 "Display the given MESSAGE as a warning."
19859 (if (fboundp 'display-warning)
19860 (display-warning 'org message
19861 (if (featurep 'xemacs) 'warning :warning))
19862 (let ((buf (get-buffer-create "*Org warnings*")))
19863 (with-current-buffer buf
19864 (goto-char (point-max))
19865 (insert "Warning (Org): " message)
19866 (unless (bolp)
19867 (newline)))
19868 (display-buffer buf)
19869 (sit-for 0))))
19871 (defun org-eval (form)
19872 "Eval FORM and return result."
19873 (condition-case error
19874 (eval form)
19875 (error (format "%%![Error: %s]" error))))
19877 (defun org-in-clocktable-p ()
19878 "Check if the cursor is in a clocktable."
19879 (let ((pos (point)) start)
19880 (save-excursion
19881 (end-of-line 1)
19882 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19883 (setq start (match-beginning 0))
19884 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19885 (>= (match-end 0) pos)
19886 start))))
19888 (defun org-in-commented-line ()
19889 "Is point in a line starting with `#'?"
19890 (equal (char-after (point-at-bol)) ?#))
19892 (defun org-in-indented-comment-line ()
19893 "Is point in a line starting with `#' after some white space?"
19894 (save-excursion
19895 (save-match-data
19896 (goto-char (point-at-bol))
19897 (looking-at "[ \t]*#"))))
19899 (defun org-in-verbatim-emphasis ()
19900 (save-match-data
19901 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19903 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19904 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19905 (if (and marker (marker-buffer marker)
19906 (buffer-live-p (marker-buffer marker)))
19907 (progn
19908 (org-pop-to-buffer-same-window (marker-buffer marker))
19909 (if (or (> marker (point-max)) (< marker (point-min)))
19910 (widen))
19911 (goto-char marker)
19912 (org-show-context 'org-goto))
19913 (if bookmark
19914 (bookmark-jump bookmark)
19915 (error "Cannot find location"))))
19917 (defun org-quote-csv-field (s)
19918 "Quote field for inclusion in CSV material."
19919 (if (string-match "[\",]" s)
19920 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19923 (defun org-force-self-insert (N)
19924 "Needed to enforce self-insert under remapping."
19925 (interactive "p")
19926 (self-insert-command N))
19928 (defun org-string-width (s)
19929 "Compute width of string, ignoring invisible characters.
19930 This ignores character with invisibility property `org-link', and also
19931 characters with property `org-cwidth', because these will become invisible
19932 upon the next fontification round."
19933 (let (b l)
19934 (when (or (eq t buffer-invisibility-spec)
19935 (assq 'org-link buffer-invisibility-spec))
19936 (while (setq b (text-property-any 0 (length s)
19937 'invisible 'org-link s))
19938 (setq s (concat (substring s 0 b)
19939 (substring s (or (next-single-property-change
19940 b 'invisible s) (length s)))))))
19941 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19942 (setq s (concat (substring s 0 b)
19943 (substring s (or (next-single-property-change
19944 b 'org-cwidth s) (length s))))))
19945 (setq l (string-width s) b -1)
19946 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19947 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19950 (defun org-shorten-string (s maxlength)
19951 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19952 If the string is shorter or has length MAXLENGTH, just return the
19953 original string. If it is longer, the functions finds a space in the
19954 string, breaks this string off at that locations and adds three dots
19955 as ellipsis. Including the ellipsis, the string will not be longer
19956 than MAXLENGTH. If finding a good breaking point in the string does
19957 not work, the string is just chopped off in the middle of a word
19958 if necessary."
19959 (if (<= (length s) maxlength)
19961 (let* ((n (max (- maxlength 4) 1))
19962 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19963 (if (string-match re s)
19964 (concat (match-string 1 s) "...")
19965 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19967 (defun org-get-indentation (&optional line)
19968 "Get the indentation of the current line, interpreting tabs.
19969 When LINE is given, assume it represents a line and compute its indentation."
19970 (if line
19971 (if (string-match "^ *" (org-remove-tabs line))
19972 (match-end 0))
19973 (save-excursion
19974 (beginning-of-line 1)
19975 (skip-chars-forward " \t")
19976 (current-column))))
19978 (defun org-get-string-indentation (s)
19979 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19980 (let ((n -1) (i 0) (w tab-width) c)
19981 (catch 'exit
19982 (while (< (setq n (1+ n)) (length s))
19983 (setq c (aref s n))
19984 (cond ((= c ?\ ) (setq i (1+ i)))
19985 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19986 (t (throw 'exit t)))))
19989 (defun org-remove-tabs (s &optional width)
19990 "Replace tabulators in S with spaces.
19991 Assumes that s is a single line, starting in column 0."
19992 (setq width (or width tab-width))
19993 (while (string-match "\t" s)
19994 (setq s (replace-match
19995 (make-string
19996 (- (* width (/ (+ (match-beginning 0) width) width))
19997 (match-beginning 0)) ?\ )
19998 t t s)))
20001 (defun org-fix-indentation (line ind)
20002 "Fix indentation in LINE.
20003 IND is a cons cell with target and minimum indentation.
20004 If the current indentation in LINE is smaller than the minimum,
20005 leave it alone. If it is larger than ind, set it to the target."
20006 (let* ((l (org-remove-tabs line))
20007 (i (org-get-indentation l))
20008 (i1 (car ind)) (i2 (cdr ind)))
20009 (if (>= i i2) (setq l (substring line i2)))
20010 (if (> i1 0)
20011 (concat (make-string i1 ?\ ) l)
20012 l)))
20014 (defun org-remove-indentation (code &optional n)
20015 "Remove the maximum common indentation from the lines in CODE.
20016 N may optionally be the number of spaces to remove."
20017 (with-temp-buffer
20018 (insert code)
20019 (org-do-remove-indentation n)
20020 (buffer-string)))
20022 (defun org-do-remove-indentation (&optional n)
20023 "Remove the maximum common indentation from the buffer."
20024 (untabify (point-min) (point-max))
20025 (let ((min 10000) re)
20026 (if n
20027 (setq min n)
20028 (goto-char (point-min))
20029 (while (re-search-forward "^ *[^ \n]" nil t)
20030 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20031 (unless (or (= min 0) (= min 10000))
20032 (setq re (format "^ \\{%d\\}" min))
20033 (goto-char (point-min))
20034 (while (re-search-forward re nil t)
20035 (replace-match "")
20036 (end-of-line 1))
20037 min)))
20039 (defun org-fill-template (template alist)
20040 "Find each %key of ALIST in TEMPLATE and replace it."
20041 (let ((case-fold-search nil)
20042 entry key value)
20043 (setq alist (sort (copy-sequence alist)
20044 (lambda (a b) (< (length (car a)) (length (car b))))))
20045 (while (setq entry (pop alist))
20046 (setq template
20047 (replace-regexp-in-string
20048 (concat "%" (regexp-quote (car entry)))
20049 (cdr entry) template t t)))
20050 template))
20052 (defun org-base-buffer (buffer)
20053 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20054 (if (not buffer)
20055 buffer
20056 (or (buffer-base-buffer buffer)
20057 buffer)))
20059 (defun org-trim (s)
20060 "Remove whitespace at beginning and end of string."
20061 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20062 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20065 (defun org-wrap (string &optional width lines)
20066 "Wrap string to either a number of lines, or a width in characters.
20067 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20068 that costs. If there is a word longer than WIDTH, the text is actually
20069 wrapped to the length of that word.
20070 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20071 many lines, whatever width that takes.
20072 The return value is a list of lines, without newlines at the end."
20073 (let* ((words (org-split-string string "[ \t\n]+"))
20074 (maxword (apply 'max (mapcar 'org-string-width words)))
20075 w ll)
20076 (cond (width
20077 (org-do-wrap words (max maxword width)))
20078 (lines
20079 (setq w maxword)
20080 (setq ll (org-do-wrap words maxword))
20081 (if (<= (length ll) lines)
20083 (setq ll words)
20084 (while (> (length ll) lines)
20085 (setq w (1+ w))
20086 (setq ll (org-do-wrap words w)))
20087 ll))
20088 (t (error "Cannot wrap this")))))
20090 (defun org-do-wrap (words width)
20091 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20092 (let (lines line)
20093 (while words
20094 (setq line (pop words))
20095 (while (and words (< (+ (length line) (length (car words))) width))
20096 (setq line (concat line " " (pop words))))
20097 (setq lines (push line lines)))
20098 (nreverse lines)))
20100 (defun org-split-string (string &optional separators)
20101 "Splits STRING into substrings at SEPARATORS.
20102 No empty strings are returned if there are matches at the beginning
20103 and end of string."
20104 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20105 (start 0)
20106 notfirst
20107 (list nil))
20108 (while (and (string-match rexp string
20109 (if (and notfirst
20110 (= start (match-beginning 0))
20111 (< start (length string)))
20112 (1+ start) start))
20113 (< (match-beginning 0) (length string)))
20114 (setq notfirst t)
20115 (or (eq (match-beginning 0) 0)
20116 (and (eq (match-beginning 0) (match-end 0))
20117 (eq (match-beginning 0) start))
20118 (setq list
20119 (cons (substring string start (match-beginning 0))
20120 list)))
20121 (setq start (match-end 0)))
20122 (or (eq start (length string))
20123 (setq list
20124 (cons (substring string start)
20125 list)))
20126 (nreverse list)))
20128 (defun org-quote-vert (s)
20129 "Replace \"|\" with \"\\vert\"."
20130 (while (string-match "|" s)
20131 (setq s (replace-match "\\vert" t t s)))
20134 (defun org-uuidgen-p (s)
20135 "Is S an ID created by UUIDGEN?"
20136 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20138 (defun org-in-src-block-p nil
20139 "Whether point is in a code source block."
20140 (let (ov)
20141 (when (setq ov (overlays-at (point)))
20142 (memq 'org-block-background
20143 (overlay-properties
20144 (car ov))))))
20146 (defun org-context ()
20147 "Return a list of contexts of the current cursor position.
20148 If several contexts apply, all are returned.
20149 Each context entry is a list with a symbol naming the context, and
20150 two positions indicating start and end of the context. Possible
20151 contexts are:
20153 :headline anywhere in a headline
20154 :headline-stars on the leading stars in a headline
20155 :todo-keyword on a TODO keyword (including DONE) in a headline
20156 :tags on the TAGS in a headline
20157 :priority on the priority cookie in a headline
20158 :item on the first line of a plain list item
20159 :item-bullet on the bullet/number of a plain list item
20160 :checkbox on the checkbox in a plain list item
20161 :table in an org-mode table
20162 :table-special on a special filed in a table
20163 :table-table in a table.el table
20164 :clocktable in a clocktable
20165 :src-block in a source block
20166 :link on a hyperlink
20167 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20168 :target on a <<target>>
20169 :radio-target on a <<<radio-target>>>
20170 :latex-fragment on a LaTeX fragment
20171 :latex-preview on a LaTeX fragment with overlaid preview image
20173 This function expects the position to be visible because it uses font-lock
20174 faces as a help to recognize the following contexts: :table-special, :link,
20175 and :keyword."
20176 (let* ((f (get-text-property (point) 'face))
20177 (faces (if (listp f) f (list f)))
20178 (case-fold-search t)
20179 (p (point)) clist o)
20180 ;; First the large context
20181 (cond
20182 ((org-at-heading-p t)
20183 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20184 (when (progn
20185 (beginning-of-line 1)
20186 (looking-at org-todo-line-tags-regexp))
20187 (push (org-point-in-group p 1 :headline-stars) clist)
20188 (push (org-point-in-group p 2 :todo-keyword) clist)
20189 (push (org-point-in-group p 4 :tags) clist))
20190 (goto-char p)
20191 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20192 (if (looking-at "\\[#[A-Z0-9]\\]")
20193 (push (org-point-in-group p 0 :priority) clist)))
20195 ((org-at-item-p)
20196 (push (org-point-in-group p 2 :item-bullet) clist)
20197 (push (list :item (point-at-bol)
20198 (save-excursion (org-end-of-item) (point)))
20199 clist)
20200 (and (org-at-item-checkbox-p)
20201 (push (org-point-in-group p 0 :checkbox) clist)))
20203 ((org-at-table-p)
20204 (push (list :table (org-table-begin) (org-table-end)) clist)
20205 (if (memq 'org-formula faces)
20206 (push (list :table-special
20207 (previous-single-property-change p 'face)
20208 (next-single-property-change p 'face)) clist)))
20209 ((org-at-table-p 'any)
20210 (push (list :table-table) clist)))
20211 (goto-char p)
20213 ;; New the "medium" contexts: clocktables, source blocks
20214 (cond ((org-in-clocktable-p)
20215 (push (list :clocktable
20216 (and (or (looking-at "#\\+BEGIN: clocktable")
20217 (search-backward "#+BEGIN: clocktable" nil t))
20218 (match-beginning 0))
20219 (and (re-search-forward "#\\+END:?" nil t)
20220 (match-end 0))) clist))
20221 ((org-in-src-block-p)
20222 (push (list :src-block
20223 (and (or (looking-at "#\\+BEGIN_SRC")
20224 (search-backward "#+BEGIN_SRC" nil t))
20225 (match-beginning 0))
20226 (and (search-forward "#+END_SRC" nil t)
20227 (match-beginning 0))) clist)))
20228 (goto-char p)
20230 ;; Now the small context
20231 (cond
20232 ((org-at-timestamp-p)
20233 (push (org-point-in-group p 0 :timestamp) clist))
20234 ((memq 'org-link faces)
20235 (push (list :link
20236 (previous-single-property-change p 'face)
20237 (next-single-property-change p 'face)) clist))
20238 ((memq 'org-special-keyword faces)
20239 (push (list :keyword
20240 (previous-single-property-change p 'face)
20241 (next-single-property-change p 'face)) clist))
20242 ((org-at-target-p)
20243 (push (org-point-in-group p 0 :target) clist)
20244 (goto-char (1- (match-beginning 0)))
20245 (if (looking-at org-radio-target-regexp)
20246 (push (org-point-in-group p 0 :radio-target) clist))
20247 (goto-char p))
20248 ((setq o (car (delq nil
20249 (mapcar
20250 (lambda (x)
20251 (if (memq x org-latex-fragment-image-overlays) x))
20252 (overlays-at (point))))))
20253 (push (list :latex-fragment
20254 (overlay-start o) (overlay-end o)) clist)
20255 (push (list :latex-preview
20256 (overlay-start o) (overlay-end o)) clist))
20257 ((org-inside-LaTeX-fragment-p)
20258 ;; FIXME: positions wrong.
20259 (push (list :latex-fragment (point) (point)) clist)))
20261 (setq clist (nreverse (delq nil clist)))
20262 clist))
20264 ;; FIXME: Compare with at-regexp-p Do we need both?
20265 (defun org-in-regexp (re &optional nlines visually)
20266 "Check if point is inside a match of regexp.
20267 Normally only the current line is checked, but you can include NLINES extra
20268 lines both before and after point into the search.
20269 If VISUALLY is set, require that the cursor is not after the match but
20270 really on, so that the block visually is on the match."
20271 (catch 'exit
20272 (let ((pos (point))
20273 (eol (point-at-eol (+ 1 (or nlines 0))))
20274 (inc (if visually 1 0)))
20275 (save-excursion
20276 (beginning-of-line (- 1 (or nlines 0)))
20277 (while (re-search-forward re eol t)
20278 (if (and (<= (match-beginning 0) pos)
20279 (>= (+ inc (match-end 0)) pos))
20280 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20282 (defun org-at-regexp-p (regexp)
20283 "Is point inside a match of REGEXP in the current line?"
20284 (catch 'exit
20285 (save-excursion
20286 (let ((pos (point)) (end (point-at-eol)))
20287 (beginning-of-line 1)
20288 (while (re-search-forward regexp end t)
20289 (if (and (<= (match-beginning 0) pos)
20290 (>= (match-end 0) pos))
20291 (throw 'exit t)))
20292 nil))))
20294 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20295 "Non-nil when point is between matches of START-RE and END-RE.
20297 Also return a non-nil value when point is on one of the matches.
20299 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20300 buffer positions. Default values are the positions of headlines
20301 surrounding the point.
20303 The functions returns a cons cell whose car (resp. cdr) is the
20304 position before START-RE (resp. after END-RE)."
20305 (save-match-data
20306 (let ((pos (point))
20307 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20308 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20309 beg end)
20310 (save-excursion
20311 ;; Point is on a block when on START-RE or if START-RE can be
20312 ;; found before it...
20313 (and (or (org-at-regexp-p start-re)
20314 (re-search-backward start-re limit-up t))
20315 (setq beg (match-beginning 0))
20316 ;; ... and END-RE after it...
20317 (goto-char (match-end 0))
20318 (re-search-forward end-re limit-down t)
20319 (> (setq end (match-end 0)) pos)
20320 ;; ... without another START-RE in-between.
20321 (goto-char (match-beginning 0))
20322 (not (re-search-backward start-re (1+ beg) t))
20323 ;; Return value.
20324 (cons beg end))))))
20326 (defun org-in-block-p (names)
20327 "Non-nil when point belongs to a block whose name belongs to NAMES.
20329 NAMES is a list of strings containing names of blocks.
20331 Return first block name matched, or nil. Beware that in case of
20332 nested blocks, the returned name may not belong to the closest
20333 block from point."
20334 (save-match-data
20335 (catch 'exit
20336 (let ((case-fold-search t)
20337 (lim-up (save-excursion (outline-previous-heading)))
20338 (lim-down (save-excursion (outline-next-heading))))
20339 (mapc (lambda (name)
20340 (let ((n (regexp-quote name)))
20341 (when (org-between-regexps-p
20342 (concat "^[ \t]*#\\+begin_" n)
20343 (concat "^[ \t]*#\\+end_" n)
20344 lim-up lim-down)
20345 (throw 'exit n))))
20346 names))
20347 nil)))
20349 (defun org-occur-in-agenda-files (regexp &optional nlines)
20350 "Call `multi-occur' with buffers for all agenda files."
20351 (interactive "sOrg-files matching: \np")
20352 (let* ((files (org-agenda-files))
20353 (tnames (mapcar 'file-truename files))
20354 (extra org-agenda-text-search-extra-files)
20356 (when (eq (car extra) 'agenda-archives)
20357 (setq extra (cdr extra))
20358 (setq files (org-add-archive-files files)))
20359 (while (setq f (pop extra))
20360 (unless (member (file-truename f) tnames)
20361 (add-to-list 'files f 'append)
20362 (add-to-list 'tnames (file-truename f) 'append)))
20363 (multi-occur
20364 (mapcar (lambda (x)
20365 (with-current-buffer
20366 (or (get-file-buffer x) (find-file-noselect x))
20367 (widen)
20368 (current-buffer)))
20369 files)
20370 regexp)))
20372 (if (boundp 'occur-mode-find-occurrence-hook)
20373 ;; Emacs 23
20374 (add-hook 'occur-mode-find-occurrence-hook
20375 (lambda ()
20376 (when (derived-mode-p 'org-mode)
20377 (org-reveal))))
20378 ;; Emacs 22
20379 (defadvice occur-mode-goto-occurrence
20380 (after org-occur-reveal activate)
20381 (and (derived-mode-p 'org-mode) (org-reveal)))
20382 (defadvice occur-mode-goto-occurrence-other-window
20383 (after org-occur-reveal activate)
20384 (and (derived-mode-p 'org-mode) (org-reveal)))
20385 (defadvice occur-mode-display-occurrence
20386 (after org-occur-reveal activate)
20387 (when (derived-mode-p 'org-mode)
20388 (let ((pos (occur-mode-find-occurrence)))
20389 (with-current-buffer (marker-buffer pos)
20390 (save-excursion
20391 (goto-char pos)
20392 (org-reveal)))))))
20394 (defun org-occur-link-in-agenda-files ()
20395 "Create a link and search for it in the agendas.
20396 The link is not stored in `org-stored-links', it is just created
20397 for the search purpose."
20398 (interactive)
20399 (let ((link (condition-case nil
20400 (org-store-link nil)
20401 (error "Unable to create a link to here"))))
20402 (org-occur-in-agenda-files (regexp-quote link))))
20404 (defun org-uniquify (list)
20405 "Remove duplicate elements from LIST."
20406 (let (res)
20407 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20408 res))
20410 (defun org-delete-all (elts list)
20411 "Remove all elements in ELTS from LIST."
20412 (while elts
20413 (setq list (delete (pop elts) list)))
20414 list)
20416 (defun org-count (cl-item cl-seq)
20417 "Count the number of occurrences of ITEM in SEQ.
20418 Taken from `count' in cl-seq.el with all keyword arguments removed."
20419 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20420 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20421 (while (< cl-start cl-end)
20422 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20423 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20424 (setq cl-start (1+ cl-start)))
20425 cl-count))
20427 (defun org-remove-if (predicate seq)
20428 "Remove everything from SEQ that fulfills PREDICATE."
20429 (let (res e)
20430 (while seq
20431 (setq e (pop seq))
20432 (if (not (funcall predicate e)) (push e res)))
20433 (nreverse res)))
20435 (defun org-remove-if-not (predicate seq)
20436 "Remove everything from SEQ that does not fulfill PREDICATE."
20437 (let (res e)
20438 (while seq
20439 (setq e (pop seq))
20440 (if (funcall predicate e) (push e res)))
20441 (nreverse res)))
20443 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20444 "Reduce two-argument FUNCTION across SEQ.
20445 Taken from `reduce' in cl-seq.el with all keyword arguments but
20446 \":initial-value\" removed."
20447 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20448 (cadr (memq :initial-value cl-keys)))
20449 (cl-seq (pop cl-seq))
20450 (t (funcall cl-func)))))
20451 (while cl-seq
20452 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20453 cl-accum))
20455 (defun org-back-over-empty-lines ()
20456 "Move backwards over whitespace, to the beginning of the first empty line.
20457 Returns the number of empty lines passed."
20458 (let ((pos (point)))
20459 (if (cdr (assoc 'heading org-blank-before-new-entry))
20460 (skip-chars-backward " \t\n\r")
20461 (unless (eobp)
20462 (forward-line -1)))
20463 (beginning-of-line 2)
20464 (goto-char (min (point) pos))
20465 (count-lines (point) pos)))
20467 (defun org-skip-whitespace ()
20468 (skip-chars-forward " \t\n\r"))
20470 (defun org-point-in-group (point group &optional context)
20471 "Check if POINT is in match-group GROUP.
20472 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20473 match. If the match group does not exist or point is not inside it,
20474 return nil."
20475 (and (match-beginning group)
20476 (>= point (match-beginning group))
20477 (<= point (match-end group))
20478 (if context
20479 (list context (match-beginning group) (match-end group))
20480 t)))
20482 (defun org-switch-to-buffer-other-window (&rest args)
20483 "Switch to buffer in a second window on the current frame.
20484 In particular, do not allow pop-up frames.
20485 Returns the newly created buffer."
20486 (let (pop-up-frames special-display-buffer-names special-display-regexps
20487 special-display-function)
20488 (apply 'switch-to-buffer-other-window args)))
20490 (defun org-combine-plists (&rest plists)
20491 "Create a single property list from all plists in PLISTS.
20492 The process starts by copying the first list, and then setting properties
20493 from the other lists. Settings in the last list are the most significant
20494 ones and overrule settings in the other lists."
20495 (let ((rtn (copy-sequence (pop plists)))
20496 p v ls)
20497 (while plists
20498 (setq ls (pop plists))
20499 (while ls
20500 (setq p (pop ls) v (pop ls))
20501 (setq rtn (plist-put rtn p v))))
20502 rtn))
20504 (defun org-replace-escapes (string table)
20505 "Replace %-escapes in STRING with values in TABLE.
20506 TABLE is an association list with keys like \"%a\" and string values.
20507 The sequences in STRING may contain normal field width and padding information,
20508 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20509 so values can contain further %-escapes if they are define later in TABLE."
20510 (let ((tbl (copy-alist table))
20511 (case-fold-search nil)
20512 (pchg 0)
20513 e re rpl)
20514 (while (setq e (pop tbl))
20515 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20516 (when (and (cdr e) (string-match re (cdr e)))
20517 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20518 (safe "SREF"))
20519 (add-text-properties 0 3 (list 'sref sref) safe)
20520 (setcdr e (replace-match safe t t (cdr e)))))
20521 (while (string-match re string)
20522 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20523 (cdr e)))
20524 (setq string (replace-match rpl t t string))))
20525 (while (setq pchg (next-property-change pchg string))
20526 (let ((sref (get-text-property pchg 'sref string)))
20527 (when (and sref (string-match "SREF" string pchg))
20528 (setq string (replace-match sref t t string)))))
20529 string))
20531 (defun org-sublist (list start end)
20532 "Return a section of LIST, from START to END.
20533 Counting starts at 1."
20534 (let (rtn (c start))
20535 (setq list (nthcdr (1- start) list))
20536 (while (and list (<= c end))
20537 (push (pop list) rtn)
20538 (setq c (1+ c)))
20539 (nreverse rtn)))
20541 (defun org-find-base-buffer-visiting (file)
20542 "Like `find-buffer-visiting' but always return the base buffer and
20543 not an indirect buffer."
20544 (let ((buf (or (get-file-buffer file)
20545 (find-buffer-visiting file))))
20546 (if buf
20547 (or (buffer-base-buffer buf) buf)
20548 nil)))
20550 (defun org-image-file-name-regexp (&optional extensions)
20551 "Return regexp matching the file names of images.
20552 If EXTENSIONS is given, only match these."
20553 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20554 (image-file-name-regexp)
20555 (let ((image-file-name-extensions
20556 (or extensions
20557 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20558 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20559 (concat "\\."
20560 (regexp-opt (nconc (mapcar 'upcase
20561 image-file-name-extensions)
20562 image-file-name-extensions)
20564 "\\'"))))
20566 (defun org-file-image-p (file &optional extensions)
20567 "Return non-nil if FILE is an image."
20568 (save-match-data
20569 (string-match (org-image-file-name-regexp extensions) file)))
20571 (defun org-get-cursor-date ()
20572 "Return the date at cursor in as a time.
20573 This works in the calendar and in the agenda, anywhere else it just
20574 returns the current time."
20575 (let (date day defd)
20576 (cond
20577 ((eq major-mode 'calendar-mode)
20578 (setq date (calendar-cursor-to-date)
20579 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20580 ((eq major-mode 'org-agenda-mode)
20581 (setq day (get-text-property (point) 'day))
20582 (if day
20583 (setq date (calendar-gregorian-from-absolute day)
20584 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20585 (nth 2 date))))))
20586 (or defd (current-time))))
20588 (defvar org-agenda-action-marker (make-marker)
20589 "Marker pointing to the entry for the next agenda action.")
20591 (defun org-mark-entry-for-agenda-action ()
20592 "Mark the current entry as target of an agenda action.
20593 Agenda actions are actions executed from the agenda with the key `k',
20594 which make use of the date at the cursor."
20595 (interactive)
20596 (move-marker org-agenda-action-marker
20597 (save-excursion (org-back-to-heading t) (point))
20598 (current-buffer))
20599 (message
20600 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20602 (defun org-mark-subtree ()
20603 "Mark the current subtree.
20604 This puts point at the start of the current subtree, and mark at the end.
20606 If point is in an inline task, mark that task instead."
20607 (interactive)
20608 (let ((inline-task-p
20609 (and (featurep 'org-inlinetask)
20610 (org-inlinetask-in-task-p)))
20611 (beg))
20612 ;; Get beginning of subtree
20613 (cond
20614 (inline-task-p (org-inlinetask-goto-beginning))
20615 ((org-at-heading-p) (beginning-of-line))
20616 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20617 (setq beg (point))
20618 ;; Get end of it
20619 (if inline-task-p
20620 (org-inlinetask-goto-end)
20621 (org-end-of-subtree))
20622 ;; Mark zone
20623 (push-mark (point) nil t)
20624 (goto-char beg)))
20626 ;;; Indentation
20628 (defun org-indent-line ()
20629 "Indent line depending on context."
20630 (interactive)
20631 (let* ((pos (point))
20632 (itemp (org-at-item-p))
20633 (case-fold-search t)
20634 (org-drawer-regexp (or org-drawer-regexp "\000"))
20635 (inline-task-p (and (featurep 'org-inlinetask)
20636 (org-inlinetask-in-task-p)))
20637 (inline-re (and inline-task-p
20638 (org-inlinetask-outline-regexp)))
20639 column)
20640 (beginning-of-line 1)
20641 (cond
20642 ;; Comments
20643 ((looking-at "# ") (setq column 0))
20644 ;; Headings
20645 ((looking-at org-outline-regexp) (setq column 0))
20646 ;; Included files
20647 ((looking-at "#\\+include:") (setq column 0))
20648 ;; Footnote definition
20649 ((looking-at org-footnote-definition-re) (setq column 0))
20650 ;; Literal examples
20651 ((looking-at "[ \t]*:\\( \\|$\\)")
20652 (setq column (org-get-indentation))) ; do nothing
20653 ;; Lists
20654 ((ignore-errors (goto-char (org-in-item-p)))
20655 (setq column (if itemp
20656 (org-get-indentation)
20657 (org-list-item-body-column (point))))
20658 (goto-char pos))
20659 ;; Drawers
20660 ((and (looking-at "[ \t]*:END:")
20661 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20662 (save-excursion
20663 (goto-char (1- (match-beginning 1)))
20664 (setq column (current-column))))
20665 ;; Special blocks
20666 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20667 (save-excursion
20668 (re-search-backward
20669 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20670 (setq column (org-get-indentation (match-string 0))))
20671 ((and (not (looking-at "[ \t]*#\\+begin_"))
20672 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20673 (save-excursion
20674 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20675 (setq column
20676 (cond ((equal (downcase (match-string 1)) "src")
20677 ;; src blocks: let `org-edit-src-exit' handle them
20678 (org-get-indentation))
20679 ((equal (downcase (match-string 1)) "example")
20680 (max (org-get-indentation)
20681 (org-get-indentation (match-string 0))))
20683 (org-get-indentation (match-string 0))))))
20684 ;; This line has nothing special, look at the previous relevant
20685 ;; line to compute indentation
20687 (beginning-of-line 0)
20688 (while (and (not (bobp))
20689 (not (looking-at org-drawer-regexp))
20690 ;; When point started in an inline task, do not move
20691 ;; above task starting line.
20692 (not (and inline-task-p (looking-at inline-re)))
20693 ;; Skip drawers, blocks, empty lines, verbatim,
20694 ;; comments, tables, footnotes definitions, lists,
20695 ;; inline tasks.
20696 (or (and (looking-at "[ \t]*:END:")
20697 (re-search-backward org-drawer-regexp nil t))
20698 (and (looking-at "[ \t]*#\\+end_")
20699 (re-search-backward "[ \t]*#\\+begin_"nil t))
20700 (looking-at "[ \t]*[\n:#|]")
20701 (looking-at org-footnote-definition-re)
20702 (and (ignore-errors (goto-char (org-in-item-p)))
20703 (goto-char
20704 (org-list-get-top-point (org-list-struct))))
20705 (and (not inline-task-p)
20706 (featurep 'org-inlinetask)
20707 (org-inlinetask-in-task-p)
20708 (or (org-inlinetask-goto-beginning) t))))
20709 (beginning-of-line 0))
20710 (cond
20711 ;; There was an heading above.
20712 ((looking-at "\\*+[ \t]+")
20713 (if (not org-adapt-indentation)
20714 (setq column 0)
20715 (goto-char (match-end 0))
20716 (setq column (current-column))))
20717 ;; A drawer had started and is unfinished
20718 ((looking-at org-drawer-regexp)
20719 (goto-char (1- (match-beginning 1)))
20720 (setq column (current-column)))
20721 ;; Else, nothing noticeable found: get indentation and go on.
20722 (t (setq column (org-get-indentation))))))
20723 ;; Now apply indentation and move cursor accordingly
20724 (goto-char pos)
20725 (if (<= (current-column) (current-indentation))
20726 (org-indent-line-to column)
20727 (save-excursion (org-indent-line-to column)))
20728 ;; Special polishing for properties, see `org-property-format'
20729 (setq column (current-column))
20730 (beginning-of-line 1)
20731 (if (looking-at
20732 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20733 (replace-match (concat (match-string 1)
20734 (format org-property-format
20735 (match-string 2) (match-string 3)))
20736 t t))
20737 (org-move-to-column column)
20738 (when (and orgstruct-is-++ (eq pos (point)))
20739 (org-let org-fb-vars
20740 '(indent-according-to-mode)))))
20742 (defun org-indent-drawer ()
20743 "Indent the drawer at point."
20744 (interactive)
20745 (let ((p (point))
20746 (e (and (save-excursion (re-search-forward ":END:" nil t))
20747 (match-end 0)))
20748 (folded
20749 (save-excursion
20750 (end-of-line)
20751 (when (overlays-at (point))
20752 (member 'invisible (overlay-properties
20753 (car (overlays-at (point)))))))))
20754 (when folded (org-cycle))
20755 (indent-for-tab-command)
20756 (while (and (move-beginning-of-line 2) (< (point) e))
20757 (indent-for-tab-command))
20758 (goto-char p)
20759 (when folded (org-cycle)))
20760 (message "Drawer at point indented"))
20762 (defun org-indent-block ()
20763 "Indent the block at point."
20764 (interactive)
20765 (let ((p (point))
20766 (case-fold-search t)
20767 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20768 (match-end 0)))
20769 (folded
20770 (save-excursion
20771 (end-of-line)
20772 (when (overlays-at (point))
20773 (member 'invisible (overlay-properties
20774 (car (overlays-at (point)))))))))
20775 (when folded (org-cycle))
20776 (indent-for-tab-command)
20777 (while (and (move-beginning-of-line 2) (< (point) e))
20778 (indent-for-tab-command))
20779 (goto-char p)
20780 (when folded (org-cycle)))
20781 (message "Block at point indented"))
20783 (defun org-indent-region (start end)
20784 "Indent region."
20785 (interactive "r")
20786 (save-excursion
20787 (let ((line-end (org-current-line end)))
20788 (goto-char start)
20789 (while (< (org-current-line) line-end)
20790 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20791 (t (call-interactively 'org-indent-line)))
20792 (move-beginning-of-line 2)))))
20795 ;;; Filling
20797 ;; We use our own fill-paragraph and auto-fill functions. These
20798 ;; functions will shadow `fill-prefix' (computed internally with
20799 ;; `org-fill-context-prefix') and pass through to
20800 ;; `fill-region-as-paragraph' and `do-auto-fill' as appropriate.
20802 (defun org-set-autofill-regexps ()
20803 (interactive)
20804 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20805 ;; Prevent auto-fill from inserting unwanted new items.
20806 (when (boundp 'fill-nobreak-predicate)
20807 (org-set-local
20808 'fill-nobreak-predicate
20809 (org-uniquify
20810 (append fill-nobreak-predicate
20811 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20812 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20813 (org-set-local 'align-mode-rules-list
20814 '((org-in-buffer-settings
20815 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20816 (modes . '(org-mode))))))
20818 (defun org-fill-item-nobreak-p ()
20819 "Non-nil when a line break at point would insert a new item."
20820 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20822 (defun org-fill-line-break-nobreak-p ()
20823 "Non-nil when a line break at point would create an Org line break."
20824 (save-excursion
20825 (skip-chars-backward "[ \t]")
20826 (skip-chars-backward "\\\\")
20827 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20829 (defun org-fill-context-prefix (p)
20830 "Compute a fill prefix for the line at point P.
20831 Return fill prefix, as a string, or nil if current line isn't
20832 meant to be filled."
20833 (save-excursion
20834 (goto-char p)
20835 (beginning-of-line)
20836 (let* ((element (org-element-at-point))
20837 (type (org-element-type element))
20838 (post-affiliated
20839 (progn
20840 (goto-char (org-element-property :begin element))
20841 (while (looking-at org-element--affiliated-re) (forward-line))
20842 (point))))
20843 (unless (< p post-affiliated)
20844 (case type
20845 (comment (looking-at "[ \t]*#\\+? ?") (match-string 0))
20846 ((item plain-list)
20847 (make-string (org-list-item-body-column
20848 (org-element-property :begin element))
20849 ? ))
20850 (paragraph
20851 ;; Fill prefix is usually the same as the current line,
20852 ;; except if the paragraph is at the beginning of an item.
20853 (let ((parent (org-element-property :parent element)))
20854 (cond ((eq (org-element-type parent) 'item)
20855 (make-string (org-list-item-body-column
20856 (org-element-property :begin parent))
20857 ? ))
20858 ((looking-at "\\s-+") (match-string 0))
20859 (t ""))))
20860 ((comment-block verse-block)
20861 ;; Only fill contents if P is within block boundaries.
20862 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20863 (forward-line)
20864 (point)))
20865 (cend (save-excursion
20866 (goto-char (org-element-property :end element))
20867 (skip-chars-backward " \r\t\n")
20868 (line-beginning-position))))
20869 (when (and (>= p cbeg) (< p cend))
20870 (if (looking-at "\\s-+") (match-string 0) "")))))))))
20872 (defun org-fill-paragraph (&optional justify)
20873 "Fill element at point, when applicable.
20875 This function only applies to comment blocks, comments, example
20876 blocks, paragraphs and verse blocks. Also, as a special case,
20877 re-align table when point is at one.
20879 If JUSTIFY is non-nil (interactively, with prefix argument),
20880 justify as well. If `sentence-end-double-space' is non-nil, then
20881 period followed by one space does not end a sentence, so don't
20882 break a line there. The variable `fill-column' controls the
20883 width for filling."
20884 (let ((element (org-element-at-point)))
20885 ;; First check if point is in a blank line at the beginning of the
20886 ;; buffer. In that case, ignore filling.
20887 (if (< (point) (org-element-property :begin element)) t
20888 (case (org-element-type element)
20889 ;; Align Org tables, leave table.el tables as-is.
20890 (table-row (org-table-align) t)
20891 (table
20892 (when (eq (org-element-property :type element) 'org) (org-table-align))
20894 ;; Elements that may contain `line-break' type objects.
20895 ((paragraph verse-block)
20896 (let ((beg (org-element-property :contents-begin element))
20897 (end (org-element-property :contents-end element))
20898 (type (org-element-type element)))
20899 ;; Do nothing if point is at an affiliated keyword or at
20900 ;; verse block markers.
20901 (if (or (< (point) beg)
20902 (and (eq type 'verse-block) (>= (point) end)))
20904 ;; At a verse block, first narrow to current "paragraph"
20905 ;; and set current element to that paragraph.
20906 (save-restriction
20907 (when (eq type 'verse-block)
20908 (narrow-to-region beg end)
20909 (save-excursion
20910 (end-of-line)
20911 (let ((bol-pos (point-at-bol)))
20912 (re-search-backward org-element-paragraph-separate nil 'm)
20913 (unless (or (bobp) (= (point-at-bol) bol-pos))
20914 (forward-line))
20915 (setq element (org-element-paragraph-parser end)
20916 beg (org-element-property :contents-begin element)
20917 end (org-element-property :contents-end element)))))
20918 ;; Fill paragraph, taking line breaks into consideration.
20919 ;; For that, slice the paragraph using line breaks as
20920 ;; separators, and fill the parts in reverse order to
20921 ;; avoid messing with markers.
20922 (save-excursion
20923 (goto-char end)
20924 (mapc
20925 (lambda (pos)
20926 (let ((fill-prefix (org-fill-context-prefix pos)))
20927 (fill-region-as-paragraph pos (point) justify))
20928 (goto-char pos))
20929 ;; Find the list of ending positions for line breaks
20930 ;; in the current paragraph. Add paragraph beginning
20931 ;; to include first slice.
20932 (nreverse
20933 (cons beg
20934 (org-element-map
20935 (org-element--parse-objects
20936 beg end nil org-element-all-objects)
20937 'line-break
20938 (lambda (lb) (org-element-property :end lb))))))))
20939 t)))
20940 ;; Contents of `comment-block' type elements should be filled as
20941 ;; plain text.
20942 (comment-block
20943 (let ((fill-prefix (org-fill-context-prefix (point))))
20944 (save-excursion
20945 (fill-region-as-paragraph
20946 (progn
20947 (goto-char (org-element-property :begin element))
20948 (while (looking-at org-element--affiliated-re) (forward-line))
20949 (forward-line)
20950 (point))
20951 (progn
20952 (goto-char (org-element-property :end element))
20953 (skip-chars-backward " \r\t\n")
20954 (line-beginning-position))
20955 justify))) t)
20956 ;; Fill comments, indented or not.
20957 (comment
20958 (let ((fill-prefix (org-fill-context-prefix (point))))
20959 (save-excursion
20960 (fill-region-as-paragraph
20961 (progn
20962 (goto-char (org-element-property :begin element))
20963 (while (looking-at org-element--affiliated-re) (forward-line))
20964 (point))
20965 (progn
20966 (goto-char (org-element-property :end element))
20967 (skip-chars-backward " \r\t\n")
20968 (line-end-position))))))
20969 ;; Ignore every other element.
20970 (otherwise t)))))
20972 (defun org-auto-fill-function ()
20973 "Auto-fill function."
20974 ;; Check if auto-filling is meaningful before computing fill prefix.
20975 (let ((fc (current-fill-column)))
20976 (when (and fc (> (current-column) fc))
20977 (let ((fill-prefix (org-fill-context-prefix (point))))
20978 (when fill-prefix (do-auto-fill))))))
20981 ;;; Comments
20983 ;; Since difference between comments and keywords is subtle, we cannot
20984 ;; trust `comment-only-p' when applying `comment-dwim'. Hence, both
20985 ;; `comment-region-function' and `uncomment-region-function' point to
20986 ;; `org-comment-or-uncomment-region', which can tell when region only
20987 ;; contains comments or not.
20989 (defun org-insert-comment ()
20990 "Insert an empty comment above current line.
20991 If the line is empty, insert comment at its beginning."
20992 (beginning-of-line)
20993 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
20994 (org-indent-line)
20995 (insert "#+ "))
20997 (defun org-comment-or-uncomment-region (beg end &rest ignore)
20998 "Comment or uncomment each non-blank line in the region.
20999 Uncomment each non-blank line between BEG and END if it only
21000 contains commented lines. Otherwise, comment them."
21001 (save-excursion
21002 (goto-char beg)
21003 (skip-chars-forward " \r\t\n" end)
21004 (beginning-of-line)
21005 (let ((uncommentp
21006 ;; UNCOMMENTP is non-nil when every non blank line between
21007 ;; BEG and END is a comment.
21008 (save-excursion
21009 (while (progn (and (not (eobp))
21010 (let ((element (org-element-at-point)))
21011 (and (eq (org-element-type element) 'comment)
21012 (goto-char (org-element-property
21013 :end element)))))))
21014 (>= (point) end)))
21015 ;; Remove or adding comment markers is going to change end
21016 ;; position so make it a marker.
21017 (end (copy-marker end)))
21018 (while (< (point) end)
21019 (unless (looking-at "\\s-*$")
21020 (if (not uncommentp) (progn (back-to-indentation) (insert "#+ "))
21021 ;; Only comments and blank lines in region: uncomment it.
21022 (looking-at "[ \t]*\\(#\\+? ?\\)")
21023 (replace-match "" nil nil nil 1)))
21024 (forward-line))
21025 (set-marker end nil))))
21028 ;;; Other stuff.
21030 (defun org-toggle-fixed-width-section (arg)
21031 "Toggle the fixed-width export.
21032 If there is no active region, the QUOTE keyword at the current headline is
21033 inserted or removed. When present, it causes the text between this headline
21034 and the next to be exported as fixed-width text, and unmodified.
21035 If there is an active region, this command adds or removes a colon as the
21036 first character of this line. If the first character of a line is a colon,
21037 this line is also exported in fixed-width font."
21038 (interactive "P")
21039 (let* ((cc 0)
21040 (regionp (org-region-active-p))
21041 (beg (if regionp (region-beginning) (point)))
21042 (end (if regionp (region-end)))
21043 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21044 (case-fold-search nil)
21045 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21046 off)
21047 (if regionp
21048 (save-excursion
21049 (goto-char beg)
21050 (setq cc (current-column))
21051 (beginning-of-line 1)
21052 (setq off (looking-at re))
21053 (while (> nlines 0)
21054 (setq nlines (1- nlines))
21055 (beginning-of-line 1)
21056 (cond
21057 (arg
21058 (org-move-to-column cc t)
21059 (insert ": \n")
21060 (forward-line -1))
21061 ((and off (looking-at re))
21062 (replace-match "" t t nil 1))
21063 ((not off) (org-move-to-column cc t) (insert ": ")))
21064 (forward-line 1)))
21065 (save-excursion
21066 (org-back-to-heading)
21067 (cond
21068 ((looking-at (format org-heading-keyword-regexp-format
21069 org-quote-string))
21070 (goto-char (match-end 1))
21071 (looking-at (concat " +" org-quote-string))
21072 (replace-match "" t t)
21073 (when (eolp) (insert " ")))
21074 ((looking-at org-outline-regexp)
21075 (goto-char (match-end 0))
21076 (insert org-quote-string " ")))))))
21078 (defun org-reftex-citation ()
21079 "Use reftex-citation to insert a citation into the buffer.
21080 This looks for a line like
21082 #+BIBLIOGRAPHY: foo plain option:-d
21084 and derives from it that foo.bib is the bibliography file relevant
21085 for this document. It then installs the necessary environment for RefTeX
21086 to work in this buffer and calls `reftex-citation' to insert a citation
21087 into the buffer.
21089 Export of such citations to both LaTeX and HTML is handled by the contributed
21090 package org-exp-bibtex by Taru Karttunen."
21091 (interactive)
21092 (let ((reftex-docstruct-symbol 'rds)
21093 (reftex-cite-format "\\cite{%l}")
21094 rds bib)
21095 (save-excursion
21096 (save-restriction
21097 (widen)
21098 (let ((case-fold-search t)
21099 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21100 (if (not (save-excursion
21101 (or (re-search-forward re nil t)
21102 (re-search-backward re nil t))))
21103 (error "No bibliography defined in file")
21104 (setq bib (concat (match-string 1) ".bib")
21105 rds (list (list 'bib bib)))))))
21106 (call-interactively 'reftex-citation)))
21108 ;;;; Functions extending outline functionality
21110 (defun org-beginning-of-line (&optional arg)
21111 "Go to the beginning of the current line. If that is invisible, continue
21112 to a visible line beginning. This makes the function of C-a more intuitive.
21113 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21114 first attempt, and only move to after the tags when the cursor is already
21115 beyond the end of the headline."
21116 (interactive "P")
21117 (let ((pos (point))
21118 (special (if (consp org-special-ctrl-a/e)
21119 (car org-special-ctrl-a/e)
21120 org-special-ctrl-a/e))
21121 refpos)
21122 (if (org-bound-and-true-p line-move-visual)
21123 (beginning-of-visual-line 1)
21124 (beginning-of-line 1))
21125 (if (and arg (fboundp 'move-beginning-of-line))
21126 (call-interactively 'move-beginning-of-line)
21127 (if (bobp)
21129 (backward-char 1)
21130 (if (org-truely-invisible-p)
21131 (while (and (not (bobp)) (org-truely-invisible-p))
21132 (backward-char 1)
21133 (beginning-of-line 1))
21134 (forward-char 1))))
21135 (when special
21136 (cond
21137 ((and (looking-at org-complex-heading-regexp)
21138 (= (char-after (match-end 1)) ?\ ))
21139 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21140 (point-at-eol)))
21141 (goto-char
21142 (if (eq special t)
21143 (cond ((> pos refpos) refpos)
21144 ((= pos (point)) refpos)
21145 (t (point)))
21146 (cond ((> pos (point)) (point))
21147 ((not (eq last-command this-command)) (point))
21148 (t refpos)))))
21149 ((org-at-item-p)
21150 ;; Being at an item and not looking at an the item means point
21151 ;; was previously moved to beginning of a visual line, which
21152 ;; doesn't contain the item. Therefore, do nothing special,
21153 ;; just stay here.
21154 (when (looking-at org-list-full-item-re)
21155 ;; Set special position at first white space character after
21156 ;; bullet, and check-box, if any.
21157 (let ((after-bullet
21158 (let ((box (match-end 3)))
21159 (if (not box) (match-end 1)
21160 (let ((after (char-after box)))
21161 (if (and after (= after ? )) (1+ box) box))))))
21162 ;; Special case: Move point to special position when
21163 ;; currently after it or at beginning of line.
21164 (if (eq special t)
21165 (when (or (> pos after-bullet) (= (point) pos))
21166 (goto-char after-bullet))
21167 ;; Reversed case: Move point to special position when
21168 ;; point was already at beginning of line and command is
21169 ;; repeated.
21170 (when (and (= (point) pos) (eq last-command this-command))
21171 (goto-char after-bullet))))))))
21172 (org-no-warnings
21173 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21175 (defun org-end-of-line (&optional arg)
21176 "Go to the end of the line.
21177 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21178 first attempt, and only move to after the tags when the cursor is already
21179 beyond the end of the headline."
21180 (interactive "P")
21181 (let ((special (if (consp org-special-ctrl-a/e)
21182 (cdr org-special-ctrl-a/e)
21183 org-special-ctrl-a/e)))
21184 (cond
21185 ((or (not special) arg
21186 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21187 (call-interactively
21188 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21189 ((fboundp 'move-end-of-line) 'move-end-of-line)
21190 (t 'end-of-line))))
21191 ((org-at-heading-p)
21192 (let ((pos (point)))
21193 (beginning-of-line 1)
21194 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21195 (if (eq special t)
21196 (if (or (< pos (match-beginning 1))
21197 (= pos (match-end 0)))
21198 (goto-char (match-beginning 1))
21199 (goto-char (match-end 0)))
21200 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21201 (goto-char (match-end 0))
21202 (goto-char (match-beginning 1))))
21203 (call-interactively (if (fboundp 'move-end-of-line)
21204 'move-end-of-line
21205 'end-of-line)))))
21206 ((org-at-drawer-p)
21207 (move-end-of-line 1)
21208 (when (overlays-at (1- (point))) (backward-char 1)))
21209 ;; At an item: Move before any hidden text.
21210 (t (call-interactively
21211 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21212 ((fboundp 'move-end-of-line) 'move-end-of-line)
21213 (t 'end-of-line)))))
21214 (org-no-warnings
21215 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21217 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21218 (define-key org-mode-map "\C-e" 'org-end-of-line)
21220 (defun org-backward-sentence (&optional arg)
21221 "Go to beginning of sentence, or beginning of table field.
21222 This will call `backward-sentence' or `org-table-beginning-of-field',
21223 depending on context."
21224 (interactive "P")
21225 (cond
21226 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21227 (t (call-interactively 'backward-sentence))))
21229 (defun org-forward-sentence (&optional arg)
21230 "Go to end of sentence, or end of table field.
21231 This will call `forward-sentence' or `org-table-end-of-field',
21232 depending on context."
21233 (interactive "P")
21234 (cond
21235 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21236 (t (call-interactively 'forward-sentence))))
21238 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21239 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21241 (defun org-kill-line (&optional arg)
21242 "Kill line, to tags or end of line."
21243 (interactive "P")
21244 (cond
21245 ((or (not org-special-ctrl-k)
21246 (bolp)
21247 (not (org-at-heading-p)))
21248 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21249 org-ctrl-k-protect-subtree)
21250 (if (or (eq org-ctrl-k-protect-subtree 'error)
21251 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21252 (error "C-k aborted - would kill hidden subtree")))
21253 (call-interactively
21254 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21255 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21256 (kill-region (point) (match-beginning 1))
21257 (org-set-tags nil t))
21258 (t (kill-region (point) (point-at-eol)))))
21260 (define-key org-mode-map "\C-k" 'org-kill-line)
21262 (defun org-yank (&optional arg)
21263 "Yank. If the kill is a subtree, treat it specially.
21264 This command will look at the current kill and check if is a single
21265 subtree, or a series of subtrees[1]. If it passes the test, and if the
21266 cursor is at the beginning of a line or after the stars of a currently
21267 empty headline, then the yank is handled specially. How exactly depends
21268 on the value of the following variables, both set by default.
21270 org-yank-folded-subtrees
21271 When set, the subtree(s) will be folded after insertion, but only
21272 if doing so would now swallow text after the yanked text.
21274 org-yank-adjusted-subtrees
21275 When set, the subtree will be promoted or demoted in order to
21276 fit into the local outline tree structure, which means that the level
21277 will be adjusted so that it becomes the smaller one of the two
21278 *visible* surrounding headings.
21280 Any prefix to this command will cause `yank' to be called directly with
21281 no special treatment. In particular, a simple \\[universal-argument] prefix \
21282 will just
21283 plainly yank the text as it is.
21285 \[1] The test checks if the first non-white line is a heading
21286 and if there are no other headings with fewer stars."
21287 (interactive "P")
21288 (org-yank-generic 'yank arg))
21290 (defun org-yank-generic (command arg)
21291 "Perform some yank-like command.
21293 This function implements the behavior described in the `org-yank'
21294 documentation. However, it has been generalized to work for any
21295 interactive command with similar behavior."
21297 ;; pretend to be command COMMAND
21298 (setq this-command command)
21300 (if arg
21301 (call-interactively command)
21303 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21304 (and (org-kill-is-subtree-p)
21305 (or (bolp)
21306 (and (looking-at "[ \t]*$")
21307 (string-match
21308 "\\`\\*+\\'"
21309 (buffer-substring (point-at-bol) (point)))))))
21310 swallowp)
21311 (cond
21312 ((and subtreep org-yank-folded-subtrees)
21313 (let ((beg (point))
21314 end)
21315 (if (and subtreep org-yank-adjusted-subtrees)
21316 (org-paste-subtree nil nil 'for-yank)
21317 (call-interactively command))
21319 (setq end (point))
21320 (goto-char beg)
21321 (when (and (bolp) subtreep
21322 (not (setq swallowp
21323 (org-yank-folding-would-swallow-text beg end))))
21324 (org-with-limited-levels
21325 (or (looking-at org-outline-regexp)
21326 (re-search-forward org-outline-regexp-bol end t))
21327 (while (and (< (point) end) (looking-at org-outline-regexp))
21328 (hide-subtree)
21329 (org-cycle-show-empty-lines 'folded)
21330 (condition-case nil
21331 (outline-forward-same-level 1)
21332 (error (goto-char end))))))
21333 (when swallowp
21334 (message
21335 "Inserted text not folded because that would swallow text"))
21337 (goto-char end)
21338 (skip-chars-forward " \t\n\r")
21339 (beginning-of-line 1)
21340 (push-mark beg 'nomsg)))
21341 ((and subtreep org-yank-adjusted-subtrees)
21342 (let ((beg (point-at-bol)))
21343 (org-paste-subtree nil nil 'for-yank)
21344 (push-mark beg 'nomsg)))
21346 (call-interactively command))))))
21348 (defun org-yank-folding-would-swallow-text (beg end)
21349 "Would hide-subtree at BEG swallow any text after END?"
21350 (let (level)
21351 (org-with-limited-levels
21352 (save-excursion
21353 (goto-char beg)
21354 (when (or (looking-at org-outline-regexp)
21355 (re-search-forward org-outline-regexp-bol end t))
21356 (setq level (org-outline-level)))
21357 (goto-char end)
21358 (skip-chars-forward " \t\r\n\v\f")
21359 (if (or (eobp)
21360 (and (bolp) (looking-at org-outline-regexp)
21361 (<= (org-outline-level) level)))
21362 nil ; Nothing would be swallowed
21363 t))))) ; something would swallow
21365 (define-key org-mode-map "\C-y" 'org-yank)
21367 (defun org-truely-invisible-p ()
21368 "Check if point is at a character currently not visible.
21369 This version does not only check the character property, but also
21370 `visible-mode'."
21371 ;; Early versions of noutline don't have `outline-invisible-p'.
21372 (if (org-bound-and-true-p visible-mode)
21374 (outline-invisible-p)))
21376 (defun org-invisible-p2 ()
21377 "Check if point is at a character currently not visible."
21378 (save-excursion
21379 (if (and (eolp) (not (bobp))) (backward-char 1))
21380 ;; Early versions of noutline don't have `outline-invisible-p'.
21381 (outline-invisible-p)))
21383 (defun org-back-to-heading (&optional invisible-ok)
21384 "Call `outline-back-to-heading', but provide a better error message."
21385 (condition-case nil
21386 (outline-back-to-heading invisible-ok)
21387 (error (error "Before first headline at position %d in buffer %s"
21388 (point) (current-buffer)))))
21390 (defun org-beginning-of-defun ()
21391 "Go to the beginning of the subtree, i.e. back to the heading."
21392 (org-back-to-heading))
21393 (defun org-end-of-defun ()
21394 "Go to the end of the subtree."
21395 (org-end-of-subtree nil t))
21397 (defun org-before-first-heading-p ()
21398 "Before first heading?"
21399 (save-excursion
21400 (end-of-line)
21401 (null (re-search-backward org-outline-regexp-bol nil t))))
21403 (defun org-at-heading-p (&optional ignored)
21404 (outline-on-heading-p t))
21405 ;; Compatibility alias with Org versions < 7.8.03
21406 (defalias 'org-on-heading-p 'org-at-heading-p)
21408 (defun org-at-comment-p nil
21409 "Is cursor in a line starting with a # character?"
21410 (save-excursion
21411 (beginning-of-line)
21412 (looking-at "^#")))
21414 (defun org-at-drawer-p nil
21415 "Is cursor at a drawer keyword?"
21416 (save-excursion
21417 (move-beginning-of-line 1)
21418 (looking-at org-drawer-regexp)))
21420 (defun org-at-block-p nil
21421 "Is cursor at a block keyword?"
21422 (save-excursion
21423 (move-beginning-of-line 1)
21424 (looking-at org-block-regexp)))
21426 (defun org-point-at-end-of-empty-headline ()
21427 "If point is at the end of an empty headline, return t, else nil.
21428 If the heading only contains a TODO keyword, it is still still considered
21429 empty."
21430 (and (looking-at "[ \t]*$")
21431 (when org-todo-line-regexp
21432 (save-excursion
21433 (beginning-of-line 1)
21434 (let ((case-fold-search nil))
21435 (looking-at org-todo-line-regexp)
21436 (string= (match-string 3) ""))))))
21438 (defun org-at-heading-or-item-p ()
21439 (or (org-at-heading-p) (org-at-item-p)))
21441 (defun org-at-target-p ()
21442 (or (org-in-regexp org-radio-target-regexp)
21443 (org-in-regexp org-target-regexp)))
21444 ;; Compatibility alias with Org versions < 7.8.03
21445 (defalias 'org-on-target-p 'org-at-target-p)
21447 (defun org-up-heading-all (arg)
21448 "Move to the heading line of which the present line is a subheading.
21449 This function considers both visible and invisible heading lines.
21450 With argument, move up ARG levels."
21451 (if (fboundp 'outline-up-heading-all)
21452 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21453 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21455 (defun org-up-heading-safe ()
21456 "Move to the heading line of which the present line is a subheading.
21457 This version will not throw an error. It will return the level of the
21458 headline found, or nil if no higher level is found.
21460 Also, this function will be a lot faster than `outline-up-heading',
21461 because it relies on stars being the outline starters. This can really
21462 make a significant difference in outlines with very many siblings."
21463 (let (start-level re)
21464 (org-back-to-heading t)
21465 (setq start-level (funcall outline-level))
21466 (if (equal start-level 1)
21468 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21469 (if (re-search-backward re nil t)
21470 (funcall outline-level)))))
21472 (defun org-first-sibling-p ()
21473 "Is this heading the first child of its parents?"
21474 (interactive)
21475 (let ((re org-outline-regexp-bol)
21476 level l)
21477 (unless (org-at-heading-p t)
21478 (error "Not at a heading"))
21479 (setq level (funcall outline-level))
21480 (save-excursion
21481 (if (not (re-search-backward re nil t))
21483 (setq l (funcall outline-level))
21484 (< l level)))))
21486 (defun org-goto-sibling (&optional previous)
21487 "Goto the next sibling, even if it is invisible.
21488 When PREVIOUS is set, go to the previous sibling instead. Returns t
21489 when a sibling was found. When none is found, return nil and don't
21490 move point."
21491 (let ((fun (if previous 're-search-backward 're-search-forward))
21492 (pos (point))
21493 (re org-outline-regexp-bol)
21494 level l)
21495 (when (condition-case nil (org-back-to-heading t) (error nil))
21496 (setq level (funcall outline-level))
21497 (catch 'exit
21498 (or previous (forward-char 1))
21499 (while (funcall fun re nil t)
21500 (setq l (funcall outline-level))
21501 (when (< l level) (goto-char pos) (throw 'exit nil))
21502 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21503 (goto-char pos)
21504 nil))))
21506 (defun org-show-siblings ()
21507 "Show all siblings of the current headline."
21508 (save-excursion
21509 (while (org-goto-sibling) (org-flag-heading nil)))
21510 (save-excursion
21511 (while (org-goto-sibling 'previous)
21512 (org-flag-heading nil))))
21514 (defun org-goto-first-child ()
21515 "Goto the first child, even if it is invisible.
21516 Return t when a child was found. Otherwise don't move point and
21517 return nil."
21518 (let (level (pos (point)) (re org-outline-regexp-bol))
21519 (when (condition-case nil (org-back-to-heading t) (error nil))
21520 (setq level (outline-level))
21521 (forward-char 1)
21522 (if (and (re-search-forward re nil t) (> (outline-level) level))
21523 (progn (goto-char (match-beginning 0)) t)
21524 (goto-char pos) nil))))
21526 (defun org-show-hidden-entry ()
21527 "Show an entry where even the heading is hidden."
21528 (save-excursion
21529 (org-show-entry)))
21531 (defun org-flag-heading (flag &optional entry)
21532 "Flag the current heading. FLAG non-nil means make invisible.
21533 When ENTRY is non-nil, show the entire entry."
21534 (save-excursion
21535 (org-back-to-heading t)
21536 ;; Check if we should show the entire entry
21537 (if entry
21538 (progn
21539 (org-show-entry)
21540 (save-excursion
21541 (and (outline-next-heading)
21542 (org-flag-heading nil))))
21543 (outline-flag-region (max (point-min) (1- (point)))
21544 (save-excursion (outline-end-of-heading) (point))
21545 flag))))
21547 (defun org-get-next-sibling ()
21548 "Move to next heading of the same level, and return point.
21549 If there is no such heading, return nil.
21550 This is like outline-next-sibling, but invisible headings are ok."
21551 (let ((level (funcall outline-level)))
21552 (outline-next-heading)
21553 (while (and (not (eobp)) (> (funcall outline-level) level))
21554 (outline-next-heading))
21555 (if (or (eobp) (< (funcall outline-level) level))
21557 (point))))
21559 (defun org-get-last-sibling ()
21560 "Move to previous heading of the same level, and return point.
21561 If there is no such heading, return nil."
21562 (let ((opoint (point))
21563 (level (funcall outline-level)))
21564 (outline-previous-heading)
21565 (when (and (/= (point) opoint) (outline-on-heading-p t))
21566 (while (and (> (funcall outline-level) level)
21567 (not (bobp)))
21568 (outline-previous-heading))
21569 (if (< (funcall outline-level) level)
21571 (point)))))
21573 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21574 ;; This contains an exact copy of the original function, but it uses
21575 ;; `org-back-to-heading', to make it work also in invisible
21576 ;; trees. And is uses an invisible-OK argument.
21577 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21578 ;; Furthermore, when used inside Org, finding the end of a large subtree
21579 ;; with many children and grandchildren etc, this can be much faster
21580 ;; than the outline version.
21581 (org-back-to-heading invisible-OK)
21582 (let ((first t)
21583 (level (funcall outline-level)))
21584 (if (and (derived-mode-p 'org-mode) (< level 1000))
21585 ;; A true heading (not a plain list item), in Org-mode
21586 ;; This means we can easily find the end by looking
21587 ;; only for the right number of stars. Using a regexp to do
21588 ;; this is so much faster than using a Lisp loop.
21589 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21590 (forward-char 1)
21591 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21592 ;; something else, do it the slow way
21593 (while (and (not (eobp))
21594 (or first (> (funcall outline-level) level)))
21595 (setq first nil)
21596 (outline-next-heading)))
21597 (unless to-heading
21598 (if (memq (preceding-char) '(?\n ?\^M))
21599 (progn
21600 ;; Go to end of line before heading
21601 (forward-char -1)
21602 (if (memq (preceding-char) '(?\n ?\^M))
21603 ;; leave blank line before heading
21604 (forward-char -1))))))
21605 (point))
21607 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21608 "Use Org version in org-mode, for dramatic speed-up."
21609 (if (derived-mode-p 'org-mode)
21610 (progn
21611 (org-end-of-subtree nil t)
21612 (unless (eobp) (backward-char 1)))
21613 ad-do-it))
21615 (defun org-end-of-meta-data-and-drawers ()
21616 "Jump to the first text after meta data and drawers in the current entry.
21617 This will move over empty lines, lines with planning time stamps,
21618 clocking lines, and drawers."
21619 (org-back-to-heading t)
21620 (let ((end (save-excursion (outline-next-heading) (point)))
21621 (re (concat "\\(" org-drawer-regexp "\\)"
21622 "\\|" "[ \t]*" org-keyword-time-regexp)))
21623 (forward-line 1)
21624 (while (re-search-forward re end t)
21625 (if (not (match-end 1))
21626 ;; empty or planning line
21627 (forward-line 1)
21628 ;; a drawer, find the end
21629 (re-search-forward "^[ \t]*:END:" end 'move)
21630 (forward-line 1)))
21631 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21632 (point)))
21634 (defun org-forward-same-level (arg &optional invisible-ok)
21635 "Move forward to the arg'th subheading at same level as this one.
21636 Stop at the first and last subheadings of a superior heading.
21637 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21638 it wil also look at invisible ones."
21639 (interactive "p")
21640 (org-back-to-heading invisible-ok)
21641 (org-at-heading-p)
21642 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21643 (re (format "^\\*\\{1,%d\\} " level))
21645 (forward-char 1)
21646 (while (> arg 0)
21647 (while (and (re-search-forward re nil 'move)
21648 (setq l (- (match-end 0) (match-beginning 0) 1))
21649 (= l level)
21650 (not invisible-ok)
21651 (progn (backward-char 1) (outline-invisible-p)))
21652 (if (< l level) (setq arg 1)))
21653 (setq arg (1- arg)))
21654 (beginning-of-line 1)))
21656 (defun org-backward-same-level (arg &optional invisible-ok)
21657 "Move backward to the arg'th subheading at same level as this one.
21658 Stop at the first and last subheadings of a superior heading."
21659 (interactive "p")
21660 (org-back-to-heading)
21661 (org-at-heading-p)
21662 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21663 (re (format "^\\*\\{1,%d\\} " level))
21665 (while (> arg 0)
21666 (while (and (re-search-backward re nil 'move)
21667 (setq l (- (match-end 0) (match-beginning 0) 1))
21668 (= l level)
21669 (not invisible-ok)
21670 (outline-invisible-p))
21671 (if (< l level) (setq arg 1)))
21672 (setq arg (1- arg)))))
21674 (defun org-show-subtree ()
21675 "Show everything after this heading at deeper levels."
21676 (interactive)
21677 (outline-flag-region
21678 (point)
21679 (save-excursion
21680 (org-end-of-subtree t t))
21681 nil))
21683 (defun org-show-entry ()
21684 "Show the body directly following this heading.
21685 Show the heading too, if it is currently invisible."
21686 (interactive)
21687 (save-excursion
21688 (condition-case nil
21689 (progn
21690 (org-back-to-heading t)
21691 (outline-flag-region
21692 (max (point-min) (1- (point)))
21693 (save-excursion
21694 (if (re-search-forward
21695 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21696 (match-beginning 1)
21697 (point-max)))
21698 nil)
21699 (org-cycle-hide-drawers 'children))
21700 (error nil))))
21702 (defun org-make-options-regexp (kwds &optional extra)
21703 "Make a regular expression for keyword lines."
21704 (concat
21706 "#?[ \t]*\\+\\("
21707 (mapconcat 'regexp-quote kwds "\\|")
21708 (if extra (concat "\\|" extra))
21709 "\\):[ \t]*"
21710 "\\(.*\\)"))
21712 ;; Make isearch reveal the necessary context
21713 (defun org-isearch-end ()
21714 "Reveal context after isearch exits."
21715 (when isearch-success ; only if search was successful
21716 (if (featurep 'xemacs)
21717 ;; Under XEmacs, the hook is run in the correct place,
21718 ;; we directly show the context.
21719 (org-show-context 'isearch)
21720 ;; In Emacs the hook runs *before* restoring the overlays.
21721 ;; So we have to use a one-time post-command-hook to do this.
21722 ;; (Emacs 22 has a special variable, see function `org-mode')
21723 (unless (and (boundp 'isearch-mode-end-hook-quit)
21724 isearch-mode-end-hook-quit)
21725 ;; Only when the isearch was not quitted.
21726 (org-add-hook 'post-command-hook 'org-isearch-post-command
21727 'append 'local)))))
21729 (defun org-isearch-post-command ()
21730 "Remove self from hook, and show context."
21731 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21732 (org-show-context 'isearch))
21735 ;;;; Integration with and fixes for other packages
21737 ;;; Imenu support
21739 (defvar org-imenu-markers nil
21740 "All markers currently used by Imenu.")
21741 (make-variable-buffer-local 'org-imenu-markers)
21743 (defun org-imenu-new-marker (&optional pos)
21744 "Return a new marker for use by Imenu, and remember the marker."
21745 (let ((m (make-marker)))
21746 (move-marker m (or pos (point)))
21747 (push m org-imenu-markers)
21750 (defun org-imenu-get-tree ()
21751 "Produce the index for Imenu."
21752 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21753 (setq org-imenu-markers nil)
21754 (let* ((n org-imenu-depth)
21755 (re (concat "^" (org-get-limited-outline-regexp)))
21756 (subs (make-vector (1+ n) nil))
21757 (last-level 0)
21758 m level head)
21759 (save-excursion
21760 (save-restriction
21761 (widen)
21762 (goto-char (point-max))
21763 (while (re-search-backward re nil t)
21764 (setq level (org-reduced-level (funcall outline-level)))
21765 (when (and (<= level n)
21766 (looking-at org-complex-heading-regexp))
21767 (setq head (org-link-display-format
21768 (org-match-string-no-properties 4))
21769 m (org-imenu-new-marker))
21770 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21771 (if (>= level last-level)
21772 (push (cons head m) (aref subs level))
21773 (push (cons head (aref subs (1+ level))) (aref subs level))
21774 (loop for i from (1+ level) to n do (aset subs i nil)))
21775 (setq last-level level)))))
21776 (aref subs 1)))
21778 (eval-after-load "imenu"
21779 '(progn
21780 (add-hook 'imenu-after-jump-hook
21781 (lambda ()
21782 (if (derived-mode-p 'org-mode)
21783 (org-show-context 'org-goto))))))
21785 (defun org-link-display-format (link)
21786 "Replace a link with either the description, or the link target
21787 if no description is present"
21788 (save-match-data
21789 (if (string-match org-bracket-link-analytic-regexp link)
21790 (replace-match (if (match-end 5)
21791 (match-string 5 link)
21792 (concat (match-string 1 link)
21793 (match-string 3 link)))
21794 nil t link)
21795 link)))
21797 (defun org-toggle-link-display ()
21798 "Toggle the literal or descriptive display of links."
21799 (interactive)
21800 (if org-descriptive-links
21801 (progn (org-remove-from-invisibility-spec '(org-link))
21802 (org-restart-font-lock)
21803 (setq org-descriptive-links nil))
21804 (progn (add-to-invisibility-spec '(org-link))
21805 (org-restart-font-lock)
21806 (setq org-descriptive-links t))))
21808 ;; Speedbar support
21810 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21811 "Overlay marking the agenda restriction line in speedbar.")
21812 (overlay-put org-speedbar-restriction-lock-overlay
21813 'face 'org-agenda-restriction-lock)
21814 (overlay-put org-speedbar-restriction-lock-overlay
21815 'help-echo "Agendas are currently limited to this item.")
21816 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21818 (defun org-speedbar-set-agenda-restriction ()
21819 "Restrict future agenda commands to the location at point in speedbar.
21820 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21821 (interactive)
21822 (require 'org-agenda)
21823 (let (p m tp np dir txt)
21824 (cond
21825 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21826 'org-imenu t))
21827 (setq m (get-text-property p 'org-imenu-marker))
21828 (with-current-buffer (marker-buffer m)
21829 (goto-char m)
21830 (org-agenda-set-restriction-lock 'subtree)))
21831 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21832 'speedbar-function 'speedbar-find-file))
21833 (setq tp (previous-single-property-change
21834 (1+ p) 'speedbar-function)
21835 np (next-single-property-change
21836 tp 'speedbar-function)
21837 dir (speedbar-line-directory)
21838 txt (buffer-substring-no-properties (or tp (point-min))
21839 (or np (point-max))))
21840 (with-current-buffer (find-file-noselect
21841 (let ((default-directory dir))
21842 (expand-file-name txt)))
21843 (unless (derived-mode-p 'org-mode)
21844 (error "Cannot restrict to non-Org-mode file"))
21845 (org-agenda-set-restriction-lock 'file)))
21846 (t (error "Don't know how to restrict Org-mode's agenda")))
21847 (move-overlay org-speedbar-restriction-lock-overlay
21848 (point-at-bol) (point-at-eol))
21849 (setq current-prefix-arg nil)
21850 (org-agenda-maybe-redo)))
21852 (eval-after-load "speedbar"
21853 '(progn
21854 (speedbar-add-supported-extension ".org")
21855 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21856 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21857 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21858 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21859 (add-hook 'speedbar-visiting-tag-hook
21860 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21862 ;;; Fixes and Hacks for problems with other packages
21864 ;; Make flyspell not check words in links, to not mess up our keymap
21865 (defun org-mode-flyspell-verify ()
21866 "Don't let flyspell put overlays at active buttons, or on
21867 {todo,all-time,additional-option-like}-keywords."
21868 (let ((pos (max (1- (point)) (point-min)))
21869 (word (thing-at-point 'word)))
21870 (and (not (get-text-property pos 'keymap))
21871 (not (get-text-property pos 'org-no-flyspell))
21872 (not (member word org-todo-keywords-1))
21873 (not (member word org-all-time-keywords))
21874 (not (member word (mapcar 'car org-startup-options)))
21875 (not (member word org-additional-option-like-keywords-for-flyspell)))))
21877 (defun org-remove-flyspell-overlays-in (beg end)
21878 "Remove flyspell overlays in region."
21879 (and (org-bound-and-true-p flyspell-mode)
21880 (fboundp 'flyspell-delete-region-overlays)
21881 (flyspell-delete-region-overlays beg end))
21882 (add-text-properties beg end '(org-no-flyspell t)))
21884 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21885 (eval-after-load "bookmark"
21886 '(if (boundp 'bookmark-after-jump-hook)
21887 ;; We can use the hook
21888 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21889 ;; Hook not available, use advice
21890 (defadvice bookmark-jump (after org-make-visible activate)
21891 "Make the position visible."
21892 (org-bookmark-jump-unhide))))
21894 ;; Make sure saveplace shows the location if it was hidden
21895 (eval-after-load "saveplace"
21896 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21897 "Make the position visible."
21898 (org-bookmark-jump-unhide)))
21900 ;; Make sure ecb shows the location if it was hidden
21901 (eval-after-load "ecb"
21902 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21903 "Make hierarchy visible when jumping into location from ECB tree buffer."
21904 (if (derived-mode-p 'org-mode)
21905 (org-show-context))))
21907 (defun org-bookmark-jump-unhide ()
21908 "Unhide the current position, to show the bookmark location."
21909 (and (derived-mode-p 'org-mode)
21910 (or (outline-invisible-p)
21911 (save-excursion (goto-char (max (point-min) (1- (point))))
21912 (outline-invisible-p)))
21913 (org-show-context 'bookmark-jump)))
21915 ;; Make session.el ignore our circular variable
21916 (eval-after-load "session"
21917 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21919 ;;;; Experimental code
21921 (defun org-closed-in-range ()
21922 "Sparse tree of items closed in a certain time range.
21923 Still experimental, may disappear in the future."
21924 (interactive)
21925 ;; Get the time interval from the user.
21926 (let* ((time1 (org-float-time
21927 (org-read-date nil 'to-time nil "Starting date: ")))
21928 (time2 (org-float-time
21929 (org-read-date nil 'to-time nil "End date:")))
21930 ;; callback function
21931 (callback (lambda ()
21932 (let ((time
21933 (org-float-time
21934 (apply 'encode-time
21935 (org-parse-time-string
21936 (match-string 1))))))
21937 ;; check if time in interval
21938 (and (>= time time1) (<= time time2))))))
21939 ;; make tree, check each match with the callback
21940 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21942 ;;;; Finish up
21944 (provide 'org)
21946 (run-hooks 'org-load-hook)
21948 ;;; org.el ends here