org-publish.el (org-publish-cache-ctime-of-src): Simplify.
[org-mode.git] / lisp / org.el
blob2935045fa40402be462024c4af8446fa885c9d9a
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-timestamps-up "org-clock" ())
117 (declare-function org-clock-timestamps-down "org-clock" ())
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :version "24.1"
151 :type '(alist :tag "Babel Languages"
152 :key-type
153 (choice
154 (const :tag "Awk" awk)
155 (const :tag "C" C)
156 (const :tag "R" R)
157 (const :tag "Asymptote" asymptote)
158 (const :tag "Calc" calc)
159 (const :tag "Clojure" clojure)
160 (const :tag "CSS" css)
161 (const :tag "Ditaa" ditaa)
162 (const :tag "Dot" dot)
163 (const :tag "Emacs Lisp" emacs-lisp)
164 (const :tag "Fortran" fortran)
165 (const :tag "Gnuplot" gnuplot)
166 (const :tag "Haskell" haskell)
167 (const :tag "IO" io)
168 (const :tag "Java" java)
169 (const :tag "Javascript" js)
170 (const :tag "LaTeX" latex)
171 (const :tag "Ledger" ledger)
172 (const :tag "Lilypond" lilypond)
173 (const :tag "Lisp" lisp)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "Pico Lisp" picolisp)
182 (const :tag "PlantUML" plantuml)
183 (const :tag "Python" python)
184 (const :tag "Ruby" ruby)
185 (const :tag "Sass" sass)
186 (const :tag "Scala" scala)
187 (const :tag "Scheme" scheme)
188 (const :tag "Screen" screen)
189 (const :tag "Shell Script" sh)
190 (const :tag "Shen" shen)
191 (const :tag "Sql" sql)
192 (const :tag "Sqlite" sqlite))
193 :value-type (boolean :tag "Activate" :value t)))
195 ;;;; Customization variables
196 (defcustom org-clone-delete-id nil
197 "Remove ID property of clones of a subtree.
198 When non-nil, clones of a subtree don't inherit the ID property.
199 Otherwise they inherit the ID property with a new unique
200 identifier."
201 :type 'boolean
202 :version "24.1"
203 :group 'org-id)
205 ;;; Version
206 (require 'org-compat)
207 (org-check-version)
208 ;;;###autoload
209 (defun org-version (&optional here full message)
210 "Show the org-mode version in the echo area.
211 With prefix argument HERE, insert it at point.
212 When FULL is non-nil, use a verbose version string.
213 When MESSAGE is non-nil, display a message with the version."
214 (interactive "P")
215 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
216 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
217 (org-trash (or
218 (and (fboundp 'org-release) (fboundp 'org-git-version))
219 (load (concat org-dir "org-version.el")
220 'noerror 'nomessage 'nosuffix)))
221 (org-version (org-release))
222 (git-version (org-git-version))
223 (version (format "Org-mode version %s (%s @ %s)"
224 org-version
225 git-version
226 (if org-install-dir
227 (if (string= org-dir org-install-dir)
228 org-install-dir
229 (concat "mixed installation! " org-install-dir " and " org-dir))
230 "org-install.el can not be found!")))
231 (_version (if full version org-version)))
232 (if (org-called-interactively-p 'interactive)
233 (if here
234 (insert version)
235 (message version))
236 (if message (message _version))
237 _version)))
239 ;;; Compatibility constants
241 ;;; The custom variables
243 (defgroup org nil
244 "Outline-based notes management and organizer."
245 :tag "Org"
246 :group 'outlines
247 :group 'calendar)
249 (defcustom org-mode-hook nil
250 "Mode hook for Org-mode, run after the mode was turned on."
251 :group 'org
252 :type 'hook)
254 (defcustom org-load-hook nil
255 "Hook that is run after org.el has been loaded."
256 :group 'org
257 :type 'hook)
259 (defcustom org-log-buffer-setup-hook nil
260 "Hook that is run after an Org log buffer is created."
261 :group 'org
262 :version "24.1"
263 :type 'hook)
265 (defvar org-modules) ; defined below
266 (defvar org-modules-loaded nil
267 "Have the modules been loaded already?")
269 (defun org-load-modules-maybe (&optional force)
270 "Load all extensions listed in `org-modules'."
271 (when (or force (not org-modules-loaded))
272 (mapc (lambda (ext)
273 (condition-case nil (require ext)
274 (error (message "Problems while trying to load feature `%s'" ext))))
275 org-modules)
276 (setq org-modules-loaded t)))
278 (defun org-set-modules (var value)
279 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
280 (set var value)
281 (when (featurep 'org)
282 (org-load-modules-maybe 'force)))
284 (when (org-bound-and-true-p org-modules)
285 (let ((a (member 'org-infojs org-modules)))
286 (and a (setcar a 'org-jsinfo))))
288 (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)
289 "Modules that should always be loaded together with org.el.
290 If a description starts with <C>, the file is not part of Emacs
291 and loading it will require that you have downloaded and properly installed
292 the org-mode distribution.
294 You can also use this system to load external packages (i.e. neither Org
295 core modules, nor modules from the CONTRIB directory). Just add symbols
296 to the end of the list. If the package is called org-xyz.el, then you need
297 to add the symbol `xyz', and the package must have a call to
299 (provide 'org-xyz)"
300 :group 'org
301 :set 'org-set-modules
302 :type
303 '(set :greedy t
304 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
305 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
306 (const :tag " crypt: Encryption of subtrees" org-crypt)
307 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
308 (const :tag " docview: Links to doc-view buffers" org-docview)
309 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
310 (const :tag " id: Global IDs for identifying entries" org-id)
311 (const :tag " info: Links to Info nodes" org-info)
312 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
313 (const :tag " habit: Track your consistency with habits" org-habit)
314 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
315 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
316 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
317 (const :tag " mew Links to Mew folders/messages" org-mew)
318 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
319 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
320 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
321 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
322 (const :tag " vm: Links to VM folders/messages" org-vm)
323 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
324 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
325 (const :tag " mouse: Additional mouse support" org-mouse)
326 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
328 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
329 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
330 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
331 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
332 (const :tag "C collector: Collect properties into tables" org-collector)
333 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
334 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
335 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
336 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
337 (const :tag "C eval: Include command output as text" org-eval)
338 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
339 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
340 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
341 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
342 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
344 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
346 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
347 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
348 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
349 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
350 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
351 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
352 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
353 (const :tag "C mtags: Support for muse-like tags" org-mtags)
354 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
355 (const :tag "C registry: A registry for Org-mode links" org-registry)
356 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
357 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
358 (const :tag "C secretary: Team management with org-mode" org-secretary)
359 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
360 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
361 (const :tag "C track: Keep up with Org-mode development" org-track)
362 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
363 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
364 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
366 (defcustom org-support-shift-select nil
367 "Non-nil means make shift-cursor commands select text when possible.
369 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
370 start selecting a region, or enlarge regions started in this way.
371 In Org-mode, in special contexts, these same keys are used for
372 other purposes, important enough to compete with shift selection.
373 Org tries to balance these needs by supporting `shift-select-mode'
374 outside these special contexts, under control of this variable.
376 The default of this variable is nil, to avoid confusing behavior. Shifted
377 cursor keys will then execute Org commands in the following contexts:
378 - on a headline, changing TODO state (left/right) and priority (up/down)
379 - on a time stamp, changing the time
380 - in a plain list item, changing the bullet type
381 - in a property definition line, switching between allowed values
382 - in the BEGIN line of a clock table (changing the time block).
383 Outside these contexts, the commands will throw an error.
385 When this variable is t and the cursor is not in a special
386 context, Org-mode will support shift-selection for making and
387 enlarging regions. To make this more effective, the bullet
388 cycling will no longer happen anywhere in an item line, but only
389 if the cursor is exactly on the bullet.
391 If you set this variable to the symbol `always', then the keys
392 will not be special in headlines, property lines, and item lines,
393 to make shift selection work there as well. If this is what you
394 want, you can use the following alternative commands: `C-c C-t'
395 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
396 can be used to switch TODO sets, `C-c -' to cycle item bullet
397 types, and properties can be edited by hand or in column view.
399 However, when the cursor is on a timestamp, shift-cursor commands
400 will still edit the time stamp - this is just too good to give up.
402 XEmacs user should have this variable set to nil, because
403 `shift-select-mode' is in Emacs 23 or later only."
404 :group 'org
405 :type '(choice
406 (const :tag "Never" nil)
407 (const :tag "When outside special context" t)
408 (const :tag "Everywhere except timestamps" always)))
410 (defcustom org-loop-over-headlines-in-active-region nil
411 "Shall some commands act upon headlines in the active region?
413 When set to `t', some commands will be performed in all headlines
414 within the active region.
416 When set to `start-level', some commands will be performed in all
417 headlines within the active region, provided that these headlines
418 are of the same level than the first one.
420 When set to a string, those commands will be performed on the
421 matching headlines within the active region. Such string must be
422 a tags/property/todo match as it is used in the agenda tags view.
424 The list of commands is: `org-schedule', `org-deadline',
425 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
426 `org-archive-to-archive-sibling'. The archiving commands skip
427 already archived entries."
428 :type '(choice (const :tag "Don't loop" nil)
429 (const :tag "All headlines in active region" t)
430 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
431 (string :tag "Tags/Property/Todo matcher"))
432 :version "24.1"
433 :group 'org-todo
434 :group 'org-archive)
436 (defgroup org-startup nil
437 "Options concerning startup of Org-mode."
438 :tag "Org Startup"
439 :group 'org)
441 (defcustom org-startup-folded t
442 "Non-nil means entering Org-mode will switch to OVERVIEW.
443 This can also be configured on a per-file basis by adding one of
444 the following lines anywhere in the buffer:
446 #+STARTUP: fold (or `overview', this is equivalent)
447 #+STARTUP: nofold (or `showall', this is equivalent)
448 #+STARTUP: content
449 #+STARTUP: showeverything"
450 :group 'org-startup
451 :type '(choice
452 (const :tag "nofold: show all" nil)
453 (const :tag "fold: overview" t)
454 (const :tag "content: all headlines" content)
455 (const :tag "show everything, even drawers" showeverything)))
457 (defcustom org-startup-truncated t
458 "Non-nil means entering Org-mode will set `truncate-lines'.
459 This is useful since some lines containing links can be very long and
460 uninteresting. Also tables look terrible when wrapped."
461 :group 'org-startup
462 :type 'boolean)
464 (defcustom org-startup-indented nil
465 "Non-nil means turn on `org-indent-mode' on startup.
466 This can also be configured on a per-file basis by adding one of
467 the following lines anywhere in the buffer:
469 #+STARTUP: indent
470 #+STARTUP: noindent"
471 :group 'org-structure
472 :type '(choice
473 (const :tag "Not" nil)
474 (const :tag "Globally (slow on startup in large files)" t)))
476 (defcustom org-use-sub-superscripts t
477 "Non-nil means interpret \"_\" and \"^\" for export.
478 When this option is turned on, you can use TeX-like syntax for sub- and
479 superscripts. Several characters after \"_\" or \"^\" will be
480 considered as a single item - so grouping with {} is normally not
481 needed. For example, the following things will be parsed as single
482 sub- or superscripts.
484 10^24 or 10^tau several digits will be considered 1 item.
485 10^-12 or 10^-tau a leading sign with digits or a word
486 x^2-y^3 will be read as x^2 - y^3, because items are
487 terminated by almost any nonword/nondigit char.
488 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
490 Still, ambiguity is possible - so when in doubt use {} to enclose the
491 sub/superscript. If you set this variable to the symbol `{}',
492 the braces are *required* in order to trigger interpretations as
493 sub/superscript. This can be helpful in documents that need \"_\"
494 frequently in plain text.
496 Not all export backends support this, but HTML does.
498 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
499 :group 'org-startup
500 :group 'org-export-translation
501 :version "24.1"
502 :type '(choice
503 (const :tag "Always interpret" t)
504 (const :tag "Only with braces" {})
505 (const :tag "Never interpret" nil)))
507 (if (fboundp 'defvaralias)
508 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
511 (defcustom org-startup-with-beamer-mode nil
512 "Non-nil means turn on `org-beamer-mode' on startup.
513 This can also be configured on a per-file basis by adding one of
514 the following lines anywhere in the buffer:
516 #+STARTUP: beamer"
517 :group 'org-startup
518 :version "24.1"
519 :type 'boolean)
521 (defcustom org-startup-align-all-tables nil
522 "Non-nil means align all tables when visiting a file.
523 This is useful when the column width in tables is forced with <N> cookies
524 in table fields. Such tables will look correct only after the first re-align.
525 This can also be configured on a per-file basis by adding one of
526 the following lines anywhere in the buffer:
527 #+STARTUP: align
528 #+STARTUP: noalign"
529 :group 'org-startup
530 :type 'boolean)
532 (defcustom org-startup-with-inline-images nil
533 "Non-nil means show inline images when loading a new Org file.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
536 #+STARTUP: inlineimages
537 #+STARTUP: noinlineimages"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-insert-mode-line-in-empty-file nil
543 "Non-nil means insert the first line setting Org-mode in empty files.
544 When the function `org-mode' is called interactively in an empty file, this
545 normally means that the file name does not automatically trigger Org-mode.
546 To ensure that the file will always be in Org-mode in the future, a
547 line enforcing Org-mode will be inserted into the buffer, if this option
548 has been set."
549 :group 'org-startup
550 :type 'boolean)
552 (defcustom org-replace-disputed-keys nil
553 "Non-nil means use alternative key bindings for some keys.
554 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
555 These keys are also used by other packages like shift-selection-mode'
556 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
557 If you want to use Org-mode together with one of these other modes,
558 or more generally if you would like to move some Org-mode commands to
559 other keys, set this variable and configure the keys with the variable
560 `org-disputed-keys'.
562 This option is only relevant at load-time of Org-mode, and must be set
563 *before* org.el is loaded. Changing it requires a restart of Emacs to
564 become effective."
565 :group 'org-startup
566 :type 'boolean)
568 (defcustom org-use-extra-keys nil
569 "Non-nil means use extra key sequence definitions for certain commands.
570 This happens automatically if you run XEmacs or if `window-system'
571 is nil. This variable lets you do the same manually. You must
572 set it before loading org.
574 Example: on Carbon Emacs 22 running graphically, with an external
575 keyboard on a Powerbook, the default way of setting M-left might
576 not work for either Alt or ESC. Setting this variable will make
577 it work for ESC."
578 :group 'org-startup
579 :type 'boolean)
581 (if (fboundp 'defvaralias)
582 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
584 (defcustom org-disputed-keys
585 '(([(shift up)] . [(meta p)])
586 ([(shift down)] . [(meta n)])
587 ([(shift left)] . [(meta -)])
588 ([(shift right)] . [(meta +)])
589 ([(control shift right)] . [(meta shift +)])
590 ([(control shift left)] . [(meta shift -)]))
591 "Keys for which Org-mode and other modes compete.
592 This is an alist, cars are the default keys, second element specifies
593 the alternative to use when `org-replace-disputed-keys' is t.
595 Keys can be specified in any syntax supported by `define-key'.
596 The value of this option takes effect only at Org-mode's startup,
597 therefore you'll have to restart Emacs to apply it after changing."
598 :group 'org-startup
599 :type 'alist)
601 (defun org-key (key)
602 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
603 Or return the original if not disputed.
604 Also apply the translations defined in `org-xemacs-key-equivalents'."
605 (when org-replace-disputed-keys
606 (let* ((nkey (key-description key))
607 (x (org-find-if (lambda (x)
608 (equal (key-description (car x)) nkey))
609 org-disputed-keys)))
610 (setq key (if x (cdr x) key))))
611 (when (featurep 'xemacs)
612 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
613 key)
615 (defun org-find-if (predicate seq)
616 (catch 'exit
617 (while seq
618 (if (funcall predicate (car seq))
619 (throw 'exit (car seq))
620 (pop seq)))))
622 (defun org-defkey (keymap key def)
623 "Define a key, possibly translated, as returned by `org-key'."
624 (define-key keymap (org-key key) def))
626 (defcustom org-ellipsis nil
627 "The ellipsis to use in the Org-mode outline.
628 When nil, just use the standard three dots. When a string, use that instead,
629 When a face, use the standard 3 dots, but with the specified face.
630 The change affects only Org-mode (which will then use its own display table).
631 Changing this requires executing `M-x org-mode' in a buffer to become
632 effective."
633 :group 'org-startup
634 :type '(choice (const :tag "Default" nil)
635 (face :tag "Face" :value org-warning)
636 (string :tag "String" :value "...#")))
638 (defvar org-display-table nil
639 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
641 (defgroup org-keywords nil
642 "Keywords in Org-mode."
643 :tag "Org Keywords"
644 :group 'org)
646 (defcustom org-deadline-string "DEADLINE:"
647 "String to mark deadline entries.
648 A deadline is this string, followed by a time stamp. Should be a word,
649 terminated by a colon. You can insert a schedule keyword and
650 a timestamp with \\[org-deadline].
651 Changes become only effective after restarting Emacs."
652 :group 'org-keywords
653 :type 'string)
655 (defcustom org-scheduled-string "SCHEDULED:"
656 "String to mark scheduled TODO entries.
657 A schedule is this string, followed by a time stamp. Should be a word,
658 terminated by a colon. You can insert a schedule keyword and
659 a timestamp with \\[org-schedule].
660 Changes become only effective after restarting Emacs."
661 :group 'org-keywords
662 :type 'string)
664 (defcustom org-closed-string "CLOSED:"
665 "String used as the prefix for timestamps logging closing a TODO entry."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-clock-string "CLOCK:"
670 "String used as prefix for timestamps clocking work hours on an item."
671 :group 'org-keywords
672 :type 'string)
674 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
675 org-scheduled-string "\\|"
676 org-deadline-string "\\|"
677 org-closed-string "\\|"
678 org-clock-string "\\)")
679 "Matches a line with planning or clock info.")
681 (defcustom org-comment-string "COMMENT"
682 "Entries starting with this keyword will never be exported.
683 An entry can be toggled between COMMENT and normal with
684 \\[org-toggle-comment].
685 Changes become only effective after restarting Emacs."
686 :group 'org-keywords
687 :type 'string)
689 (defcustom org-quote-string "QUOTE"
690 "Entries starting with this keyword will be exported in fixed-width font.
691 Quoting applies only to the text in the entry following the headline, and does
692 not extend beyond the next headline, even if that is lower level.
693 An entry can be toggled between QUOTE and normal with
694 \\[org-toggle-fixed-width-section]."
695 :group 'org-keywords
696 :type 'string)
698 (defconst org-repeat-re
699 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
700 "Regular expression for specifying repeated events.
701 After a match, group 1 contains the repeat expression.")
703 (defgroup org-structure nil
704 "Options concerning the general structure of Org-mode files."
705 :tag "Org Structure"
706 :group 'org)
708 (defgroup org-reveal-location nil
709 "Options about how to make context of a location visible."
710 :tag "Org Reveal Location"
711 :group 'org-structure)
713 (defconst org-context-choice
714 '(choice
715 (const :tag "Always" t)
716 (const :tag "Never" nil)
717 (repeat :greedy t :tag "Individual contexts"
718 (cons
719 (choice :tag "Context"
720 (const agenda)
721 (const org-goto)
722 (const occur-tree)
723 (const tags-tree)
724 (const link-search)
725 (const mark-goto)
726 (const bookmark-jump)
727 (const isearch)
728 (const default))
729 (boolean))))
730 "Contexts for the reveal options.")
732 (defcustom org-show-hierarchy-above '((default . t))
733 "Non-nil means show full hierarchy when revealing a location.
734 Org-mode often shows locations in an org-mode file which might have
735 been invisible before. When this is set, the hierarchy of headings
736 above the exposed location is shown.
737 Turning this off for example for sparse trees makes them very compact.
738 Instead of t, this can also be an alist specifying this option for different
739 contexts. Valid contexts are
740 agenda when exposing an entry from the agenda
741 org-goto when using the command `org-goto' on key C-c C-j
742 occur-tree when using the command `org-occur' on key C-c /
743 tags-tree when constructing a sparse tree based on tags matches
744 link-search when exposing search matches associated with a link
745 mark-goto when exposing the jump goal of a mark
746 bookmark-jump when exposing a bookmark location
747 isearch when exiting from an incremental search
748 default default for all contexts not set explicitly"
749 :group 'org-reveal-location
750 :type org-context-choice)
752 (defcustom org-show-following-heading '((default . nil))
753 "Non-nil means show following heading when revealing a location.
754 Org-mode often shows locations in an org-mode file which might have
755 been invisible before. When this is set, the heading following the
756 match is shown.
757 Turning this off for example for sparse trees makes them very compact,
758 but makes it harder to edit the location of the match. In such a case,
759 use the command \\[org-reveal] to show more context.
760 Instead of t, this can also be an alist specifying this option for different
761 contexts. See `org-show-hierarchy-above' for valid contexts."
762 :group 'org-reveal-location
763 :type org-context-choice)
765 (defcustom org-show-siblings '((default . nil) (isearch t))
766 "Non-nil means show all sibling heading when revealing a location.
767 Org-mode often shows locations in an org-mode file which might have
768 been invisible before. When this is set, the sibling of the current entry
769 heading are all made visible. If `org-show-hierarchy-above' is t,
770 the same happens on each level of the hierarchy above the current entry.
772 By default this is on for the isearch context, off for all other contexts.
773 Turning this off for example for sparse trees makes them very compact,
774 but makes it harder to edit the location of the match. In such a case,
775 use the command \\[org-reveal] to show more context.
776 Instead of t, this can also be an alist specifying this option for different
777 contexts. See `org-show-hierarchy-above' for valid contexts."
778 :group 'org-reveal-location
779 :type org-context-choice)
781 (defcustom org-show-entry-below '((default . nil))
782 "Non-nil means show the entry below a headline when revealing a location.
783 Org-mode often shows locations in an org-mode file which might have
784 been invisible before. When this is set, the text below the headline that is
785 exposed is also shown.
787 By default this is off for all contexts.
788 Instead of t, this can also be an alist specifying this option for different
789 contexts. See `org-show-hierarchy-above' for valid contexts."
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-indirect-buffer-display 'other-window
794 "How should indirect tree buffers be displayed?
795 This applies to indirect buffers created with the commands
796 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
797 Valid values are:
798 current-window Display in the current window
799 other-window Just display in another window.
800 dedicated-frame Create one new frame, and re-use it each time.
801 new-frame Make a new frame each time. Note that in this case
802 previously-made indirect buffers are kept, and you need to
803 kill these buffers yourself."
804 :group 'org-structure
805 :group 'org-agenda-windows
806 :type '(choice
807 (const :tag "In current window" current-window)
808 (const :tag "In current frame, other window" other-window)
809 (const :tag "Each time a new frame" new-frame)
810 (const :tag "One dedicated frame" dedicated-frame)))
812 (defcustom org-use-speed-commands nil
813 "Non-nil means activate single letter commands at beginning of a headline.
814 This may also be a function to test for appropriate locations where speed
815 commands should be active."
816 :group 'org-structure
817 :type '(choice
818 (const :tag "Never" nil)
819 (const :tag "At beginning of headline stars" t)
820 (function)))
822 (defcustom org-speed-commands-user nil
823 "Alist of additional speed commands.
824 This list will be checked before `org-speed-commands-default'
825 when the variable `org-use-speed-commands' is non-nil
826 and when the cursor is at the beginning of a headline.
827 The car if each entry is a string with a single letter, which must
828 be assigned to `self-insert-command' in the global map.
829 The cdr is either a command to be called interactively, a function
830 to be called, or a form to be evaluated.
831 An entry that is just a list with a single string will be interpreted
832 as a descriptive headline that will be added when listing the speed
833 commands in the Help buffer using the `?' speed command."
834 :group 'org-structure
835 :type '(repeat :value ("k" . ignore)
836 (choice :value ("k" . ignore)
837 (list :tag "Descriptive Headline" (string :tag "Headline"))
838 (cons :tag "Letter and Command"
839 (string :tag "Command letter")
840 (choice
841 (function)
842 (sexp))))))
844 (defgroup org-cycle nil
845 "Options concerning visibility cycling in Org-mode."
846 :tag "Org Cycle"
847 :group 'org-structure)
849 (defcustom org-cycle-skip-children-state-if-no-children t
850 "Non-nil means skip CHILDREN state in entries that don't have any."
851 :group 'org-cycle
852 :type 'boolean)
854 (defcustom org-cycle-max-level nil
855 "Maximum level which should still be subject to visibility cycling.
856 Levels higher than this will, for cycling, be treated as text, not a headline.
857 When `org-odd-levels-only' is set, a value of N in this variable actually
858 means 2N-1 stars as the limiting headline.
859 When nil, cycle all levels.
860 Note that the limiting level of cycling is also influenced by
861 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
862 `org-inlinetask-min-level' is, cycling will be limited to levels one less
863 than its value."
864 :group 'org-cycle
865 :type '(choice
866 (const :tag "No limit" nil)
867 (integer :tag "Maximum level")))
869 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
870 "Names of drawers. Drawers are not opened by cycling on the headline above.
871 Drawers only open with a TAB on the drawer line itself. A drawer looks like
872 this:
873 :DRAWERNAME:
874 .....
875 :END:
876 The drawer \"PROPERTIES\" is special for capturing properties through
877 the property API.
879 Drawers can be defined on the per-file basis with a line like:
881 #+DRAWERS: HIDDEN STATE PROPERTIES"
882 :group 'org-structure
883 :group 'org-cycle
884 :type '(repeat (string :tag "Drawer Name")))
886 (defcustom org-hide-block-startup nil
887 "Non-nil means entering Org-mode will fold all blocks.
888 This can also be set in on a per-file basis with
890 #+STARTUP: hideblocks
891 #+STARTUP: showblocks"
892 :group 'org-startup
893 :group 'org-cycle
894 :type 'boolean)
896 (defcustom org-cycle-global-at-bob nil
897 "Cycle globally if cursor is at beginning of buffer and not at a headline.
898 This makes it possible to do global cycling without having to use S-TAB or
899 \\[universal-argument] TAB. For this special case to work, the first line \
900 of the buffer
901 must not be a headline - it may be empty or some other text. When used in
902 this way, `org-cycle-hook' is disables temporarily, to make sure the
903 cursor stays at the beginning of the buffer.
904 When this option is nil, don't do anything special at the beginning
905 of the buffer."
906 :group 'org-cycle
907 :type 'boolean)
909 (defcustom org-cycle-level-after-item/entry-creation t
910 "Non-nil means cycle entry level or item indentation in new empty entries.
912 When the cursor is at the end of an empty headline, i.e with only stars
913 and maybe a TODO keyword, TAB will then switch the entry to become a child,
914 and then all possible ancestor states, before returning to the original state.
915 This makes data entry extremely fast: M-RET to create a new headline,
916 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
918 When the cursor is at the end of an empty plain list item, one TAB will
919 make it a subitem, two or more tabs will back up to make this an item
920 higher up in the item hierarchy."
921 :group 'org-cycle
922 :type 'boolean)
924 (defcustom org-cycle-emulate-tab t
925 "Where should `org-cycle' emulate TAB.
926 nil Never
927 white Only in completely white lines
928 whitestart Only at the beginning of lines, before the first non-white char
929 t Everywhere except in headlines
930 exc-hl-bol Everywhere except at the start of a headline
931 If TAB is used in a place where it does not emulate TAB, the current subtree
932 visibility is cycled."
933 :group 'org-cycle
934 :type '(choice (const :tag "Never" nil)
935 (const :tag "Only in completely white lines" white)
936 (const :tag "Before first char in a line" whitestart)
937 (const :tag "Everywhere except in headlines" t)
938 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
941 (defcustom org-cycle-separator-lines 2
942 "Number of empty lines needed to keep an empty line between collapsed trees.
943 If you leave an empty line between the end of a subtree and the following
944 headline, this empty line is hidden when the subtree is folded.
945 Org-mode will leave (exactly) one empty line visible if the number of
946 empty lines is equal or larger to the number given in this variable.
947 So the default 2 means at least 2 empty lines after the end of a subtree
948 are needed to produce free space between a collapsed subtree and the
949 following headline.
951 If the number is negative, and the number of empty lines is at least -N,
952 all empty lines are shown.
954 Special case: when 0, never leave empty lines in collapsed view."
955 :group 'org-cycle
956 :type 'integer)
957 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
959 (defcustom org-pre-cycle-hook nil
960 "Hook that is run before visibility cycling is happening.
961 The function(s) in this hook must accept a single argument which indicates
962 the new state that will be set right after running this hook. The
963 argument is a symbol. Before a global state change, it can have the values
964 `overview', `content', or `all'. Before a local state change, it can have
965 the values `folded', `children', or `subtree'."
966 :group 'org-cycle
967 :type 'hook)
969 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
970 org-cycle-hide-drawers
971 org-cycle-show-empty-lines
972 org-optimize-window-after-visibility-change)
973 "Hook that is run after `org-cycle' has changed the buffer visibility.
974 The function(s) in this hook must accept a single argument which indicates
975 the new state that was set by the most recent `org-cycle' command. The
976 argument is a symbol. After a global state change, it can have the values
977 `overview', `content', or `all'. After a local state change, it can have
978 the values `folded', `children', or `subtree'."
979 :group 'org-cycle
980 :type 'hook)
982 (defgroup org-edit-structure nil
983 "Options concerning structure editing in Org-mode."
984 :tag "Org Edit Structure"
985 :group 'org-structure)
987 (defcustom org-odd-levels-only nil
988 "Non-nil means skip even levels and only use odd levels for the outline.
989 This has the effect that two stars are being added/taken away in
990 promotion/demotion commands. It also influences how levels are
991 handled by the exporters.
992 Changing it requires restart of `font-lock-mode' to become effective
993 for fontification also in regions already fontified.
994 You may also set this on a per-file basis by adding one of the following
995 lines to the buffer:
997 #+STARTUP: odd
998 #+STARTUP: oddeven"
999 :group 'org-edit-structure
1000 :group 'org-appearance
1001 :type 'boolean)
1003 (defcustom org-adapt-indentation t
1004 "Non-nil means adapt indentation to outline node level.
1006 When this variable is set, Org assumes that you write outlines by
1007 indenting text in each node to align with the headline (after the stars).
1008 The following issues are influenced by this variable:
1010 - When this is set and the *entire* text in an entry is indented, the
1011 indentation is increased by one space in a demotion command, and
1012 decreased by one in a promotion command. If any line in the entry
1013 body starts with text at column 0, indentation is not changed at all.
1015 - Property drawers and planning information is inserted indented when
1016 this variable s set. When nil, they will not be indented.
1018 - TAB indents a line relative to context. The lines below a headline
1019 will be indented when this variable is set.
1021 Note that this is all about true indentation, by adding and removing
1022 space characters. See also `org-indent.el' which does level-dependent
1023 indentation in a virtual way, i.e. at display time in Emacs."
1024 :group 'org-edit-structure
1025 :type 'boolean)
1027 (defcustom org-special-ctrl-a/e nil
1028 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1030 When t, `C-a' will bring back the cursor to the beginning of the
1031 headline text, i.e. after the stars and after a possible TODO
1032 keyword. In an item, this will be the position after bullet and
1033 check-box, if any. When the cursor is already at that position,
1034 another `C-a' will bring it to the beginning of the line.
1036 `C-e' will jump to the end of the headline, ignoring the presence
1037 of tags in the headline. A second `C-e' will then jump to the
1038 true end of the line, after any tags. This also means that, when
1039 this variable is non-nil, `C-e' also will never jump beyond the
1040 end of the heading of a folded section, i.e. not after the
1041 ellipses.
1043 When set to the symbol `reversed', the first `C-a' or `C-e' works
1044 normally, going to the true line boundary first. Only a directly
1045 following, identical keypress will bring the cursor to the
1046 special positions.
1048 This may also be a cons cell where the behavior for `C-a' and
1049 `C-e' is set separately."
1050 :group 'org-edit-structure
1051 :type '(choice
1052 (const :tag "off" nil)
1053 (const :tag "on: after stars/bullet and before tags first" t)
1054 (const :tag "reversed: true line boundary first" reversed)
1055 (cons :tag "Set C-a and C-e separately"
1056 (choice :tag "Special C-a"
1057 (const :tag "off" nil)
1058 (const :tag "on: after stars/bullet first" t)
1059 (const :tag "reversed: before stars/bullet first" reversed))
1060 (choice :tag "Special C-e"
1061 (const :tag "off" nil)
1062 (const :tag "on: before tags first" t)
1063 (const :tag "reversed: after tags first" reversed)))))
1064 (if (fboundp 'defvaralias)
1065 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1067 (defcustom org-special-ctrl-k nil
1068 "Non-nil means `C-k' will behave specially in headlines.
1069 When nil, `C-k' will call the default `kill-line' command.
1070 When t, the following will happen while the cursor is in the headline:
1072 - When the cursor is at the beginning of a headline, kill the entire
1073 line and possible the folded subtree below the line.
1074 - When in the middle of the headline text, kill the headline up to the tags.
1075 - When after the headline text, kill the tags."
1076 :group 'org-edit-structure
1077 :type 'boolean)
1079 (defcustom org-ctrl-k-protect-subtree nil
1080 "Non-nil means, do not delete a hidden subtree with C-k.
1081 When set to the symbol `error', simply throw an error when C-k is
1082 used to kill (part-of) a headline that has hidden text behind it.
1083 Any other non-nil value will result in a query to the user, if it is
1084 OK to kill that hidden subtree. When nil, kill without remorse."
1085 :group 'org-edit-structure
1086 :version "24.1"
1087 :type '(choice
1088 (const :tag "Do not protect hidden subtrees" nil)
1089 (const :tag "Protect hidden subtrees with a security query" t)
1090 (const :tag "Never kill a hidden subtree with C-k" error)))
1092 (defcustom org-catch-invisible-edits nil
1093 "Check if in invisible region before inserting or deleting a character.
1094 Valid values are:
1096 nil Do not check, so just do invisible edits.
1097 error Throw an error and do nothing.
1098 show Make point visible, and do the requested edit.
1099 show-and-error Make point visible, then throw an error and abort the edit.
1100 smart Make point visible, and do insertion/deletion if it is
1101 adjacent to visible text and the change feels predictable.
1102 Never delete a previously invisible character or add in the
1103 middle or right after an invisible region. Basically, this
1104 allows insertion and backward-delete right before ellipses.
1105 FIXME: maybe in this case we should not even show?"
1106 :group 'org-edit-structure
1107 :version "24.1"
1108 :type '(choice
1109 (const :tag "Do not check" nil)
1110 (const :tag "Throw error when trying to edit" error)
1111 (const :tag "Unhide, but do not do the edit" show-and-error)
1112 (const :tag "Show invisible part and do the edit" show)
1113 (const :tag "Be smart and do the right thing" smart)))
1115 (defcustom org-yank-folded-subtrees t
1116 "Non-nil means when yanking subtrees, fold them.
1117 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1118 it starts with a heading and all other headings in it are either children
1119 or siblings, then fold all the subtrees. However, do this only if no
1120 text after the yank would be swallowed into a folded tree by this action."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1124 (defcustom org-yank-adjusted-subtrees nil
1125 "Non-nil means when yanking subtrees, adjust the level.
1126 With this setting, `org-paste-subtree' is used to insert the subtree, see
1127 this function for details."
1128 :group 'org-edit-structure
1129 :type 'boolean)
1131 (defcustom org-M-RET-may-split-line '((default . t))
1132 "Non-nil means M-RET will split the line at the cursor position.
1133 When nil, it will go to the end of the line before making a
1134 new line.
1135 You may also set this option in a different way for different
1136 contexts. Valid contexts are:
1138 headline when creating a new headline
1139 item when creating a new item
1140 table in a table field
1141 default the value to be used for all contexts not explicitly
1142 customized"
1143 :group 'org-structure
1144 :group 'org-table
1145 :type '(choice
1146 (const :tag "Always" t)
1147 (const :tag "Never" nil)
1148 (repeat :greedy t :tag "Individual contexts"
1149 (cons
1150 (choice :tag "Context"
1151 (const headline)
1152 (const item)
1153 (const table)
1154 (const default))
1155 (boolean)))))
1158 (defcustom org-insert-heading-respect-content nil
1159 "Non-nil means insert new headings after the current subtree.
1160 When nil, the new heading is created directly after the current line.
1161 The commands \\[org-insert-heading-respect-content] and
1162 \\[org-insert-todo-heading-respect-content] turn this variable on
1163 for the duration of the command."
1164 :group 'org-structure
1165 :type 'boolean)
1167 (defcustom org-blank-before-new-entry '((heading . auto)
1168 (plain-list-item . auto))
1169 "Should `org-insert-heading' leave a blank line before new heading/item?
1170 The value is an alist, with `heading' and `plain-list-item' as CAR,
1171 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1172 which case Org will look at the surrounding headings/items and try to
1173 make an intelligent decision whether to insert a blank line or not.
1175 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1176 set, the setting here is ignored and no empty line is inserted, to avoid
1177 breaking the list structure."
1178 :group 'org-edit-structure
1179 :type '(list
1180 (cons (const heading)
1181 (choice (const :tag "Never" nil)
1182 (const :tag "Always" t)
1183 (const :tag "Auto" auto)))
1184 (cons (const plain-list-item)
1185 (choice (const :tag "Never" nil)
1186 (const :tag "Always" t)
1187 (const :tag "Auto" auto)))))
1189 (defcustom org-insert-heading-hook nil
1190 "Hook being run after inserting a new heading."
1191 :group 'org-edit-structure
1192 :type 'hook)
1194 (defcustom org-enable-fixed-width-editor t
1195 "Non-nil means lines starting with \":\" are treated as fixed-width.
1196 This currently only means they are never auto-wrapped.
1197 When nil, such lines will be treated like ordinary lines.
1198 See also the QUOTE keyword."
1199 :group 'org-edit-structure
1200 :type 'boolean)
1202 (defcustom org-goto-auto-isearch t
1203 "Non-nil means typing characters in `org-goto' starts incremental search."
1204 :group 'org-edit-structure
1205 :type 'boolean)
1207 (defgroup org-sparse-trees nil
1208 "Options concerning sparse trees in Org-mode."
1209 :tag "Org Sparse Trees"
1210 :group 'org-structure)
1212 (defcustom org-highlight-sparse-tree-matches t
1213 "Non-nil means highlight all matches that define a sparse tree.
1214 The highlights will automatically disappear the next time the buffer is
1215 changed by an edit command."
1216 :group 'org-sparse-trees
1217 :type 'boolean)
1219 (defcustom org-remove-highlights-with-change t
1220 "Non-nil means any change to the buffer will remove temporary highlights.
1221 Such highlights are created by `org-occur' and `org-clock-display'.
1222 When nil, `C-c C-c needs to be used to get rid of the highlights.
1223 The highlights created by `org-preview-latex-fragment' always need
1224 `C-c C-c' to be removed."
1225 :group 'org-sparse-trees
1226 :group 'org-time
1227 :type 'boolean)
1230 (defcustom org-occur-hook '(org-first-headline-recenter)
1231 "Hook that is run after `org-occur' has constructed a sparse tree.
1232 This can be used to recenter the window to show as much of the structure
1233 as possible."
1234 :group 'org-sparse-trees
1235 :type 'hook)
1237 (defgroup org-imenu-and-speedbar nil
1238 "Options concerning imenu and speedbar in Org-mode."
1239 :tag "Org Imenu and Speedbar"
1240 :group 'org-structure)
1242 (defcustom org-imenu-depth 2
1243 "The maximum level for Imenu access to Org-mode headlines.
1244 This also applied for speedbar access."
1245 :group 'org-imenu-and-speedbar
1246 :type 'integer)
1248 (defgroup org-table nil
1249 "Options concerning tables in Org-mode."
1250 :tag "Org Table"
1251 :group 'org)
1253 (defcustom org-enable-table-editor 'optimized
1254 "Non-nil means lines starting with \"|\" are handled by the table editor.
1255 When nil, such lines will be treated like ordinary lines.
1257 When equal to the symbol `optimized', the table editor will be optimized to
1258 do the following:
1259 - Automatic overwrite mode in front of whitespace in table fields.
1260 This makes the structure of the table stay in tact as long as the edited
1261 field does not exceed the column width.
1262 - Minimize the number of realigns. Normally, the table is aligned each time
1263 TAB or RET are pressed to move to another field. With optimization this
1264 happens only if changes to a field might have changed the column width.
1265 Optimization requires replacing the functions `self-insert-command',
1266 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1267 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1268 very good at guessing when a re-align will be necessary, but you can always
1269 force one with \\[org-ctrl-c-ctrl-c].
1271 If you would like to use the optimized version in Org-mode, but the
1272 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1274 This variable can be used to turn on and off the table editor during a session,
1275 but in order to toggle optimization, a restart is required.
1277 See also the variable `org-table-auto-blank-field'."
1278 :group 'org-table
1279 :type '(choice
1280 (const :tag "off" nil)
1281 (const :tag "on" t)
1282 (const :tag "on, optimized" optimized)))
1284 (defcustom org-self-insert-cluster-for-undo (version<= emacs-version "24.1")
1285 "Non-nil means cluster self-insert commands for undo when possible.
1286 If this is set, then, like in the Emacs command loop, 20 consecutive
1287 characters will be undone together.
1288 This is configurable, because there is some impact on typing performance."
1289 :group 'org-table
1290 :type 'boolean)
1292 (defcustom org-table-tab-recognizes-table.el t
1293 "Non-nil means TAB will automatically notice a table.el table.
1294 When it sees such a table, it moves point into it and - if necessary -
1295 calls `table-recognize-table'."
1296 :group 'org-table-editing
1297 :type 'boolean)
1299 (defgroup org-link nil
1300 "Options concerning links in Org-mode."
1301 :tag "Org Link"
1302 :group 'org)
1304 (defvar org-link-abbrev-alist-local nil
1305 "Buffer-local version of `org-link-abbrev-alist', which see.
1306 The value of this is taken from the #+LINK lines.")
1307 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1309 (defcustom org-link-abbrev-alist nil
1310 "Alist of link abbreviations.
1311 The car of each element is a string, to be replaced at the start of a link.
1312 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1313 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1315 [[linkkey:tag][description]]
1317 The 'linkkey' must be a word word, starting with a letter, followed
1318 by letters, numbers, '-' or '_'.
1320 If REPLACE is a string, the tag will simply be appended to create the link.
1321 If the string contains \"%s\", the tag will be inserted there. If the string
1322 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1323 at that point (see the function `url-hexify-string'). If the string contains
1324 the specifier \"%(my-function)\", then the custom function `my-function' will
1325 be invoked: this function takes the tag as its only argument and must return
1326 a string.
1328 REPLACE may also be a function that will be called with the tag as the
1329 only argument to create the link, which should be returned as a string.
1331 See the manual for examples."
1332 :group 'org-link
1333 :type '(repeat
1334 (cons
1335 (string :tag "Protocol")
1336 (choice
1337 (string :tag "Format")
1338 (function)))))
1340 (defcustom org-descriptive-links t
1341 "Non-nil means Org will display descriptive links.
1342 E.g. [[http://orgmode.org][Org website]] will be displayed as
1343 \"Org Website\", hiding the link itself and just displaying its
1344 description. When set to `nil', Org will display the full links
1345 literally.
1347 You can interactively set the value of this variable by calling
1348 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1349 :group 'org-link
1350 :type 'boolean)
1352 (defcustom org-link-file-path-type 'adaptive
1353 "How the path name in file links should be stored.
1354 Valid values are:
1356 relative Relative to the current directory, i.e. the directory of the file
1357 into which the link is being inserted.
1358 absolute Absolute path, if possible with ~ for home directory.
1359 noabbrev Absolute path, no abbreviation of home directory.
1360 adaptive Use relative path for files in the current directory and sub-
1361 directories of it. For other files, use an absolute path."
1362 :group 'org-link
1363 :type '(choice
1364 (const relative)
1365 (const absolute)
1366 (const noabbrev)
1367 (const adaptive)))
1369 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1370 "Types of links that should be activated in Org-mode files.
1371 This is a list of symbols, each leading to the activation of a certain link
1372 type. In principle, it does not hurt to turn on most link types - there may
1373 be a small gain when turning off unused link types. The types are:
1375 bracket The recommended [[link][description]] or [[link]] links with hiding.
1376 angle Links in angular brackets that may contain whitespace like
1377 <bbdb:Carsten Dominik>.
1378 plain Plain links in normal text, no whitespace, like http://google.com.
1379 radio Text that is matched by a radio target, see manual for details.
1380 tag Tag settings in a headline (link to tag search).
1381 date Time stamps (link to calendar).
1382 footnote Footnote labels.
1384 Changing this variable requires a restart of Emacs to become effective."
1385 :group 'org-link
1386 :type '(set :greedy t
1387 (const :tag "Double bracket links" bracket)
1388 (const :tag "Angular bracket links" angle)
1389 (const :tag "Plain text links" plain)
1390 (const :tag "Radio target matches" radio)
1391 (const :tag "Tags" tag)
1392 (const :tag "Timestamps" date)
1393 (const :tag "Footnotes" footnote)))
1395 (defcustom org-make-link-description-function nil
1396 "Function to use to generate link descriptions from links.
1397 If nil the link location will be used. This function must take
1398 two parameters; the first is the link and the second the
1399 description `org-insert-link' has generated, and should return the
1400 description to use."
1401 :group 'org-link
1402 :type 'function)
1404 (defgroup org-link-store nil
1405 "Options concerning storing links in Org-mode."
1406 :tag "Org Store Link"
1407 :group 'org-link)
1409 (defcustom org-url-hexify-p t
1410 "When non-nil, hexify URL when creating a link."
1411 :type 'boolean
1412 :version "24.2"
1413 :group 'org-link-store)
1415 (defcustom org-email-link-description-format "Email %c: %.30s"
1416 "Format of the description part of a link to an email or usenet message.
1417 The following %-escapes will be replaced by corresponding information:
1419 %F full \"From\" field
1420 %f name, taken from \"From\" field, address if no name
1421 %T full \"To\" field
1422 %t first name in \"To\" field, address if no name
1423 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1424 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1425 %s subject
1426 %d date
1427 %m message-id.
1429 You may use normal field width specification between the % and the letter.
1430 This is for example useful to limit the length of the subject.
1432 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1433 :group 'org-link-store
1434 :type 'string)
1436 (defcustom org-from-is-user-regexp
1437 (let (r1 r2)
1438 (when (and user-mail-address (not (string= user-mail-address "")))
1439 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1440 (when (and user-full-name (not (string= user-full-name "")))
1441 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1442 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1443 "Regexp matched against the \"From:\" header of an email or usenet message.
1444 It should match if the message is from the user him/herself."
1445 :group 'org-link-store
1446 :type 'regexp)
1448 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1449 "Non-nil means storing a link to an Org file will use entry IDs.
1451 Note that before this variable is even considered, org-id must be loaded,
1452 so please customize `org-modules' and turn it on.
1454 The variable can have the following values:
1456 t Create an ID if needed to make a link to the current entry.
1458 create-if-interactive
1459 If `org-store-link' is called directly (interactively, as a user
1460 command), do create an ID to support the link. But when doing the
1461 job for remember, only use the ID if it already exists. The
1462 purpose of this setting is to avoid proliferation of unwanted
1463 IDs, just because you happen to be in an Org file when you
1464 call `org-capture' that automatically and preemptively creates a
1465 link. If you do want to get an ID link in a remember template to
1466 an entry not having an ID, create it first by explicitly creating
1467 a link to it, using `C-c C-l' first.
1469 create-if-interactive-and-no-custom-id
1470 Like create-if-interactive, but do not create an ID if there is
1471 a CUSTOM_ID property defined in the entry. This is the default.
1473 use-existing
1474 Use existing ID, do not create one.
1476 nil Never use an ID to make a link, instead link using a text search for
1477 the headline text."
1478 :group 'org-link-store
1479 :type '(choice
1480 (const :tag "Create ID to make link" t)
1481 (const :tag "Create if storing link interactively"
1482 create-if-interactive)
1483 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1484 create-if-interactive-and-no-custom-id)
1485 (const :tag "Only use existing" use-existing)
1486 (const :tag "Do not use ID to create link" nil)))
1488 (defcustom org-context-in-file-links t
1489 "Non-nil means file links from `org-store-link' contain context.
1490 A search string will be added to the file name with :: as separator and
1491 used to find the context when the link is activated by the command
1492 `org-open-at-point'. When this option is t, the entire active region
1493 will be placed in the search string of the file link. If set to a
1494 positive integer, only the first n lines of context will be stored.
1496 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1497 negates this setting for the duration of the command."
1498 :group 'org-link-store
1499 :type '(choice boolean integer))
1501 (defcustom org-keep-stored-link-after-insertion nil
1502 "Non-nil means keep link in list for entire session.
1504 The command `org-store-link' adds a link pointing to the current
1505 location to an internal list. These links accumulate during a session.
1506 The command `org-insert-link' can be used to insert links into any
1507 Org-mode file (offering completion for all stored links). When this
1508 option is nil, every link which has been inserted once using \\[org-insert-link]
1509 will be removed from the list, to make completing the unused links
1510 more efficient."
1511 :group 'org-link-store
1512 :type 'boolean)
1514 (defgroup org-link-follow nil
1515 "Options concerning following links in Org-mode."
1516 :tag "Org Follow Link"
1517 :group 'org-link)
1519 (defcustom org-link-translation-function nil
1520 "Function to translate links with different syntax to Org syntax.
1521 This can be used to translate links created for example by the Planner
1522 or emacs-wiki packages to Org syntax.
1523 The function must accept two parameters, a TYPE containing the link
1524 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1525 which is everything after the link protocol. It should return a cons
1526 with possibly modified values of type and path.
1527 Org contains a function for this, so if you set this variable to
1528 `org-translate-link-from-planner', you should be able follow many
1529 links created by planner."
1530 :group 'org-link-follow
1531 :type 'function)
1533 (defcustom org-follow-link-hook nil
1534 "Hook that is run after a link has been followed."
1535 :group 'org-link-follow
1536 :type 'hook)
1538 (defcustom org-tab-follows-link nil
1539 "Non-nil means on links TAB will follow the link.
1540 Needs to be set before org.el is loaded.
1541 This really should not be used, it does not make sense, and the
1542 implementation is bad."
1543 :group 'org-link-follow
1544 :type 'boolean)
1546 (defcustom org-return-follows-link nil
1547 "Non-nil means on links RET will follow the link."
1548 :group 'org-link-follow
1549 :type 'boolean)
1551 (defcustom org-mouse-1-follows-link
1552 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1553 "Non-nil means mouse-1 on a link will follow the link.
1554 A longer mouse click will still set point. Does not work on XEmacs.
1555 Needs to be set before org.el is loaded."
1556 :group 'org-link-follow
1557 :type 'boolean)
1559 (defcustom org-mark-ring-length 4
1560 "Number of different positions to be recorded in the ring.
1561 Changing this requires a restart of Emacs to work correctly."
1562 :group 'org-link-follow
1563 :type 'integer)
1565 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1566 "Non-nil means internal links in Org files must exactly match a headline.
1567 When nil, the link search tries to match a phrase with all words
1568 in the search text."
1569 :group 'org-link-follow
1570 :version "24.1"
1571 :type '(choice
1572 (const :tag "Use fuzzy text search" nil)
1573 (const :tag "Match only exact headline" t)
1574 (const :tag "Match exact headline or query to create it"
1575 query-to-create)))
1577 (defcustom org-link-frame-setup
1578 '((vm . vm-visit-folder-other-frame)
1579 (vm-imap . vm-visit-imap-folder-other-frame)
1580 (gnus . org-gnus-no-new-news)
1581 (file . find-file-other-window)
1582 (wl . wl-other-frame))
1583 "Setup the frame configuration for following links.
1584 When following a link with Emacs, it may often be useful to display
1585 this link in another window or frame. This variable can be used to
1586 set this up for the different types of links.
1587 For VM, use any of
1588 `vm-visit-folder'
1589 `vm-visit-folder-other-window'
1590 `vm-visit-folder-other-frame'
1591 For Gnus, use any of
1592 `gnus'
1593 `gnus-other-frame'
1594 `org-gnus-no-new-news'
1595 For FILE, use any of
1596 `find-file'
1597 `find-file-other-window'
1598 `find-file-other-frame'
1599 For Wanderlust use any of
1600 `wl'
1601 `wl-other-frame'
1602 For the calendar, use the variable `calendar-setup'.
1603 For BBDB, it is currently only possible to display the matches in
1604 another window."
1605 :group 'org-link-follow
1606 :type '(list
1607 (cons (const vm)
1608 (choice
1609 (const vm-visit-folder)
1610 (const vm-visit-folder-other-window)
1611 (const vm-visit-folder-other-frame)))
1612 (cons (const gnus)
1613 (choice
1614 (const gnus)
1615 (const gnus-other-frame)
1616 (const org-gnus-no-new-news)))
1617 (cons (const file)
1618 (choice
1619 (const find-file)
1620 (const find-file-other-window)
1621 (const find-file-other-frame)))
1622 (cons (const wl)
1623 (choice
1624 (const wl)
1625 (const wl-other-frame)))))
1627 (defcustom org-display-internal-link-with-indirect-buffer nil
1628 "Non-nil means use indirect buffer to display infile links.
1629 Activating internal links (from one location in a file to another location
1630 in the same file) normally just jumps to the location. When the link is
1631 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1632 is displayed in
1633 another window. When this option is set, the other window actually displays
1634 an indirect buffer clone of the current buffer, to avoid any visibility
1635 changes to the current buffer."
1636 :group 'org-link-follow
1637 :type 'boolean)
1639 (defcustom org-open-non-existing-files nil
1640 "Non-nil means `org-open-file' will open non-existing files.
1641 When nil, an error will be generated.
1642 This variable applies only to external applications because they
1643 might choke on non-existing files. If the link is to a file that
1644 will be opened in Emacs, the variable is ignored."
1645 :group 'org-link-follow
1646 :type 'boolean)
1648 (defcustom org-open-directory-means-index-dot-org nil
1649 "Non-nil means a link to a directory really means to index.org.
1650 When nil, following a directory link will run dired or open a finder/explorer
1651 window on that directory."
1652 :group 'org-link-follow
1653 :type 'boolean)
1655 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1656 "Function and arguments to call for following mailto links.
1657 This is a list with the first element being a Lisp function, and the
1658 remaining elements being arguments to the function. In string arguments,
1659 %a will be replaced by the address, and %s will be replaced by the subject
1660 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1661 :group 'org-link-follow
1662 :type '(choice
1663 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1664 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1665 (const :tag "message-mail" (message-mail "%a" "%s"))
1666 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1668 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1669 "Non-nil means ask for confirmation before executing shell links.
1670 Shell links can be dangerous: just think about a link
1672 [[shell:rm -rf ~/*][Google Search]]
1674 This link would show up in your Org-mode document as \"Google Search\",
1675 but really it would remove your entire home directory.
1676 Therefore we advise against setting this variable to nil.
1677 Just change it to `y-or-n-p' if you want to confirm with a
1678 single keystroke rather than having to type \"yes\"."
1679 :group 'org-link-follow
1680 :type '(choice
1681 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1682 (const :tag "with y-or-n (faster)" y-or-n-p)
1683 (const :tag "no confirmation (dangerous)" nil)))
1684 (put 'org-confirm-shell-link-function
1685 'safe-local-variable
1686 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1688 (defcustom org-confirm-shell-link-not-regexp ""
1689 "A regexp to skip confirmation for shell links."
1690 :group 'org-link-follow
1691 :version "24.1"
1692 :type 'regexp)
1694 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1695 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1696 Elisp links can be dangerous: just think about a link
1698 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1700 This link would show up in your Org-mode document as \"Google Search\",
1701 but really it would remove your entire home directory.
1702 Therefore we advise against setting this variable to nil.
1703 Just change it to `y-or-n-p' if you want to confirm with a
1704 single keystroke rather than having to type \"yes\"."
1705 :group 'org-link-follow
1706 :type '(choice
1707 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1708 (const :tag "with y-or-n (faster)" y-or-n-p)
1709 (const :tag "no confirmation (dangerous)" nil)))
1710 (put 'org-confirm-shell-link-function
1711 'safe-local-variable
1712 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1714 (defcustom org-confirm-elisp-link-not-regexp ""
1715 "A regexp to skip confirmation for Elisp links."
1716 :group 'org-link-follow
1717 :version "24.1"
1718 :type 'regexp)
1720 (defconst org-file-apps-defaults-gnu
1721 '((remote . emacs)
1722 (system . mailcap)
1723 (t . mailcap))
1724 "Default file applications on a UNIX or GNU/Linux system.
1725 See `org-file-apps'.")
1727 (defconst org-file-apps-defaults-macosx
1728 '((remote . emacs)
1729 (t . "open %s")
1730 (system . "open %s")
1731 ("ps.gz" . "gv %s")
1732 ("eps.gz" . "gv %s")
1733 ("dvi" . "xdvi %s")
1734 ("fig" . "xfig %s"))
1735 "Default file applications on a MacOS X system.
1736 The system \"open\" is known as a default, but we use X11 applications
1737 for some files for which the OS does not have a good default.
1738 See `org-file-apps'.")
1740 (defconst org-file-apps-defaults-windowsnt
1741 (list
1742 '(remote . emacs)
1743 (cons t
1744 (list (if (featurep 'xemacs)
1745 'mswindows-shell-execute
1746 'w32-shell-execute)
1747 "open" 'file))
1748 (cons 'system
1749 (list (if (featurep 'xemacs)
1750 'mswindows-shell-execute
1751 'w32-shell-execute)
1752 "open" 'file)))
1753 "Default file applications on a Windows NT system.
1754 The system \"open\" is used for most files.
1755 See `org-file-apps'.")
1757 (defcustom org-file-apps
1759 (auto-mode . emacs)
1760 ("\\.mm\\'" . default)
1761 ("\\.x?html?\\'" . default)
1762 ("\\.pdf\\'" . default)
1764 "External applications for opening `file:path' items in a document.
1765 Org-mode uses system defaults for different file types, but
1766 you can use this variable to set the application for a given file
1767 extension. The entries in this list are cons cells where the car identifies
1768 files and the cdr the corresponding command. Possible values for the
1769 file identifier are
1770 \"string\" A string as a file identifier can be interpreted in different
1771 ways, depending on its contents:
1773 - Alphanumeric characters only:
1774 Match links with this file extension.
1775 Example: (\"pdf\" . \"evince %s\")
1776 to open PDFs with evince.
1778 - Regular expression: Match links where the
1779 filename matches the regexp. If you want to
1780 use groups here, use shy groups.
1782 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1783 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1784 to open *.html and *.xhtml with firefox.
1786 - Regular expression which contains (non-shy) groups:
1787 Match links where the whole link, including \"::\", and
1788 anything after that, matches the regexp.
1789 In a custom command string, %1, %2, etc. are replaced with
1790 the parts of the link that were matched by the groups.
1791 For backwards compatibility, if a command string is given
1792 that does not use any of the group matches, this case is
1793 handled identically to the second one (i.e. match against
1794 file name only).
1795 In a custom lisp form, you can access the group matches with
1796 (match-string n link).
1798 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1799 to open [[file:document.pdf::5]] with evince at page 5.
1801 `directory' Matches a directory
1802 `remote' Matches a remote file, accessible through tramp or efs.
1803 Remote files most likely should be visited through Emacs
1804 because external applications cannot handle such paths.
1805 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1806 so all files Emacs knows how to handle. Using this with
1807 command `emacs' will open most files in Emacs. Beware that this
1808 will also open html files inside Emacs, unless you add
1809 (\"html\" . default) to the list as well.
1810 t Default for files not matched by any of the other options.
1811 `system' The system command to open files, like `open' on Windows
1812 and Mac OS X, and mailcap under GNU/Linux. This is the command
1813 that will be selected if you call `C-c C-o' with a double
1814 \\[universal-argument] \\[universal-argument] prefix.
1816 Possible values for the command are:
1817 `emacs' The file will be visited by the current Emacs process.
1818 `default' Use the default application for this file type, which is the
1819 association for t in the list, most likely in the system-specific
1820 part.
1821 This can be used to overrule an unwanted setting in the
1822 system-specific variable.
1823 `system' Use the system command for opening files, like \"open\".
1824 This command is specified by the entry whose car is `system'.
1825 Most likely, the system-specific version of this variable
1826 does define this command, but you can overrule/replace it
1827 here.
1828 string A command to be executed by a shell; %s will be replaced
1829 by the path to the file.
1830 sexp A Lisp form which will be evaluated. The file path will
1831 be available in the Lisp variable `file'.
1832 For more examples, see the system specific constants
1833 `org-file-apps-defaults-macosx'
1834 `org-file-apps-defaults-windowsnt'
1835 `org-file-apps-defaults-gnu'."
1836 :group 'org-link-follow
1837 :type '(repeat
1838 (cons (choice :value ""
1839 (string :tag "Extension")
1840 (const :tag "System command to open files" system)
1841 (const :tag "Default for unrecognized files" t)
1842 (const :tag "Remote file" remote)
1843 (const :tag "Links to a directory" directory)
1844 (const :tag "Any files that have Emacs modes"
1845 auto-mode))
1846 (choice :value ""
1847 (const :tag "Visit with Emacs" emacs)
1848 (const :tag "Use default" default)
1849 (const :tag "Use the system command" system)
1850 (string :tag "Command")
1851 (sexp :tag "Lisp form")))))
1853 (defcustom org-doi-server-url "http://dx.doi.org/"
1854 "The URL of the DOI server."
1855 :type 'string
1856 :version "24.2"
1857 :group 'org-link-follow)
1859 (defgroup org-refile nil
1860 "Options concerning refiling entries in Org-mode."
1861 :tag "Org Refile"
1862 :group 'org)
1864 (defcustom org-directory "~/org"
1865 "Directory with org files.
1866 This is just a default location to look for Org files. There is no need
1867 at all to put your files into this directory. It is only used in the
1868 following situations:
1870 1. When a remember template specifies a target file that is not an
1871 absolute path. The path will then be interpreted relative to
1872 `org-directory'
1873 2. When a remember note is filed away in an interactive way (when exiting the
1874 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1875 with `org-directory' as the default path."
1876 :group 'org-refile
1877 :group 'org-remember
1878 :type 'directory)
1880 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1881 "Default target for storing notes.
1882 Used as a fall back file for org-remember.el and org-capture.el, for
1883 templates that do not specify a target file."
1884 :group 'org-refile
1885 :group 'org-remember
1886 :type '(choice
1887 (const :tag "Default from remember-data-file" nil)
1888 file))
1890 (defcustom org-goto-interface 'outline
1891 "The default interface to be used for `org-goto'.
1892 Allowed values are:
1893 outline The interface shows an outline of the relevant file
1894 and the correct heading is found by moving through
1895 the outline or by searching with incremental search.
1896 outline-path-completion Headlines in the current buffer are offered via
1897 completion. This is the interface also used by
1898 the refile command."
1899 :group 'org-refile
1900 :type '(choice
1901 (const :tag "Outline" outline)
1902 (const :tag "Outline-path-completion" outline-path-completion)))
1904 (defcustom org-goto-max-level 5
1905 "Maximum target level when running `org-goto' with refile interface."
1906 :group 'org-refile
1907 :type 'integer)
1909 (defcustom org-reverse-note-order nil
1910 "Non-nil means store new notes at the beginning of a file or entry.
1911 When nil, new notes will be filed to the end of a file or entry.
1912 This can also be a list with cons cells of regular expressions that
1913 are matched against file names, and values."
1914 :group 'org-remember
1915 :group 'org-refile
1916 :type '(choice
1917 (const :tag "Reverse always" t)
1918 (const :tag "Reverse never" nil)
1919 (repeat :tag "By file name regexp"
1920 (cons regexp boolean))))
1922 (defcustom org-log-refile nil
1923 "Information to record when a task is refiled.
1925 Possible values are:
1927 nil Don't add anything
1928 time Add a time stamp to the task
1929 note Prompt for a note and add it with template `org-log-note-headings'
1931 This option can also be set with on a per-file-basis with
1933 #+STARTUP: nologrefile
1934 #+STARTUP: logrefile
1935 #+STARTUP: lognoterefile
1937 You can have local logging settings for a subtree by setting the LOGGING
1938 property to one or more of these keywords.
1940 When bulk-refiling from the agenda, the value `note' is forbidden and
1941 will temporarily be changed to `time'."
1942 :group 'org-refile
1943 :group 'org-progress
1944 :version "24.1"
1945 :type '(choice
1946 (const :tag "No logging" nil)
1947 (const :tag "Record timestamp" time)
1948 (const :tag "Record timestamp with note." note)))
1950 (defcustom org-refile-targets nil
1951 "Targets for refiling entries with \\[org-refile].
1952 This is a list of cons cells. Each cell contains:
1953 - a specification of the files to be considered, either a list of files,
1954 or a symbol whose function or variable value will be used to retrieve
1955 a file name or a list of file names. If you use `org-agenda-files' for
1956 that, all agenda files will be scanned for targets. Nil means consider
1957 headings in the current buffer.
1958 - A specification of how to find candidate refile targets. This may be
1959 any of:
1960 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1961 This tag has to be present in all target headlines, inheritance will
1962 not be considered.
1963 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1964 todo keyword.
1965 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1966 headlines that are refiling targets.
1967 - a cons cell (:level . N). Any headline of level N is considered a target.
1968 Note that, when `org-odd-levels-only' is set, level corresponds to
1969 order in hierarchy, not to the number of stars.
1970 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1971 Note that, when `org-odd-levels-only' is set, level corresponds to
1972 order in hierarchy, not to the number of stars.
1974 Each element of this list generates a set of possible targets.
1975 The union of these sets is presented (with completion) to
1976 the user by `org-refile'.
1978 You can set the variable `org-refile-target-verify-function' to a function
1979 to verify each headline found by the simple criteria above.
1981 When this variable is nil, all top-level headlines in the current buffer
1982 are used, equivalent to the value `((nil . (:level . 1))'."
1983 :group 'org-refile
1984 :type '(repeat
1985 (cons
1986 (choice :value org-agenda-files
1987 (const :tag "All agenda files" org-agenda-files)
1988 (const :tag "Current buffer" nil)
1989 (function) (variable) (file))
1990 (choice :tag "Identify target headline by"
1991 (cons :tag "Specific tag" (const :value :tag) (string))
1992 (cons :tag "TODO keyword" (const :value :todo) (string))
1993 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1994 (cons :tag "Level number" (const :value :level) (integer))
1995 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1997 (defcustom org-refile-target-verify-function nil
1998 "Function to verify if the headline at point should be a refile target.
1999 The function will be called without arguments, with point at the
2000 beginning of the headline. It should return t and leave point
2001 where it is if the headline is a valid target for refiling.
2003 If the target should not be selected, the function must return nil.
2004 In addition to this, it may move point to a place from where the search
2005 should be continued. For example, the function may decide that the entire
2006 subtree of the current entry should be excluded and move point to the end
2007 of the subtree."
2008 :group 'org-refile
2009 :type 'function)
2011 (defcustom org-refile-use-cache nil
2012 "Non-nil means cache refile targets to speed up the process.
2013 The cache for a particular file will be updated automatically when
2014 the buffer has been killed, or when any of the marker used for flagging
2015 refile targets no longer points at a live buffer.
2016 If you have added new entries to a buffer that might themselves be targets,
2017 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2018 find that easier, `C-u C-u C-u C-c C-w'."
2019 :group 'org-refile
2020 :version "24.1"
2021 :type 'boolean)
2023 (defcustom org-refile-use-outline-path nil
2024 "Non-nil means provide refile targets as paths.
2025 So a level 3 headline will be available as level1/level2/level3.
2027 When the value is `file', also include the file name (without directory)
2028 into the path. In this case, you can also stop the completion after
2029 the file name, to get entries inserted as top level in the file.
2031 When `full-file-path', include the full file path."
2032 :group 'org-refile
2033 :type '(choice
2034 (const :tag "Not" nil)
2035 (const :tag "Yes" t)
2036 (const :tag "Start with file name" file)
2037 (const :tag "Start with full file path" full-file-path)))
2039 (defcustom org-outline-path-complete-in-steps t
2040 "Non-nil means complete the outline path in hierarchical steps.
2041 When Org-mode uses the refile interface to select an outline path
2042 \(see variable `org-refile-use-outline-path'), the completion of
2043 the path can be done is a single go, or if can be done in steps down
2044 the headline hierarchy. Going in steps is probably the best if you
2045 do not use a special completion package like `ido' or `icicles'.
2046 However, when using these packages, going in one step can be very
2047 fast, while still showing the whole path to the entry."
2048 :group 'org-refile
2049 :type 'boolean)
2051 (defcustom org-refile-allow-creating-parent-nodes nil
2052 "Non-nil means allow to create new nodes as refile targets.
2053 New nodes are then created by adding \"/new node name\" to the completion
2054 of an existing node. When the value of this variable is `confirm',
2055 new node creation must be confirmed by the user (recommended)
2056 When nil, the completion must match an existing entry.
2058 Note that, if the new heading is not seen by the criteria
2059 listed in `org-refile-targets', multiple instances of the same
2060 heading would be created by trying again to file under the new
2061 heading."
2062 :group 'org-refile
2063 :type '(choice
2064 (const :tag "Never" nil)
2065 (const :tag "Always" t)
2066 (const :tag "Prompt for confirmation" confirm)))
2068 (defcustom org-refile-active-region-within-subtree nil
2069 "Non-nil means also refile active region within a subtree.
2071 By default `org-refile' doesn't allow refiling regions if they
2072 don't contain a set of subtrees, but it might be convenient to
2073 do so sometimes: in that case, the first line of the region is
2074 converted to a headline before refiling."
2075 :group 'org-refile
2076 :version "24.1"
2077 :type 'boolean)
2079 (defgroup org-todo nil
2080 "Options concerning TODO items in Org-mode."
2081 :tag "Org TODO"
2082 :group 'org)
2084 (defgroup org-progress nil
2085 "Options concerning Progress logging in Org-mode."
2086 :tag "Org Progress"
2087 :group 'org-time)
2089 (defvar org-todo-interpretation-widgets
2090 '((:tag "Sequence (cycling hits every state)" sequence)
2091 (:tag "Type (cycling directly to DONE)" type))
2092 "The available interpretation symbols for customizing `org-todo-keywords'.
2093 Interested libraries should add to this list.")
2095 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2096 "List of TODO entry keyword sequences and their interpretation.
2097 \\<org-mode-map>This is a list of sequences.
2099 Each sequence starts with a symbol, either `sequence' or `type',
2100 indicating if the keywords should be interpreted as a sequence of
2101 action steps, or as different types of TODO items. The first
2102 keywords are states requiring action - these states will select a headline
2103 for inclusion into the global TODO list Org-mode produces. If one of
2104 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2105 signify that no further action is necessary. If \"|\" is not found,
2106 the last keyword is treated as the only DONE state of the sequence.
2108 The command \\[org-todo] cycles an entry through these states, and one
2109 additional state where no keyword is present. For details about this
2110 cycling, see the manual.
2112 TODO keywords and interpretation can also be set on a per-file basis with
2113 the special #+SEQ_TODO and #+TYP_TODO lines.
2115 Each keyword can optionally specify a character for fast state selection
2116 \(in combination with the variable `org-use-fast-todo-selection')
2117 and specifiers for state change logging, using the same syntax that
2118 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2119 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2120 indicates to record a time stamp each time this state is selected.
2122 Each keyword may also specify if a timestamp or a note should be
2123 recorded when entering or leaving the state, by adding additional
2124 characters in the parenthesis after the keyword. This looks like this:
2125 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2126 record only the time of the state change. With X and Y being either
2127 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2128 Y when leaving the state if and only if the *target* state does not
2129 define X. You may omit any of the fast-selection key or X or /Y,
2130 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2132 For backward compatibility, this variable may also be just a list
2133 of keywords. In this case the interpretation (sequence or type) will be
2134 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2135 :group 'org-todo
2136 :group 'org-keywords
2137 :type '(choice
2138 (repeat :tag "Old syntax, just keywords"
2139 (string :tag "Keyword"))
2140 (repeat :tag "New syntax"
2141 (cons
2142 (choice
2143 :tag "Interpretation"
2144 ;;Quick and dirty way to see
2145 ;;`org-todo-interpretations'. This takes the
2146 ;;place of item arguments
2147 :convert-widget
2148 (lambda (widget)
2149 (widget-put widget
2150 :args (mapcar
2151 #'(lambda (x)
2152 (widget-convert
2153 (cons 'const x)))
2154 org-todo-interpretation-widgets))
2155 widget))
2156 (repeat
2157 (string :tag "Keyword"))))))
2159 (defvar org-todo-keywords-1 nil
2160 "All TODO and DONE keywords active in a buffer.")
2161 (make-variable-buffer-local 'org-todo-keywords-1)
2162 (defvar org-todo-keywords-for-agenda nil)
2163 (defvar org-done-keywords-for-agenda nil)
2164 (defvar org-drawers-for-agenda nil)
2165 (defvar org-todo-keyword-alist-for-agenda nil)
2166 (defvar org-tag-alist-for-agenda nil)
2167 (defvar org-agenda-contributing-files nil)
2168 (defvar org-not-done-keywords nil)
2169 (make-variable-buffer-local 'org-not-done-keywords)
2170 (defvar org-done-keywords nil)
2171 (make-variable-buffer-local 'org-done-keywords)
2172 (defvar org-todo-heads nil)
2173 (make-variable-buffer-local 'org-todo-heads)
2174 (defvar org-todo-sets nil)
2175 (make-variable-buffer-local 'org-todo-sets)
2176 (defvar org-todo-log-states nil)
2177 (make-variable-buffer-local 'org-todo-log-states)
2178 (defvar org-todo-kwd-alist nil)
2179 (make-variable-buffer-local 'org-todo-kwd-alist)
2180 (defvar org-todo-key-alist nil)
2181 (make-variable-buffer-local 'org-todo-key-alist)
2182 (defvar org-todo-key-trigger nil)
2183 (make-variable-buffer-local 'org-todo-key-trigger)
2185 (defcustom org-todo-interpretation 'sequence
2186 "Controls how TODO keywords are interpreted.
2187 This variable is in principle obsolete and is only used for
2188 backward compatibility, if the interpretation of todo keywords is
2189 not given already in `org-todo-keywords'. See that variable for
2190 more information."
2191 :group 'org-todo
2192 :group 'org-keywords
2193 :type '(choice (const sequence)
2194 (const type)))
2196 (defcustom org-use-fast-todo-selection t
2197 "Non-nil means use the fast todo selection scheme with C-c C-t.
2198 This variable describes if and under what circumstances the cycling
2199 mechanism for TODO keywords will be replaced by a single-key, direct
2200 selection scheme.
2202 When nil, fast selection is never used.
2204 When the symbol `prefix', it will be used when `org-todo' is called
2205 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2206 `C-u t' in an agenda buffer.
2208 When t, fast selection is used by default. In this case, the prefix
2209 argument forces cycling instead.
2211 In all cases, the special interface is only used if access keys have
2212 actually been assigned by the user, i.e. if keywords in the configuration
2213 are followed by a letter in parenthesis, like TODO(t)."
2214 :group 'org-todo
2215 :type '(choice
2216 (const :tag "Never" nil)
2217 (const :tag "By default" t)
2218 (const :tag "Only with C-u C-c C-t" prefix)))
2220 (defcustom org-provide-todo-statistics t
2221 "Non-nil means update todo statistics after insert and toggle.
2222 ALL-HEADLINES means update todo statistics by including headlines
2223 with no TODO keyword as well, counting them as not done.
2224 A list of TODO keywords means the same, but skip keywords that are
2225 not in this list.
2227 When this is set, todo statistics is updated in the parent of the
2228 current entry each time a todo state is changed."
2229 :group 'org-todo
2230 :type '(choice
2231 (const :tag "Yes, only for TODO entries" t)
2232 (const :tag "Yes, including all entries" 'all-headlines)
2233 (repeat :tag "Yes, for TODOs in this list"
2234 (string :tag "TODO keyword"))
2235 (other :tag "No TODO statistics" nil)))
2237 (defcustom org-hierarchical-todo-statistics t
2238 "Non-nil means TODO statistics covers just direct children.
2239 When nil, all entries in the subtree are considered.
2240 This has only an effect if `org-provide-todo-statistics' is set.
2241 To set this to nil for only a single subtree, use a COOKIE_DATA
2242 property and include the word \"recursive\" into the value."
2243 :group 'org-todo
2244 :type 'boolean)
2246 (defcustom org-after-todo-state-change-hook nil
2247 "Hook which is run after the state of a TODO item was changed.
2248 The new state (a string with a TODO keyword, or nil) is available in the
2249 Lisp variable `org-state'."
2250 :group 'org-todo
2251 :type 'hook)
2253 (defvar org-blocker-hook nil
2254 "Hook for functions that are allowed to block a state change.
2256 Each function gets as its single argument a property list, see
2257 `org-trigger-hook' for more information about this list.
2259 If any of the functions in this hook returns nil, the state change
2260 is blocked.")
2262 (defvar org-trigger-hook nil
2263 "Hook for functions that are triggered by a state change.
2265 Each function gets as its single argument a property list with at least
2266 the following elements:
2268 (:type type-of-change :position pos-at-entry-start
2269 :from old-state :to new-state)
2271 Depending on the type, more properties may be present.
2273 This mechanism is currently implemented for:
2275 TODO state changes
2276 ------------------
2277 :type todo-state-change
2278 :from previous state (keyword as a string), or nil, or a symbol
2279 'todo' or 'done', to indicate the general type of state.
2280 :to new state, like in :from")
2282 (defcustom org-enforce-todo-dependencies nil
2283 "Non-nil means undone TODO entries will block switching the parent to DONE.
2284 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2285 be blocked if any prior sibling is not yet done.
2286 Finally, if the parent is blocked because of ordered siblings of its own,
2287 the child will also be blocked."
2288 :set (lambda (var val)
2289 (set var val)
2290 (if val
2291 (add-hook 'org-blocker-hook
2292 'org-block-todo-from-children-or-siblings-or-parent)
2293 (remove-hook 'org-blocker-hook
2294 'org-block-todo-from-children-or-siblings-or-parent)))
2295 :group 'org-todo
2296 :type 'boolean)
2298 (defcustom org-enforce-todo-checkbox-dependencies nil
2299 "Non-nil means unchecked boxes will block switching the parent to DONE.
2300 When this is nil, checkboxes have no influence on switching TODO states.
2301 When non-nil, you first need to check off all check boxes before the TODO
2302 entry can be switched to DONE.
2303 This variable needs to be set before org.el is loaded, and you need to
2304 restart Emacs after a change to make the change effective. The only way
2305 to change is while Emacs is running is through the customize interface."
2306 :set (lambda (var val)
2307 (set var val)
2308 (if val
2309 (add-hook 'org-blocker-hook
2310 'org-block-todo-from-checkboxes)
2311 (remove-hook 'org-blocker-hook
2312 'org-block-todo-from-checkboxes)))
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-treat-insert-todo-heading-as-state-change nil
2317 "Non-nil means inserting a TODO heading is treated as state change.
2318 So when the command \\[org-insert-todo-heading] is used, state change
2319 logging will apply if appropriate. When nil, the new TODO item will
2320 be inserted directly, and no logging will take place."
2321 :group 'org-todo
2322 :type 'boolean)
2324 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2325 "Non-nil means switching TODO states with S-cursor counts as state change.
2326 This is the default behavior. However, setting this to nil allows a
2327 convenient way to select a TODO state and bypass any logging associated
2328 with that."
2329 :group 'org-todo
2330 :type 'boolean)
2332 (defcustom org-todo-state-tags-triggers nil
2333 "Tag changes that should be triggered by TODO state changes.
2334 This is a list. Each entry is
2336 (state-change (tag . flag) .......)
2338 State-change can be a string with a state, and empty string to indicate the
2339 state that has no TODO keyword, or it can be one of the symbols `todo'
2340 or `done', meaning any not-done or done state, respectively."
2341 :group 'org-todo
2342 :group 'org-tags
2343 :type '(repeat
2344 (cons (choice :tag "When changing to"
2345 (const :tag "Not-done state" todo)
2346 (const :tag "Done state" done)
2347 (string :tag "State"))
2348 (repeat
2349 (cons :tag "Tag action"
2350 (string :tag "Tag")
2351 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2353 (defcustom org-log-done nil
2354 "Information to record when a task moves to the DONE state.
2356 Possible values are:
2358 nil Don't add anything, just change the keyword
2359 time Add a time stamp to the task
2360 note Prompt for a note and add it with template `org-log-note-headings'
2362 This option can also be set with on a per-file-basis with
2364 #+STARTUP: nologdone
2365 #+STARTUP: logdone
2366 #+STARTUP: lognotedone
2368 You can have local logging settings for a subtree by setting the LOGGING
2369 property to one or more of these keywords."
2370 :group 'org-todo
2371 :group 'org-progress
2372 :type '(choice
2373 (const :tag "No logging" nil)
2374 (const :tag "Record CLOSED timestamp" time)
2375 (const :tag "Record CLOSED timestamp with note." note)))
2377 ;; Normalize old uses of org-log-done.
2378 (cond
2379 ((eq org-log-done t) (setq org-log-done 'time))
2380 ((and (listp org-log-done) (memq 'done org-log-done))
2381 (setq org-log-done 'note)))
2383 (defcustom org-log-reschedule nil
2384 "Information to record when the scheduling date of a tasks is modified.
2386 Possible values are:
2388 nil Don't add anything, just change the date
2389 time Add a time stamp to the task
2390 note Prompt for a note and add it with template `org-log-note-headings'
2392 This option can also be set with on a per-file-basis with
2394 #+STARTUP: nologreschedule
2395 #+STARTUP: logreschedule
2396 #+STARTUP: lognotereschedule"
2397 :group 'org-todo
2398 :group 'org-progress
2399 :type '(choice
2400 (const :tag "No logging" nil)
2401 (const :tag "Record timestamp" time)
2402 (const :tag "Record timestamp with note." note)))
2404 (defcustom org-log-redeadline nil
2405 "Information to record when the deadline date of a tasks is modified.
2407 Possible values are:
2409 nil Don't add anything, just change the date
2410 time Add a time stamp to the task
2411 note Prompt for a note and add it with template `org-log-note-headings'
2413 This option can also be set with on a per-file-basis with
2415 #+STARTUP: nologredeadline
2416 #+STARTUP: logredeadline
2417 #+STARTUP: lognoteredeadline
2419 You can have local logging settings for a subtree by setting the LOGGING
2420 property to one or more of these keywords."
2421 :group 'org-todo
2422 :group 'org-progress
2423 :type '(choice
2424 (const :tag "No logging" nil)
2425 (const :tag "Record timestamp" time)
2426 (const :tag "Record timestamp with note." note)))
2428 (defcustom org-log-note-clock-out nil
2429 "Non-nil means record a note when clocking out of an item.
2430 This can also be configured on a per-file basis by adding one of
2431 the following lines anywhere in the buffer:
2433 #+STARTUP: lognoteclock-out
2434 #+STARTUP: nolognoteclock-out"
2435 :group 'org-todo
2436 :group 'org-progress
2437 :type 'boolean)
2439 (defcustom org-log-done-with-time t
2440 "Non-nil means the CLOSED time stamp will contain date and time.
2441 When nil, only the date will be recorded."
2442 :group 'org-progress
2443 :type 'boolean)
2445 (defcustom org-log-note-headings
2446 '((done . "CLOSING NOTE %t")
2447 (state . "State %-12s from %-12S %t")
2448 (note . "Note taken on %t")
2449 (reschedule . "Rescheduled from %S on %t")
2450 (delschedule . "Not scheduled, was %S on %t")
2451 (redeadline . "New deadline from %S on %t")
2452 (deldeadline . "Removed deadline, was %S on %t")
2453 (refile . "Refiled on %t")
2454 (clock-out . ""))
2455 "Headings for notes added to entries.
2456 The value is an alist, with the car being a symbol indicating the note
2457 context, and the cdr is the heading to be used. The heading may also be the
2458 empty string.
2459 %t in the heading will be replaced by a time stamp.
2460 %T will be an active time stamp instead the default inactive one
2461 %d will be replaced by a short-format time stamp.
2462 %D will be replaced by an active short-format time stamp.
2463 %s will be replaced by the new TODO state, in double quotes.
2464 %S will be replaced by the old TODO state, in double quotes.
2465 %u will be replaced by the user name.
2466 %U will be replaced by the full user name.
2468 In fact, it is not a good idea to change the `state' entry, because
2469 agenda log mode depends on the format of these entries."
2470 :group 'org-todo
2471 :group 'org-progress
2472 :type '(list :greedy t
2473 (cons (const :tag "Heading when closing an item" done) string)
2474 (cons (const :tag
2475 "Heading when changing todo state (todo sequence only)"
2476 state) string)
2477 (cons (const :tag "Heading when just taking a note" note) string)
2478 (cons (const :tag "Heading when clocking out" clock-out) string)
2479 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2480 (cons (const :tag "Heading when rescheduling" reschedule) string)
2481 (cons (const :tag "Heading when changing deadline" redeadline) string)
2482 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2483 (cons (const :tag "Heading when refiling" refile) string)))
2485 (unless (assq 'note org-log-note-headings)
2486 (push '(note . "%t") org-log-note-headings))
2488 (defcustom org-log-into-drawer nil
2489 "Non-nil means insert state change notes and time stamps into a drawer.
2490 When nil, state changes notes will be inserted after the headline and
2491 any scheduling and clock lines, but not inside a drawer.
2493 The value of this variable should be the name of the drawer to use.
2494 LOGBOOK is proposed as the default drawer for this purpose, you can
2495 also set this to a string to define the drawer of your choice.
2497 A value of t is also allowed, representing \"LOGBOOK\".
2499 If this variable is set, `org-log-state-notes-insert-after-drawers'
2500 will be ignored.
2502 You can set the property LOG_INTO_DRAWER to overrule this setting for
2503 a subtree."
2504 :group 'org-todo
2505 :group 'org-progress
2506 :type '(choice
2507 (const :tag "Not into a drawer" nil)
2508 (const :tag "LOGBOOK" t)
2509 (string :tag "Other")))
2511 (if (fboundp 'defvaralias)
2512 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2514 (defun org-log-into-drawer ()
2515 "Return the value of `org-log-into-drawer', but let properties overrule.
2516 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2517 used instead of the default value."
2518 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2519 (cond
2520 ((or (not p) (equal p "nil")) org-log-into-drawer)
2521 ((equal p "t") "LOGBOOK")
2522 (t p))))
2524 (defcustom org-log-state-notes-insert-after-drawers nil
2525 "Non-nil means insert state change notes after any drawers in entry.
2526 Only the drawers that *immediately* follow the headline and the
2527 deadline/scheduled line are skipped.
2528 When nil, insert notes right after the heading and perhaps the line
2529 with deadline/scheduling if present.
2531 This variable will have no effect if `org-log-into-drawer' is
2532 set."
2533 :group 'org-todo
2534 :group 'org-progress
2535 :type 'boolean)
2537 (defcustom org-log-states-order-reversed t
2538 "Non-nil means the latest state note will be directly after heading.
2539 When nil, the state change notes will be ordered according to time."
2540 :group 'org-todo
2541 :group 'org-progress
2542 :type 'boolean)
2544 (defcustom org-todo-repeat-to-state nil
2545 "The TODO state to which a repeater should return the repeating task.
2546 By default this is the first task in a TODO sequence, or the previous state
2547 in a TODO_TYP set. But you can specify another task here.
2548 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2549 :group 'org-todo
2550 :version "24.1"
2551 :type '(choice (const :tag "Head of sequence" nil)
2552 (string :tag "Specific state")))
2554 (defcustom org-log-repeat 'time
2555 "Non-nil means record moving through the DONE state when triggering repeat.
2556 An auto-repeating task is immediately switched back to TODO when
2557 marked DONE. If you are not logging state changes (by adding \"@\"
2558 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2559 record a closing note, there will be no record of the task moving
2560 through DONE. This variable forces taking a note anyway.
2562 nil Don't force a record
2563 time Record a time stamp
2564 note Prompt for a note and add it with template `org-log-note-headings'
2566 This option can also be set with on a per-file-basis with
2568 #+STARTUP: nologrepeat
2569 #+STARTUP: logrepeat
2570 #+STARTUP: lognoterepeat
2572 You can have local logging settings for a subtree by setting the LOGGING
2573 property to one or more of these keywords."
2574 :group 'org-todo
2575 :group 'org-progress
2576 :type '(choice
2577 (const :tag "Don't force a record" nil)
2578 (const :tag "Force recording the DONE state" time)
2579 (const :tag "Force recording a note with the DONE state" note)))
2582 (defgroup org-priorities nil
2583 "Priorities in Org-mode."
2584 :tag "Org Priorities"
2585 :group 'org-todo)
2587 (defcustom org-enable-priority-commands t
2588 "Non-nil means priority commands are active.
2589 When nil, these commands will be disabled, so that you never accidentally
2590 set a priority."
2591 :group 'org-priorities
2592 :type 'boolean)
2594 (defcustom org-highest-priority ?A
2595 "The highest priority of TODO items. A character like ?A, ?B etc.
2596 Must have a smaller ASCII number than `org-lowest-priority'."
2597 :group 'org-priorities
2598 :type 'character)
2600 (defcustom org-lowest-priority ?C
2601 "The lowest priority of TODO items. A character like ?A, ?B etc.
2602 Must have a larger ASCII number than `org-highest-priority'."
2603 :group 'org-priorities
2604 :type 'character)
2606 (defcustom org-default-priority ?B
2607 "The default priority of TODO items.
2608 This is the priority an item gets if no explicit priority is given.
2609 When starting to cycle on an empty priority the first step in the cycle
2610 depends on `org-priority-start-cycle-with-default'. The resulting first
2611 step priority must not exceed the range from `org-highest-priority' to
2612 `org-lowest-priority' which means that `org-default-priority' has to be
2613 in this range exclusive or inclusive the range boundaries. Else the
2614 first step refuses to set the default and the second will fall back
2615 to (depending on the command used) the highest or lowest priority."
2616 :group 'org-priorities
2617 :type 'character)
2619 (defcustom org-priority-start-cycle-with-default t
2620 "Non-nil means start with default priority when starting to cycle.
2621 When this is nil, the first step in the cycle will be (depending on the
2622 command used) one higher or lower than the default priority.
2623 See also `org-default-priority'."
2624 :group 'org-priorities
2625 :type 'boolean)
2627 (defcustom org-get-priority-function nil
2628 "Function to extract the priority from a string.
2629 The string is normally the headline. If this is nil Org computes the
2630 priority from the priority cookie like [#A] in the headline. It returns
2631 an integer, increasing by 1000 for each priority level.
2632 The user can set a different function here, which should take a string
2633 as an argument and return the numeric priority."
2634 :group 'org-priorities
2635 :version "24.1"
2636 :type 'function)
2638 (defgroup org-time nil
2639 "Options concerning time stamps and deadlines in Org-mode."
2640 :tag "Org Time"
2641 :group 'org)
2643 (defcustom org-insert-labeled-timestamps-at-point nil
2644 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2645 When nil, these labeled time stamps are forces into the second line of an
2646 entry, just after the headline. When scheduling from the global TODO list,
2647 the time stamp will always be forced into the second line."
2648 :group 'org-time
2649 :type 'boolean)
2651 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2652 "Formats for `format-time-string' which are used for time stamps.
2653 It is not recommended to change this constant.")
2655 (defcustom org-time-stamp-rounding-minutes '(0 5)
2656 "Number of minutes to round time stamps to.
2657 These are two values, the first applies when first creating a time stamp.
2658 The second applies when changing it with the commands `S-up' and `S-down'.
2659 When changing the time stamp, this means that it will change in steps
2660 of N minutes, as given by the second value.
2662 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2663 numbers should be factors of 60, so for example 5, 10, 15.
2665 When this is larger than 1, you can still force an exact time stamp by using
2666 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2667 and by using a prefix arg to `S-up/down' to specify the exact number
2668 of minutes to shift."
2669 :group 'org-time
2670 :get #'(lambda (var) ; Make sure both elements are there
2671 (if (integerp (default-value var))
2672 (list (default-value var) 5)
2673 (default-value var)))
2674 :type '(list
2675 (integer :tag "when inserting times")
2676 (integer :tag "when modifying times")))
2678 ;; Normalize old customizations of this variable.
2679 (when (integerp org-time-stamp-rounding-minutes)
2680 (setq org-time-stamp-rounding-minutes
2681 (list org-time-stamp-rounding-minutes
2682 org-time-stamp-rounding-minutes)))
2684 (defcustom org-display-custom-times nil
2685 "Non-nil means overlay custom formats over all time stamps.
2686 The formats are defined through the variable `org-time-stamp-custom-formats'.
2687 To turn this on on a per-file basis, insert anywhere in the file:
2688 #+STARTUP: customtime"
2689 :group 'org-time
2690 :set 'set-default
2691 :type 'sexp)
2692 (make-variable-buffer-local 'org-display-custom-times)
2694 (defcustom org-time-stamp-custom-formats
2695 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2696 "Custom formats for time stamps. See `format-time-string' for the syntax.
2697 These are overlaid over the default ISO format if the variable
2698 `org-display-custom-times' is set. Time like %H:%M should be at the
2699 end of the second format. The custom formats are also honored by export
2700 commands, if custom time display is turned on at the time of export."
2701 :group 'org-time
2702 :type 'sexp)
2704 (defun org-time-stamp-format (&optional long inactive)
2705 "Get the right format for a time string."
2706 (let ((f (if long (cdr org-time-stamp-formats)
2707 (car org-time-stamp-formats))))
2708 (if inactive
2709 (concat "[" (substring f 1 -1) "]")
2710 f)))
2712 (defcustom org-time-clocksum-format "%d:%02d"
2713 "The format string used when creating CLOCKSUM lines.
2714 This is also used when org-mode generates a time duration."
2715 :group 'org-time
2716 :type 'string)
2718 (defcustom org-time-clocksum-use-fractional nil
2719 "If non-nil, \\[org-clock-display] uses fractional times.
2720 org-mode generates a time duration."
2721 :group 'org-time
2722 :type 'boolean)
2724 (defcustom org-time-clocksum-fractional-format "%.2f"
2725 "The format string used when creating CLOCKSUM lines, or when
2726 org-mode generates a time duration."
2727 :group 'org-time
2728 :type 'string)
2730 (defcustom org-deadline-warning-days 14
2731 "No. of days before expiration during which a deadline becomes active.
2732 This variable governs the display in sparse trees and in the agenda.
2733 When 0 or negative, it means use this number (the absolute value of it)
2734 even if a deadline has a different individual lead time specified.
2736 Custom commands can set this variable in the options section."
2737 :group 'org-time
2738 :group 'org-agenda-daily/weekly
2739 :type 'integer)
2741 (defcustom org-read-date-prefer-future t
2742 "Non-nil means assume future for incomplete date input from user.
2743 This affects the following situations:
2744 1. The user gives a month but not a year.
2745 For example, if it is April and you enter \"feb 2\", this will be read
2746 as Feb 2, *next* year. \"May 5\", however, will be this year.
2747 2. The user gives a day, but no month.
2748 For example, if today is the 15th, and you enter \"3\", Org-mode will
2749 read this as the third of *next* month. However, if you enter \"17\",
2750 it will be considered as *this* month.
2752 If you set this variable to the symbol `time', then also the following
2753 will work:
2755 3. If the user gives a time, but no day. If the time is before now,
2756 to will be interpreted as tomorrow.
2758 Currently none of this works for ISO week specifications.
2760 When this option is nil, the current day, month and year will always be
2761 used as defaults.
2763 See also `org-agenda-jump-prefer-future'."
2764 :group 'org-time
2765 :type '(choice
2766 (const :tag "Never" nil)
2767 (const :tag "Check month and day" t)
2768 (const :tag "Check month, day, and time" time)))
2770 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2771 "Should the agenda jump command prefer the future for incomplete dates?
2772 The default is to do the same as configured in `org-read-date-prefer-future'.
2773 But you can also set a deviating value here.
2774 This may t or nil, or the symbol `org-read-date-prefer-future'."
2775 :group 'org-agenda
2776 :group 'org-time
2777 :version "24.1"
2778 :type '(choice
2779 (const :tag "Use org-read-date-prefer-future"
2780 org-read-date-prefer-future)
2781 (const :tag "Never" nil)
2782 (const :tag "Always" t)))
2784 (defcustom org-read-date-force-compatible-dates t
2785 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2787 Depending on the system Emacs is running on, certain dates cannot
2788 be represented with the type used internally to represent time.
2789 Dates between 1970-1-1 and 2038-1-1 can always be represented
2790 correctly. Some systems allow for earlier dates, some for later,
2791 some for both. One way to find out it to insert any date into an
2792 Org buffer, putting the cursor on the year and hitting S-up and
2793 S-down to test the range.
2795 When this variable is set to t, the date/time prompt will not let
2796 you specify dates outside the 1970-2037 range, so it is certain that
2797 these dates will work in whatever version of Emacs you are
2798 running, and also that you can move a file from one Emacs implementation
2799 to another. WHenever Org is forcing the year for you, it will display
2800 a message and beep.
2802 When this variable is nil, Org will check if the date is
2803 representable in the specific Emacs implementation you are using.
2804 If not, it will force a year, usually the current year, and beep
2805 to remind you. Currently this setting is not recommended because
2806 the likelihood that you will open your Org files in an Emacs that
2807 has limited date range is not negligible.
2809 A workaround for this problem is to use diary sexp dates for time
2810 stamps outside of this range."
2811 :group 'org-time
2812 :version "24.1"
2813 :type 'boolean)
2815 (defcustom org-read-date-display-live t
2816 "Non-nil means display current interpretation of date prompt live.
2817 This display will be in an overlay, in the minibuffer."
2818 :group 'org-time
2819 :type 'boolean)
2821 (defcustom org-read-date-popup-calendar t
2822 "Non-nil means pop up a calendar when prompting for a date.
2823 In the calendar, the date can be selected with mouse-1. However, the
2824 minibuffer will also be active, and you can simply enter the date as well.
2825 When nil, only the minibuffer will be available."
2826 :group 'org-time
2827 :type 'boolean)
2828 (if (fboundp 'defvaralias)
2829 (defvaralias 'org-popup-calendar-for-date-prompt
2830 'org-read-date-popup-calendar))
2832 (defcustom org-read-date-minibuffer-setup-hook nil
2833 "Hook to be used to set up keys for the date/time interface.
2834 Add key definitions to `minibuffer-local-map', which will be a temporary
2835 copy."
2836 :group 'org-time
2837 :type 'hook)
2839 (defcustom org-extend-today-until 0
2840 "The hour when your day really ends. Must be an integer.
2841 This has influence for the following applications:
2842 - When switching the agenda to \"today\". It it is still earlier than
2843 the time given here, the day recognized as TODAY is actually yesterday.
2844 - When a date is read from the user and it is still before the time given
2845 here, the current date and time will be assumed to be yesterday, 23:59.
2846 Also, timestamps inserted in remember templates follow this rule.
2848 IMPORTANT: This is a feature whose implementation is and likely will
2849 remain incomplete. Really, it is only here because past midnight seems to
2850 be the favorite working time of John Wiegley :-)"
2851 :group 'org-time
2852 :type 'integer)
2854 (defcustom org-use-effective-time nil
2855 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2856 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2857 \"effective time\" of any timestamps between midnight and 8am will be
2858 23:59 of the previous day."
2859 :group 'org-time
2860 :version "24.1"
2861 :type 'boolean)
2863 (defcustom org-edit-timestamp-down-means-later nil
2864 "Non-nil means S-down will increase the time in a time stamp.
2865 When nil, S-up will increase."
2866 :group 'org-time
2867 :type 'boolean)
2869 (defcustom org-calendar-follow-timestamp-change t
2870 "Non-nil means make the calendar window follow timestamp changes.
2871 When a timestamp is modified and the calendar window is visible, it will be
2872 moved to the new date."
2873 :group 'org-time
2874 :type 'boolean)
2876 (defgroup org-tags nil
2877 "Options concerning tags in Org-mode."
2878 :tag "Org Tags"
2879 :group 'org)
2881 (defcustom org-tag-alist nil
2882 "List of tags allowed in Org-mode files.
2883 When this list is nil, Org-mode will base TAG input on what is already in the
2884 buffer.
2885 The value of this variable is an alist, the car of each entry must be a
2886 keyword as a string, the cdr may be a character that is used to select
2887 that tag through the fast-tag-selection interface.
2888 See the manual for details."
2889 :group 'org-tags
2890 :type '(repeat
2891 (choice
2892 (cons (string :tag "Tag name")
2893 (character :tag "Access char"))
2894 (list :tag "Start radio group"
2895 (const :startgroup)
2896 (option (string :tag "Group description")))
2897 (list :tag "End radio group"
2898 (const :endgroup)
2899 (option (string :tag "Group description")))
2900 (const :tag "New line" (:newline)))))
2902 (defcustom org-tag-persistent-alist nil
2903 "List of tags that will always appear in all Org-mode files.
2904 This is in addition to any in buffer settings or customizations
2905 of `org-tag-alist'.
2906 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2907 The value of this variable is an alist, the car of each entry must be a
2908 keyword as a string, the cdr may be a character that is used to select
2909 that tag through the fast-tag-selection interface.
2910 See the manual for details.
2911 To disable these tags on a per-file basis, insert anywhere in the file:
2912 #+STARTUP: noptag"
2913 :group 'org-tags
2914 :type '(repeat
2915 (choice
2916 (cons (string :tag "Tag name")
2917 (character :tag "Access char"))
2918 (const :tag "Start radio group" (:startgroup))
2919 (const :tag "End radio group" (:endgroup))
2920 (const :tag "New line" (:newline)))))
2922 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2923 "If non-nil, always offer completion for all tags of all agenda files.
2924 Instead of customizing this variable directly, you might want to
2925 set it locally for capture buffers, because there no list of
2926 tags in that file can be created dynamically (there are none).
2928 (add-hook 'org-capture-mode-hook
2929 (lambda ()
2930 (set (make-local-variable
2931 'org-complete-tags-always-offer-all-agenda-tags)
2932 t)))"
2933 :group 'org-tags
2934 :version "24.1"
2935 :type 'boolean)
2937 (defvar org-file-tags nil
2938 "List of tags that can be inherited by all entries in the file.
2939 The tags will be inherited if the variable `org-use-tag-inheritance'
2940 says they should be.
2941 This variable is populated from #+FILETAGS lines.")
2943 (defcustom org-use-fast-tag-selection 'auto
2944 "Non-nil means use fast tag selection scheme.
2945 This is a special interface to select and deselect tags with single keys.
2946 When nil, fast selection is never used.
2947 When the symbol `auto', fast selection is used if and only if selection
2948 characters for tags have been configured, either through the variable
2949 `org-tag-alist' or through a #+TAGS line in the buffer.
2950 When t, fast selection is always used and selection keys are assigned
2951 automatically if necessary."
2952 :group 'org-tags
2953 :type '(choice
2954 (const :tag "Always" t)
2955 (const :tag "Never" nil)
2956 (const :tag "When selection characters are configured" 'auto)))
2958 (defcustom org-fast-tag-selection-single-key nil
2959 "Non-nil means fast tag selection exits after first change.
2960 When nil, you have to press RET to exit it.
2961 During fast tag selection, you can toggle this flag with `C-c'.
2962 This variable can also have the value `expert'. In this case, the window
2963 displaying the tags menu is not even shown, until you press C-c again."
2964 :group 'org-tags
2965 :type '(choice
2966 (const :tag "No" nil)
2967 (const :tag "Yes" t)
2968 (const :tag "Expert" expert)))
2970 (defvar org-fast-tag-selection-include-todo nil
2971 "Non-nil means fast tags selection interface will also offer TODO states.
2972 This is an undocumented feature, you should not rely on it.")
2974 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2975 "The column to which tags should be indented in a headline.
2976 If this number is positive, it specifies the column. If it is negative,
2977 it means that the tags should be flushright to that column. For example,
2978 -80 works well for a normal 80 character screen.
2979 When 0, place tags directly after headline text, with only one space in
2980 between."
2981 :group 'org-tags
2982 :type 'integer)
2984 (defcustom org-auto-align-tags t
2985 "Non-nil keeps tags aligned when modifying headlines.
2986 Some operations (i.e. demoting) change the length of a headline and
2987 therefore shift the tags around. With this option turned on, after
2988 each such operation the tags are again aligned to `org-tags-column'."
2989 :group 'org-tags
2990 :type 'boolean)
2992 (defcustom org-use-tag-inheritance t
2993 "Non-nil means tags in levels apply also for sublevels.
2994 When nil, only the tags directly given in a specific line apply there.
2995 This may also be a list of tags that should be inherited, or a regexp that
2996 matches tags that should be inherited. Additional control is possible
2997 with the variable `org-tags-exclude-from-inheritance' which gives an
2998 explicit list of tags to be excluded from inheritance., even if the value of
2999 `org-use-tag-inheritance' would select it for inheritance.
3001 If this option is t, a match early-on in a tree can lead to a large
3002 number of matches in the subtree when constructing the agenda or creating
3003 a sparse tree. If you only want to see the first match in a tree during
3004 a search, check out the variable `org-tags-match-list-sublevels'."
3005 :group 'org-tags
3006 :type '(choice
3007 (const :tag "Not" nil)
3008 (const :tag "Always" t)
3009 (repeat :tag "Specific tags" (string :tag "Tag"))
3010 (regexp :tag "Tags matched by regexp")))
3012 (defcustom org-tags-exclude-from-inheritance nil
3013 "List of tags that should never be inherited.
3014 This is a way to exclude a few tags from inheritance. For way to do
3015 the opposite, to actively allow inheritance for selected tags,
3016 see the variable `org-use-tag-inheritance'."
3017 :group 'org-tags
3018 :type '(repeat (string :tag "Tag")))
3020 (defun org-tag-inherit-p (tag)
3021 "Check if TAG is one that should be inherited."
3022 (cond
3023 ((member tag org-tags-exclude-from-inheritance) nil)
3024 ((eq org-use-tag-inheritance t) t)
3025 ((not org-use-tag-inheritance) nil)
3026 ((stringp org-use-tag-inheritance)
3027 (string-match org-use-tag-inheritance tag))
3028 ((listp org-use-tag-inheritance)
3029 (member tag org-use-tag-inheritance))
3030 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3032 (defcustom org-tags-match-list-sublevels t
3033 "Non-nil means list also sublevels of headlines matching a search.
3034 This variable applies to tags/property searches, and also to stuck
3035 projects because this search is based on a tags match as well.
3037 When set to the symbol `indented', sublevels are indented with
3038 leading dots.
3040 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3041 the sublevels of a headline matching a tag search often also match
3042 the same search. Listing all of them can create very long lists.
3043 Setting this variable to nil causes subtrees of a match to be skipped.
3045 This variable is semi-obsolete and probably should always be true. It
3046 is better to limit inheritance to certain tags using the variables
3047 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3048 :group 'org-tags
3049 :type '(choice
3050 (const :tag "No, don't list them" nil)
3051 (const :tag "Yes, do list them" t)
3052 (const :tag "List them, indented with leading dots" indented)))
3054 (defcustom org-tags-sort-function nil
3055 "When set, tags are sorted using this function as a comparator."
3056 :group 'org-tags
3057 :type '(choice
3058 (const :tag "No sorting" nil)
3059 (const :tag "Alphabetical" string<)
3060 (const :tag "Reverse alphabetical" string>)
3061 (function :tag "Custom function" nil)))
3063 (defvar org-tags-history nil
3064 "History of minibuffer reads for tags.")
3065 (defvar org-last-tags-completion-table nil
3066 "The last used completion table for tags.")
3067 (defvar org-after-tags-change-hook nil
3068 "Hook that is run after the tags in a line have changed.")
3070 (defgroup org-properties nil
3071 "Options concerning properties in Org-mode."
3072 :tag "Org Properties"
3073 :group 'org)
3075 (defcustom org-property-format "%-10s %s"
3076 "How property key/value pairs should be formatted by `indent-line'.
3077 When `indent-line' hits a property definition, it will format the line
3078 according to this format, mainly to make sure that the values are
3079 lined-up with respect to each other."
3080 :group 'org-properties
3081 :type 'string)
3083 (defcustom org-properties-postprocess-alist nil
3084 "Alist of properties and functions to adjust inserted values.
3085 Elements of this alist must be of the form
3087 ([string] [function])
3089 where [string] must be a property name and [function] must be a
3090 lambda expression: this lambda expression must take one argument,
3091 the value to adjust, and return the new value as a string.
3093 For example, this element will allow the property \"Remaining\"
3094 to be updated wrt the relation between the \"Effort\" property
3095 and the clock summary:
3097 ((\"Remaining\" (lambda(value)
3098 (let ((clocksum (org-clock-sum-current-item))
3099 (effort (org-duration-string-to-minutes
3100 (org-entry-get (point) \"Effort\"))))
3101 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3102 :group 'org-properties
3103 :version "24.1"
3104 :type '(alist :key-type (string :tag "Property")
3105 :value-type (function :tag "Function")))
3107 (defcustom org-use-property-inheritance nil
3108 "Non-nil means properties apply also for sublevels.
3110 This setting is chiefly used during property searches. Turning it on can
3111 cause significant overhead when doing a search, which is why it is not
3112 on by default.
3114 When nil, only the properties directly given in the current entry count.
3115 When t, every property is inherited. The value may also be a list of
3116 properties that should have inheritance, or a regular expression matching
3117 properties that should be inherited.
3119 However, note that some special properties use inheritance under special
3120 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3121 and the properties ending in \"_ALL\" when they are used as descriptor
3122 for valid values of a property.
3124 Note for programmers:
3125 When querying an entry with `org-entry-get', you can control if inheritance
3126 should be used. By default, `org-entry-get' looks only at the local
3127 properties. You can request inheritance by setting the inherit argument
3128 to t (to force inheritance) or to `selective' (to respect the setting
3129 in this variable)."
3130 :group 'org-properties
3131 :type '(choice
3132 (const :tag "Not" nil)
3133 (const :tag "Always" t)
3134 (repeat :tag "Specific properties" (string :tag "Property"))
3135 (regexp :tag "Properties matched by regexp")))
3137 (defun org-property-inherit-p (property)
3138 "Check if PROPERTY is one that should be inherited."
3139 (cond
3140 ((eq org-use-property-inheritance t) t)
3141 ((not org-use-property-inheritance) nil)
3142 ((stringp org-use-property-inheritance)
3143 (string-match org-use-property-inheritance property))
3144 ((listp org-use-property-inheritance)
3145 (member property org-use-property-inheritance))
3146 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3148 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3149 "The default column format, if no other format has been defined.
3150 This variable can be set on the per-file basis by inserting a line
3152 #+COLUMNS: %25ITEM ....."
3153 :group 'org-properties
3154 :type 'string)
3156 (defcustom org-columns-ellipses ".."
3157 "The ellipses to be used when a field in column view is truncated.
3158 When this is the empty string, as many characters as possible are shown,
3159 but then there will be no visual indication that the field has been truncated.
3160 When this is a string of length N, the last N characters of a truncated
3161 field are replaced by this string. If the column is narrower than the
3162 ellipses string, only part of the ellipses string will be shown."
3163 :group 'org-properties
3164 :type 'string)
3166 (defcustom org-columns-modify-value-for-display-function nil
3167 "Function that modifies values for display in column view.
3168 For example, it can be used to cut out a certain part from a time stamp.
3169 The function must take 2 arguments:
3171 column-title The title of the column (*not* the property name)
3172 value The value that should be modified.
3174 The function should return the value that should be displayed,
3175 or nil if the normal value should be used."
3176 :group 'org-properties
3177 :type 'function)
3179 (defcustom org-effort-property "Effort"
3180 "The property that is being used to keep track of effort estimates.
3181 Effort estimates given in this property need to have the format H:MM."
3182 :group 'org-properties
3183 :group 'org-progress
3184 :type '(string :tag "Property"))
3186 (defconst org-global-properties-fixed
3187 '(("VISIBILITY_ALL" . "folded children content all")
3188 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3189 "List of property/value pairs that can be inherited by any entry.
3191 These are fixed values, for the preset properties. The user variable
3192 that can be used to add to this list is `org-global-properties'.
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. If the value represents
3196 multiple items like an \"_ALL\" property, separate the items by
3197 spaces.")
3199 (defcustom org-global-properties nil
3200 "List of property/value pairs that can be inherited by any entry.
3202 This list will be combined with the constant `org-global-properties-fixed'.
3204 The entries in this list are cons cells where the car is a property
3205 name and cdr is a string with the value.
3207 You can set buffer-local values for the same purpose in the variable
3208 `org-file-properties' this by adding lines like
3210 #+PROPERTY: NAME VALUE"
3211 :group 'org-properties
3212 :type '(repeat
3213 (cons (string :tag "Property")
3214 (string :tag "Value"))))
3216 (defvar org-file-properties nil
3217 "List of property/value pairs that can be inherited by any entry.
3218 Valid for the current buffer.
3219 This variable is populated from #+PROPERTY lines.")
3220 (make-variable-buffer-local 'org-file-properties)
3222 (defgroup org-agenda nil
3223 "Options concerning agenda views in Org-mode."
3224 :tag "Org Agenda"
3225 :group 'org)
3227 (defvar org-category nil
3228 "Variable used by org files to set a category for agenda display.
3229 Such files should use a file variable to set it, for example
3231 # -*- mode: org; org-category: \"ELisp\"
3233 or contain a special line
3235 #+CATEGORY: ELisp
3237 If the file does not specify a category, then file's base name
3238 is used instead.")
3239 (make-variable-buffer-local 'org-category)
3240 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3242 (defcustom org-agenda-files nil
3243 "The files to be used for agenda display.
3244 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3245 \\[org-remove-file]. You can also use customize to edit the list.
3247 If an entry is a directory, all files in that directory that are matched by
3248 `org-agenda-file-regexp' will be part of the file list.
3250 If the value of the variable is not a list but a single file name, then
3251 the list of agenda files is actually stored and maintained in that file, one
3252 agenda file per line. In this file paths can be given relative to
3253 `org-directory'. Tilde expansion and environment variable substitution
3254 are also made."
3255 :group 'org-agenda
3256 :type '(choice
3257 (repeat :tag "List of files and directories" file)
3258 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3260 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3261 "Regular expression to match files for `org-agenda-files'.
3262 If any element in the list in that variable contains a directory instead
3263 of a normal file, all files in that directory that are matched by this
3264 regular expression will be included."
3265 :group 'org-agenda
3266 :type 'regexp)
3268 (defcustom org-agenda-text-search-extra-files nil
3269 "List of extra files to be searched by text search commands.
3270 These files will be search in addition to the agenda files by the
3271 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3272 Note that these files will only be searched for text search commands,
3273 not for the other agenda views like todo lists, tag searches or the weekly
3274 agenda. This variable is intended to list notes and possibly archive files
3275 that should also be searched by these two commands.
3276 In fact, if the first element in the list is the symbol `agenda-archives',
3277 than all archive files of all agenda files will be added to the search
3278 scope."
3279 :group 'org-agenda
3280 :type '(set :greedy t
3281 (const :tag "Agenda Archives" agenda-archives)
3282 (repeat :inline t (file))))
3284 (if (fboundp 'defvaralias)
3285 (defvaralias 'org-agenda-multi-occur-extra-files
3286 'org-agenda-text-search-extra-files))
3288 (defcustom org-agenda-skip-unavailable-files nil
3289 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3290 A nil value means to remove them, after a query, from the list."
3291 :group 'org-agenda
3292 :type 'boolean)
3294 (defcustom org-calendar-to-agenda-key [?c]
3295 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3296 The command `org-calendar-goto-agenda' will be bound to this key. The
3297 default is the character `c' because then `c' can be used to switch back and
3298 forth between agenda and calendar."
3299 :group 'org-agenda
3300 :type 'sexp)
3302 (defcustom org-calendar-agenda-action-key [?k]
3303 "The key to be installed in `calendar-mode-map' for agenda-action.
3304 The command `org-agenda-action' will be bound to this key. The
3305 default is the character `k' because we use the same key in the agenda."
3306 :group 'org-agenda
3307 :type 'sexp)
3309 (defcustom org-calendar-insert-diary-entry-key [?i]
3310 "The key to be installed in `calendar-mode-map' for adding diary entries.
3311 This option is irrelevant until `org-agenda-diary-file' has been configured
3312 to point to an Org-mode file. When that is the case, the command
3313 `org-agenda-diary-entry' will be bound to the key given here, by default
3314 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3315 if you want to continue doing this, you need to change this to a different
3316 key."
3317 :group 'org-agenda
3318 :type 'sexp)
3320 (defcustom org-agenda-diary-file 'diary-file
3321 "File to which to add new entries with the `i' key in agenda and calendar.
3322 When this is the symbol `diary-file', the functionality in the Emacs
3323 calendar will be used to add entries to the `diary-file'. But when this
3324 points to a file, `org-agenda-diary-entry' will be used instead."
3325 :group 'org-agenda
3326 :type '(choice
3327 (const :tag "The standard Emacs diary file" diary-file)
3328 (file :tag "Special Org file diary entries")))
3330 (eval-after-load "calendar"
3331 '(progn
3332 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3333 'org-calendar-goto-agenda)
3334 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3335 'org-agenda-action)
3336 (add-hook 'calendar-mode-hook
3337 (lambda ()
3338 (unless (eq org-agenda-diary-file 'diary-file)
3339 (define-key calendar-mode-map
3340 org-calendar-insert-diary-entry-key
3341 'org-agenda-diary-entry))))))
3343 (defgroup org-latex nil
3344 "Options for embedding LaTeX code into Org-mode."
3345 :tag "Org LaTeX"
3346 :group 'org)
3348 (defcustom org-format-latex-options
3349 '(:foreground default :background default :scale 1.0
3350 :html-foreground "Black" :html-background "Transparent"
3351 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3352 "Options for creating images from LaTeX fragments.
3353 This is a property list with the following properties:
3354 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3355 `default' means use the foreground of the default face.
3356 :background the background color, or \"Transparent\".
3357 `default' means use the background of the default face.
3358 :scale a scaling factor for the size of the images, to get more pixels
3359 :html-foreground, :html-background, :html-scale
3360 the same numbers for HTML export.
3361 :matchers a list indicating which matchers should be used to
3362 find LaTeX fragments. Valid members of this list are:
3363 \"begin\" find environments
3364 \"$1\" find single characters surrounded by $.$
3365 \"$\" find math expressions surrounded by $...$
3366 \"$$\" find math expressions surrounded by $$....$$
3367 \"\\(\" find math expressions surrounded by \\(...\\)
3368 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3369 :group 'org-latex
3370 :type 'plist)
3372 (defcustom org-format-latex-signal-error t
3373 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3374 When nil, just push out a message."
3375 :group 'org-latex
3376 :version "24.1"
3377 :type 'boolean)
3379 (defcustom org-latex-to-mathml-jar-file nil
3380 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3381 Use this to specify additional executable file say a jar file.
3383 When using MathToWeb as the converter, specify the full-path to
3384 your mathtoweb.jar file."
3385 :group 'org-latex
3386 :version "24.1"
3387 :type '(choice
3388 (const :tag "None" nil)
3389 (file :tag "JAR file" :must-match t)))
3391 (defcustom org-latex-to-mathml-convert-command nil
3392 "Command to convert LaTeX fragments to MathML.
3393 Replace format-specifiers in the command as noted below and use
3394 `shell-command' to convert LaTeX to MathML.
3395 %j: Executable file in fully expanded form as specified by
3396 `org-latex-to-mathml-jar-file'.
3397 %I: Input LaTeX file in fully expanded form
3398 %o: Output MathML file
3399 This command is used by `org-create-math-formula'.
3401 When using MathToWeb as the converter, set this to
3402 \"java -jar %j -unicode -force -df %o %I\"."
3403 :group 'org-latex
3404 :version "24.1"
3405 :type '(choice
3406 (const :tag "None" nil)
3407 (string :tag "\nShell command")))
3409 (defcustom org-latex-create-formula-image-program 'dvipng
3410 "Program to convert LaTeX fragments with.
3412 dvipng Process the LaTeX fragments to dvi file, then convert
3413 dvi files to png files using dvipng.
3414 This will also include processing of non-math environments.
3415 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3416 to convert pdf files to png files"
3417 :group 'org-latex
3418 :version "24.1"
3419 :type '(choice
3420 (const :tag "dvipng" dvipng)
3421 (const :tag "imagemagick" imagemagick)))
3423 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3424 "Path to store latex preview images. A relative path here creates many
3425 directories relative to the processed org files paths. An absolute path
3426 puts all preview images at the same place."
3427 :group 'org-latex
3428 :version "24.2"
3429 :type 'string)
3431 (defun org-format-latex-mathml-available-p ()
3432 "Return t if `org-latex-to-mathml-convert-command' is usable."
3433 (save-match-data
3434 (when (and (boundp 'org-latex-to-mathml-convert-command)
3435 org-latex-to-mathml-convert-command)
3436 (let ((executable (car (split-string
3437 org-latex-to-mathml-convert-command))))
3438 (when (executable-find executable)
3439 (if (string-match
3440 "%j" org-latex-to-mathml-convert-command)
3441 (file-readable-p org-latex-to-mathml-jar-file)
3442 t))))))
3444 (defcustom org-format-latex-header "\\documentclass{article}
3445 \\usepackage[usenames]{color}
3446 \\usepackage{amsmath}
3447 \\usepackage[mathscr]{eucal}
3448 \\pagestyle{empty} % do not remove
3449 \[PACKAGES]
3450 \[DEFAULT-PACKAGES]
3451 % The settings below are copied from fullpage.sty
3452 \\setlength{\\textwidth}{\\paperwidth}
3453 \\addtolength{\\textwidth}{-3cm}
3454 \\setlength{\\oddsidemargin}{1.5cm}
3455 \\addtolength{\\oddsidemargin}{-2.54cm}
3456 \\setlength{\\evensidemargin}{\\oddsidemargin}
3457 \\setlength{\\textheight}{\\paperheight}
3458 \\addtolength{\\textheight}{-\\headheight}
3459 \\addtolength{\\textheight}{-\\headsep}
3460 \\addtolength{\\textheight}{-\\footskip}
3461 \\addtolength{\\textheight}{-3cm}
3462 \\setlength{\\topmargin}{1.5cm}
3463 \\addtolength{\\topmargin}{-2.54cm}"
3464 "The document header used for processing LaTeX fragments.
3465 It is imperative that this header make sure that no page number
3466 appears on the page. The package defined in the variables
3467 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3468 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3469 will be appended."
3470 :group 'org-latex
3471 :type 'string)
3473 (defvar org-format-latex-header-extra nil)
3475 (defun org-set-packages-alist (var val)
3476 "Set the packages alist and make sure it has 3 elements per entry."
3477 (set var (mapcar (lambda (x)
3478 (if (and (consp x) (= (length x) 2))
3479 (list (car x) (nth 1 x) t)
3481 val)))
3483 (defun org-get-packages-alist (var)
3485 "Get the packages alist and make sure it has 3 elements per entry."
3486 (mapcar (lambda (x)
3487 (if (and (consp x) (= (length x) 2))
3488 (list (car x) (nth 1 x) t)
3490 (default-value var)))
3492 ;; The following variables are defined here because is it also used
3493 ;; when formatting latex fragments. Originally it was part of the
3494 ;; LaTeX exporter, which is why the name includes "export".
3495 (defcustom org-export-latex-default-packages-alist
3496 '(("AUTO" "inputenc" t)
3497 ("T1" "fontenc" t)
3498 ("" "fixltx2e" nil)
3499 ("" "graphicx" t)
3500 ("" "longtable" nil)
3501 ("" "float" nil)
3502 ("" "wrapfig" nil)
3503 ("" "soul" t)
3504 ("" "textcomp" t)
3505 ("" "marvosym" t)
3506 ("" "wasysym" t)
3507 ("" "latexsym" t)
3508 ("" "amssymb" t)
3509 ("" "hyperref" nil)
3510 "\\tolerance=1000"
3512 "Alist of default packages to be inserted in the header.
3513 Change this only if one of the packages here causes an incompatibility
3514 with another package you are using.
3515 The packages in this list are needed by one part or another of Org-mode
3516 to function properly.
3518 - inputenc, fontenc: for basic font and character selection
3519 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3520 for interpreting the entities in `org-entities'. You can skip some of these
3521 packages if you don't use any of the symbols in it.
3522 - graphicx: for including images
3523 - float, wrapfig: for figure placement
3524 - longtable: for long tables
3525 - hyperref: for cross references
3527 Therefore you should not modify this variable unless you know what you
3528 are doing. The one reason to change it anyway is that you might be loading
3529 some other package that conflicts with one of the default packages.
3530 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3531 If SNIPPET-FLAG is t, the package also needs to be included when
3532 compiling LaTeX snippets into images for inclusion into HTML."
3533 :group 'org-export-latex
3534 :set 'org-set-packages-alist
3535 :get 'org-get-packages-alist
3536 :version "24.1"
3537 :type '(repeat
3538 (choice
3539 (list :tag "options/package pair"
3540 (string :tag "options")
3541 (string :tag "package")
3542 (boolean :tag "Snippet"))
3543 (string :tag "A line of LaTeX"))))
3545 (defcustom org-export-latex-packages-alist nil
3546 "Alist of packages to be inserted in every LaTeX header.
3547 These will be inserted after `org-export-latex-default-packages-alist'.
3548 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3549 SNIPPET-FLAG, when t, indicates that this package is also needed when
3550 turning LaTeX snippets into images for inclusion into HTML.
3551 Make sure that you only list packages here which:
3552 - you want in every file
3553 - do not conflict with the default packages in
3554 `org-export-latex-default-packages-alist'
3555 - do not conflict with the setup in `org-format-latex-header'."
3556 :group 'org-export-latex
3557 :set 'org-set-packages-alist
3558 :get 'org-get-packages-alist
3559 :type '(repeat
3560 (choice
3561 (list :tag "options/package pair"
3562 (string :tag "options")
3563 (string :tag "package")
3564 (boolean :tag "Snippet"))
3565 (string :tag "A line of LaTeX"))))
3568 (defgroup org-appearance nil
3569 "Settings for Org-mode appearance."
3570 :tag "Org Appearance"
3571 :group 'org)
3573 (defcustom org-level-color-stars-only nil
3574 "Non-nil means fontify only the stars in each headline.
3575 When nil, the entire headline is fontified.
3576 Changing it requires restart of `font-lock-mode' to become effective
3577 also in regions already fontified."
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-hide-leading-stars nil
3582 "Non-nil means hide the first N-1 stars in a headline.
3583 This works by using the face `org-hide' for these stars. This
3584 face is white for a light background, and black for a dark
3585 background. You may have to customize the face `org-hide' to
3586 make this work.
3587 Changing it requires restart of `font-lock-mode' to become effective
3588 also in regions already fontified.
3589 You may also set this on a per-file basis by adding one of the following
3590 lines to the buffer:
3592 #+STARTUP: hidestars
3593 #+STARTUP: showstars"
3594 :group 'org-appearance
3595 :type 'boolean)
3597 (defcustom org-hidden-keywords nil
3598 "List of symbols corresponding to keywords to be hidden the org buffer.
3599 For example, a value '(title) for this list will make the document's title
3600 appear in the buffer without the initial #+TITLE: keyword."
3601 :group 'org-appearance
3602 :version "24.1"
3603 :type '(set (const :tag "#+AUTHOR" author)
3604 (const :tag "#+DATE" date)
3605 (const :tag "#+EMAIL" email)
3606 (const :tag "#+TITLE" title)))
3608 (defcustom org-fontify-done-headline nil
3609 "Non-nil means change the face of a headline if it is marked DONE.
3610 Normally, only the TODO/DONE keyword indicates the state of a headline.
3611 When this is non-nil, the headline after the keyword is set to the
3612 `org-headline-done' as an additional indication."
3613 :group 'org-appearance
3614 :type 'boolean)
3616 (defcustom org-fontify-emphasized-text t
3617 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3618 Changing this variable requires a restart of Emacs to take effect."
3619 :group 'org-appearance
3620 :type 'boolean)
3622 (defcustom org-fontify-whole-heading-line nil
3623 "Non-nil means fontify the whole line for headings.
3624 This is useful when setting a background color for the
3625 org-level-* faces."
3626 :group 'org-appearance
3627 :type 'boolean)
3629 (defcustom org-highlight-latex-fragments-and-specials nil
3630 "Non-nil means fontify what is treated specially by the exporters."
3631 :group 'org-appearance
3632 :type 'boolean)
3634 (defcustom org-hide-emphasis-markers nil
3635 "Non-nil mean font-lock should hide the emphasis marker characters."
3636 :group 'org-appearance
3637 :type 'boolean)
3639 (defcustom org-pretty-entities nil
3640 "Non-nil means show entities as UTF8 characters.
3641 When nil, the \\name form remains in the buffer."
3642 :group 'org-appearance
3643 :version "24.1"
3644 :type 'boolean)
3646 (defcustom org-pretty-entities-include-sub-superscripts t
3647 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3648 :group 'org-appearance
3649 :version "24.1"
3650 :type 'boolean)
3652 (defvar org-emph-re nil
3653 "Regular expression for matching emphasis.
3654 After a match, the match groups contain these elements:
3655 0 The match of the full regular expression, including the characters
3656 before and after the proper match
3657 1 The character before the proper match, or empty at beginning of line
3658 2 The proper match, including the leading and trailing markers
3659 3 The leading marker like * or /, indicating the type of highlighting
3660 4 The text between the emphasis markers, not including the markers
3661 5 The character after the match, empty at the end of a line")
3662 (defvar org-verbatim-re nil
3663 "Regular expression for matching verbatim text.")
3664 (defvar org-emphasis-regexp-components) ; defined just below
3665 (defvar org-emphasis-alist) ; defined just below
3666 (defun org-set-emph-re (var val)
3667 "Set variable and compute the emphasis regular expression."
3668 (set var val)
3669 (when (and (boundp 'org-emphasis-alist)
3670 (boundp 'org-emphasis-regexp-components)
3671 org-emphasis-alist org-emphasis-regexp-components)
3672 (let* ((e org-emphasis-regexp-components)
3673 (pre (car e))
3674 (post (nth 1 e))
3675 (border (nth 2 e))
3676 (body (nth 3 e))
3677 (nl (nth 4 e))
3678 (body1 (concat body "*?"))
3679 (markers (mapconcat 'car org-emphasis-alist ""))
3680 (vmarkers (mapconcat
3681 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3682 org-emphasis-alist "")))
3683 ;; make sure special characters appear at the right position in the class
3684 (if (string-match "\\^" markers)
3685 (setq markers (concat (replace-match "" t t markers) "^")))
3686 (if (string-match "-" markers)
3687 (setq markers (concat (replace-match "" t t markers) "-")))
3688 (if (string-match "\\^" vmarkers)
3689 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3690 (if (string-match "-" vmarkers)
3691 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3692 (if (> nl 0)
3693 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3694 (int-to-string nl) "\\}")))
3695 ;; Make the regexp
3696 (setq org-emph-re
3697 (concat "\\([" pre "]\\|^\\)"
3698 "\\("
3699 "\\([" markers "]\\)"
3700 "\\("
3701 "[^" border "]\\|"
3702 "[^" border "]"
3703 body1
3704 "[^" border "]"
3705 "\\)"
3706 "\\3\\)"
3707 "\\([" post "]\\|$\\)"))
3708 (setq org-verbatim-re
3709 (concat "\\([" pre "]\\|^\\)"
3710 "\\("
3711 "\\([" vmarkers "]\\)"
3712 "\\("
3713 "[^" border "]\\|"
3714 "[^" border "]"
3715 body1
3716 "[^" border "]"
3717 "\\)"
3718 "\\3\\)"
3719 "\\([" post "]\\|$\\)")))))
3721 (defcustom org-emphasis-regexp-components
3722 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3723 "Components used to build the regular expression for emphasis.
3724 This is a list with five entries. Terminology: In an emphasis string
3725 like \" *strong word* \", we call the initial space PREMATCH, the final
3726 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3727 and \"trong wor\" is the body. The different components in this variable
3728 specify what is allowed/forbidden in each part:
3730 pre Chars allowed as prematch. Beginning of line will be allowed too.
3731 post Chars allowed as postmatch. End of line will be allowed too.
3732 border The chars *forbidden* as border characters.
3733 body-regexp A regexp like \".\" to match a body character. Don't use
3734 non-shy groups here, and don't allow newline here.
3735 newline The maximum number of newlines allowed in an emphasis exp.
3737 Use customize to modify this, or restart Emacs after changing it."
3738 :group 'org-appearance
3739 :set 'org-set-emph-re
3740 :type '(list
3741 (sexp :tag "Allowed chars in pre ")
3742 (sexp :tag "Allowed chars in post ")
3743 (sexp :tag "Forbidden chars in border ")
3744 (sexp :tag "Regexp for body ")
3745 (integer :tag "number of newlines allowed")
3746 (option (boolean :tag "Please ignore this button"))))
3748 (defcustom org-emphasis-alist
3749 `(("*" bold "<b>" "</b>")
3750 ("/" italic "<i>" "</i>")
3751 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3752 ("=" org-code "<code>" "</code>" verbatim)
3753 ("~" org-verbatim "<code>" "</code>" verbatim)
3754 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3755 "<del>" "</del>")
3757 "Special syntax for emphasized text.
3758 Text starting and ending with a special character will be emphasized, for
3759 example *bold*, _underlined_ and /italic/. This variable sets the marker
3760 characters, the face to be used by font-lock for highlighting in Org-mode
3761 Emacs buffers, and the HTML tags to be used for this.
3762 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3763 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3764 Use customize to modify this, or restart Emacs after changing it."
3765 :group 'org-appearance
3766 :set 'org-set-emph-re
3767 :type '(repeat
3768 (list
3769 (string :tag "Marker character")
3770 (choice
3771 (face :tag "Font-lock-face")
3772 (plist :tag "Face property list"))
3773 (string :tag "HTML start tag")
3774 (string :tag "HTML end tag")
3775 (option (const verbatim)))))
3777 (defvar org-protecting-blocks
3778 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3779 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3780 This is needed for font-lock setup.")
3782 ;;; Miscellaneous options
3784 (defgroup org-completion nil
3785 "Completion in Org-mode."
3786 :tag "Org Completion"
3787 :group 'org)
3789 (defcustom org-completion-use-ido nil
3790 "Non-nil means use ido completion wherever possible.
3791 Note that `ido-mode' must be active for this variable to be relevant.
3792 If you decide to turn this variable on, you might well want to turn off
3793 `org-outline-path-complete-in-steps'.
3794 See also `org-completion-use-iswitchb'."
3795 :group 'org-completion
3796 :type 'boolean)
3798 (defcustom org-completion-use-iswitchb nil
3799 "Non-nil means use iswitchb completion wherever possible.
3800 Note that `iswitchb-mode' must be active for this variable to be relevant.
3801 If you decide to turn this variable on, you might well want to turn off
3802 `org-outline-path-complete-in-steps'.
3803 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3804 :group 'org-completion
3805 :type 'boolean)
3807 (defcustom org-completion-fallback-command 'hippie-expand
3808 "The expansion command called by \\[pcomplete] in normal context.
3809 Normal means, no org-mode-specific context."
3810 :group 'org-completion
3811 :type 'function)
3813 ;;; Functions and variables from their packages
3814 ;; Declared here to avoid compiler warnings
3816 ;; XEmacs only
3817 (defvar outline-mode-menu-heading)
3818 (defvar outline-mode-menu-show)
3819 (defvar outline-mode-menu-hide)
3820 (defvar zmacs-regions) ; XEmacs regions
3822 ;; Emacs only
3823 (defvar mark-active)
3825 ;; Various packages
3826 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3827 (declare-function calendar-forward-day "cal-move" (arg))
3828 (declare-function calendar-goto-date "cal-move" (date))
3829 (declare-function calendar-goto-today "cal-move" ())
3830 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3831 (defvar calc-embedded-close-formula)
3832 (defvar calc-embedded-open-formula)
3833 (declare-function cdlatex-tab "ext:cdlatex" ())
3834 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3835 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3836 (defvar font-lock-unfontify-region-function)
3837 (declare-function iswitchb-read-buffer "iswitchb"
3838 (prompt &optional default require-match start matches-set))
3839 (defvar iswitchb-temp-buflist)
3840 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3841 (defvar org-agenda-tags-todo-honor-ignore-options)
3842 (declare-function org-agenda-skip "org-agenda" ())
3843 (declare-function
3844 org-agenda-format-item "org-agenda"
3845 (extra txt &optional category tags dotime noprefix remove-re habitp))
3846 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3847 (declare-function org-agenda-change-all-lines "org-agenda"
3848 (newhead hdmarker &optional fixface just-this))
3849 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3850 (declare-function org-agenda-maybe-redo "org-agenda" ())
3851 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3852 (beg end))
3853 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3854 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3855 "org-agenda" (&optional end))
3856 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3857 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3858 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3859 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3860 (declare-function org-indent-mode "org-indent" (&optional arg))
3861 (declare-function parse-time-string "parse-time" (string))
3862 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3863 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3864 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3865 (defvar remember-data-file)
3866 (defvar texmathp-why)
3867 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3868 (declare-function table--at-cell-p "table" (position &optional object at-column))
3870 (defvar w3m-current-url)
3871 (defvar w3m-current-title)
3873 (defvar org-latex-regexps)
3875 ;;; Autoload and prepare some org modules
3877 ;; Some table stuff that needs to be defined here, because it is used
3878 ;; by the functions setting up org-mode or checking for table context.
3880 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3881 "Detect an org-type or table-type table.")
3882 (defconst org-table-line-regexp "^[ \t]*|"
3883 "Detect an org-type table line.")
3884 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3885 "Detect an org-type table line.")
3886 (defconst org-table-hline-regexp "^[ \t]*|-"
3887 "Detect an org-type table hline.")
3888 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3889 "Detect a table-type table hline.")
3890 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3891 "Detect the first line outside a table when searching from within it.
3892 This works for both table types.")
3894 ;; Autoload the functions in org-table.el that are needed by functions here.
3896 (eval-and-compile
3897 (org-autoload "org-table"
3898 '(org-table-align org-table-begin org-table-blank-field
3899 org-table-convert org-table-convert-region org-table-copy-down
3900 org-table-copy-region org-table-create
3901 org-table-create-or-convert-from-region
3902 org-table-create-with-table.el org-table-current-dline
3903 org-table-cut-region org-table-delete-column org-table-edit-field
3904 org-table-edit-formulas org-table-end org-table-eval-formula
3905 org-table-export org-table-field-info
3906 org-table-get-stored-formulas org-table-goto-column
3907 org-table-hline-and-move org-table-import org-table-insert-column
3908 org-table-insert-hline org-table-insert-row org-table-iterate
3909 org-table-justify-field-maybe org-table-kill-row
3910 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3911 org-table-move-column org-table-move-column-left
3912 org-table-move-column-right org-table-move-row
3913 org-table-move-row-down org-table-move-row-up
3914 org-table-next-field org-table-next-row org-table-paste-rectangle
3915 org-table-previous-field org-table-recalculate
3916 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3917 org-table-toggle-coordinate-overlays
3918 org-table-toggle-formula-debugger org-table-wrap-region
3919 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3920 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3921 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3923 (defun org-at-table-p (&optional table-type)
3924 "Return t if the cursor is inside an org-type table.
3925 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3926 (if org-enable-table-editor
3927 (save-excursion
3928 (beginning-of-line 1)
3929 (looking-at (if table-type org-table-any-line-regexp
3930 org-table-line-regexp)))
3931 nil))
3932 (defsubst org-table-p () (org-at-table-p))
3934 (defun org-at-table.el-p ()
3935 "Return t if and only if we are at a table.el table."
3936 (and (org-at-table-p 'any)
3937 (save-excursion
3938 (goto-char (org-table-begin 'any))
3939 (looking-at org-table1-hline-regexp))))
3940 (defun org-table-recognize-table.el ()
3941 "If there is a table.el table nearby, recognize it and move into it."
3942 (if org-table-tab-recognizes-table.el
3943 (if (org-at-table.el-p)
3944 (progn
3945 (beginning-of-line 1)
3946 (if (looking-at org-table-dataline-regexp)
3948 (if (looking-at org-table1-hline-regexp)
3949 (progn
3950 (beginning-of-line 2)
3951 (if (looking-at org-table-any-border-regexp)
3952 (beginning-of-line -1)))))
3953 (if (re-search-forward "|" (org-table-end t) t)
3954 (progn
3955 (require 'table)
3956 (if (table--at-cell-p (point))
3958 (message "recognizing table.el table...")
3959 (table-recognize-table)
3960 (message "recognizing table.el table...done")))
3961 (error "This should not happen"))
3963 nil)
3964 nil))
3966 (defun org-at-table-hline-p ()
3967 "Return t if the cursor is inside a hline in a table."
3968 (if org-enable-table-editor
3969 (save-excursion
3970 (beginning-of-line 1)
3971 (looking-at org-table-hline-regexp))
3972 nil))
3974 (defvar org-table-clean-did-remove-column nil)
3976 (defun org-table-map-tables (function &optional quietly)
3977 "Apply FUNCTION to the start of all tables in the buffer."
3978 (save-excursion
3979 (save-restriction
3980 (widen)
3981 (goto-char (point-min))
3982 (while (re-search-forward org-table-any-line-regexp nil t)
3983 (unless quietly
3984 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3985 (beginning-of-line 1)
3986 (when (and (looking-at org-table-line-regexp)
3987 ;; Exclude tables in src/example/verbatim/clocktable blocks
3988 (not (org-in-block-p '("src" "example"))))
3989 (save-excursion (funcall function))
3990 (or (looking-at org-table-line-regexp)
3991 (forward-char 1)))
3992 (re-search-forward org-table-any-border-regexp nil 1))))
3993 (unless quietly (message "Mapping tables: done")))
3995 ;; Declare and autoload functions from org-exp.el & Co
3997 (declare-function org-default-export-plist "org-exp")
3998 (declare-function org-infile-export-plist "org-exp")
3999 (declare-function org-get-current-options "org-exp")
4000 (eval-and-compile
4001 (org-autoload "org-exp"
4002 '(org-export org-export-visible
4003 org-insert-export-options-template
4004 org-table-clean-before-export))
4005 (org-autoload "org-ascii"
4006 '(org-export-as-ascii org-export-ascii-preprocess
4007 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4008 org-export-region-as-ascii))
4009 (org-autoload "org-latex"
4010 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4011 org-replace-region-by-latex org-export-region-as-latex
4012 org-export-as-latex org-export-as-pdf
4013 org-export-as-pdf-and-open))
4014 (org-autoload "org-html"
4015 '(org-export-as-html-and-open
4016 org-export-as-html-batch org-export-as-html-to-buffer
4017 org-replace-region-by-html org-export-region-as-html
4018 org-export-as-html))
4019 (org-autoload "org-docbook"
4020 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4021 org-replace-region-by-docbook org-export-region-as-docbook
4022 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4023 org-export-as-docbook))
4024 (org-autoload "org-icalendar"
4025 '(org-export-icalendar-this-file
4026 org-export-icalendar-all-agenda-files
4027 org-export-icalendar-combine-agenda-files))
4028 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4029 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4031 ;; Declare and autoload functions from org-agenda.el
4033 (eval-and-compile
4034 (org-autoload "org-agenda"
4035 '(org-agenda org-agenda-list org-search-view
4036 org-todo-list org-tags-view org-agenda-list-stuck-projects
4037 org-diary org-agenda-to-appt
4038 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4040 ;; Autoload org-remember
4042 (eval-and-compile
4043 (org-autoload "org-remember"
4044 '(org-remember-insinuate org-remember-annotation
4045 org-remember-apply-template org-remember org-remember-handler)))
4047 (eval-and-compile
4048 (org-autoload "org-capture"
4049 '(org-capture org-capture-insert-template-here
4050 org-capture-import-remember-templates)))
4052 ;; Autoload org-clock.el
4054 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4055 (beg end))
4056 (declare-function org-clock-update-mode-line "org-clock" ())
4057 (declare-function org-resolve-clocks "org-clock"
4058 (&optional also-non-dangling-p prompt last-valid))
4059 (defvar org-clock-start-time)
4060 (defvar org-clock-marker (make-marker)
4061 "Marker recording the last clock-in.")
4062 (defvar org-clock-hd-marker (make-marker)
4063 "Marker recording the last clock-in, but the headline position.")
4064 (defvar org-clock-heading ""
4065 "The heading of the current clock entry.")
4066 (defun org-clock-is-active ()
4067 "Return non-nil if clock is currently running.
4068 The return value is actually the clock marker."
4069 (marker-buffer org-clock-marker))
4071 (eval-and-compile
4072 (org-autoload
4073 "org-clock"
4074 '(org-clock-in org-clock-out org-clock-cancel
4075 org-clock-goto org-clock-sum org-clock-display
4076 org-clock-remove-overlays org-clock-report
4077 org-clocktable-shift org-dblock-write:clocktable
4078 org-get-clocktable org-resolve-clocks)))
4080 (defun org-clock-update-time-maybe ()
4081 "If this is a CLOCK line, update it and return t.
4082 Otherwise, return nil."
4083 (interactive)
4084 (save-excursion
4085 (beginning-of-line 1)
4086 (skip-chars-forward " \t")
4087 (when (looking-at org-clock-string)
4088 (let ((re (concat "[ \t]*" org-clock-string
4089 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4090 "\\([ \t]*=>.*\\)?\\)?"))
4091 ts te h m s neg)
4092 (cond
4093 ((not (looking-at re))
4094 nil)
4095 ((not (match-end 2))
4096 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4097 (> org-clock-marker (point))
4098 (<= org-clock-marker (point-at-eol)))
4099 ;; The clock is running here
4100 (setq org-clock-start-time
4101 (apply 'encode-time
4102 (org-parse-time-string (match-string 1))))
4103 (org-clock-update-mode-line)))
4105 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4106 (end-of-line 1)
4107 (setq ts (match-string 1)
4108 te (match-string 3))
4109 (setq s (- (org-float-time
4110 (apply 'encode-time (org-parse-time-string te)))
4111 (org-float-time
4112 (apply 'encode-time (org-parse-time-string ts))))
4113 neg (< s 0)
4114 s (abs s)
4115 h (floor (/ s 3600))
4116 s (- s (* 3600 h))
4117 m (floor (/ s 60))
4118 s (- s (* 60 s)))
4119 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4120 t))))))
4122 (defun org-check-running-clock ()
4123 "Check if the current buffer contains the running clock.
4124 If yes, offer to stop it and to save the buffer with the changes."
4125 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4126 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4127 (buffer-name))))
4128 (org-clock-out)
4129 (when (y-or-n-p "Save changed buffer?")
4130 (save-buffer))))
4132 (defun org-clocktable-try-shift (dir n)
4133 "Check if this line starts a clock table, if yes, shift the time block."
4134 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4135 (org-clocktable-shift dir n)))
4137 ;; Autoload org-timer.el
4139 (eval-and-compile
4140 (org-autoload
4141 "org-timer"
4142 '(org-timer-start org-timer org-timer-item
4143 org-timer-change-times-in-region
4144 org-timer-set-timer
4145 org-timer-reset-timers
4146 org-timer-show-remaining-time)))
4148 ;; Autoload org-feed.el
4150 (eval-and-compile
4151 (org-autoload
4152 "org-feed"
4153 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4156 ;; Autoload org-indent.el
4158 ;; Define the variable already here, to make sure we have it.
4159 (defvar org-indent-mode nil
4160 "Non-nil if Org-Indent mode is enabled.
4161 Use the command `org-indent-mode' to change this variable.")
4163 (eval-and-compile
4164 (org-autoload
4165 "org-indent"
4166 '(org-indent-mode)))
4168 ;; Autoload org-mobile.el
4170 (eval-and-compile
4171 (org-autoload
4172 "org-mobile"
4173 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4175 ;; Autoload archiving code
4176 ;; The stuff that is needed for cycling and tags has to be defined here.
4178 (defgroup org-archive nil
4179 "Options concerning archiving in Org-mode."
4180 :tag "Org Archive"
4181 :group 'org-structure)
4183 (defcustom org-archive-location "%s_archive::"
4184 "The location where subtrees should be archived.
4186 The value of this variable is a string, consisting of two parts,
4187 separated by a double-colon. The first part is a filename and
4188 the second part is a headline.
4190 When the filename is omitted, archiving happens in the same file.
4191 %s in the filename will be replaced by the current file
4192 name (without the directory part). Archiving to a different file
4193 is useful to keep archived entries from contributing to the
4194 Org-mode Agenda.
4196 The archived entries will be filed as subtrees of the specified
4197 headline. When the headline is omitted, the subtrees are simply
4198 filed away at the end of the file, as top-level entries. Also in
4199 the heading you can use %s to represent the file name, this can be
4200 useful when using the same archive for a number of different files.
4202 Here are a few examples:
4203 \"%s_archive::\"
4204 If the current file is Projects.org, archive in file
4205 Projects.org_archive, as top-level trees. This is the default.
4207 \"::* Archived Tasks\"
4208 Archive in the current file, under the top-level headline
4209 \"* Archived Tasks\".
4211 \"~/org/archive.org::\"
4212 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4214 \"~/org/archive.org::* From %s\"
4215 Archive in file ~/org/archive.org (absolute path), under headlines
4216 \"From FILENAME\" where file name is the current file name.
4218 \"~/org/datetree.org::datetree/* Finished Tasks\"
4219 The \"datetree/\" string is special, signifying to archive
4220 items to the datetree. Items are placed in either the CLOSED
4221 date of the item, or the current date if there is no CLOSED date.
4222 The heading will be a subentry to the current date. There doesn't
4223 need to be a heading, but there always needs to be a slash after
4224 datetree. For example, to store archived items directly in the
4225 datetree, use \"~/org/datetree.org::datetree/\".
4227 \"basement::** Finished Tasks\"
4228 Archive in file ./basement (relative path), as level 3 trees
4229 below the level 2 heading \"** Finished Tasks\".
4231 You may set this option on a per-file basis by adding to the buffer a
4232 line like
4234 #+ARCHIVE: basement::** Finished Tasks
4236 You may also define it locally for a subtree by setting an ARCHIVE property
4237 in the entry. If such a property is found in an entry, or anywhere up
4238 the hierarchy, it will be used."
4239 :group 'org-archive
4240 :type 'string)
4242 (defcustom org-archive-tag "ARCHIVE"
4243 "The tag that marks a subtree as archived.
4244 An archived subtree does not open during visibility cycling, and does
4245 not contribute to the agenda listings.
4246 After changing this, font-lock must be restarted in the relevant buffers to
4247 get the proper fontification."
4248 :group 'org-archive
4249 :group 'org-keywords
4250 :type 'string)
4252 (defcustom org-agenda-skip-archived-trees t
4253 "Non-nil means the agenda will skip any items located in archived trees.
4254 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4255 variable is no longer recommended, you should leave it at the value t.
4256 Instead, use the key `v' to cycle the archives-mode in the agenda."
4257 :group 'org-archive
4258 :group 'org-agenda-skip
4259 :type 'boolean)
4261 (defcustom org-columns-skip-archived-trees t
4262 "Non-nil means ignore archived trees when creating column view."
4263 :group 'org-archive
4264 :group 'org-properties
4265 :type 'boolean)
4267 (defcustom org-cycle-open-archived-trees nil
4268 "Non-nil means `org-cycle' will open archived trees.
4269 An archived tree is a tree marked with the tag ARCHIVE.
4270 When nil, archived trees will stay folded. You can still open them with
4271 normal outline commands like `show-all', but not with the cycling commands."
4272 :group 'org-archive
4273 :group 'org-cycle
4274 :type 'boolean)
4276 (defcustom org-sparse-tree-open-archived-trees nil
4277 "Non-nil means sparse tree construction shows matches in archived trees.
4278 When nil, matches in these trees are highlighted, but the trees are kept in
4279 collapsed state."
4280 :group 'org-archive
4281 :group 'org-sparse-trees
4282 :type 'boolean)
4284 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4285 "The default date type when building a sparse tree.
4286 When this is nil, a date is a scheduled or a deadline timestamp.
4287 Otherwise, these types are allowed:
4289 all: all timestamps
4290 active: only active timestamps (<...>)
4291 inactive: only inactive timestamps (<...)
4292 scheduled: only scheduled timestamps
4293 deadline: only deadline timestamps"
4294 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4295 (const :tag "All timestamps" all)
4296 (const :tag "Only active timestamps" active)
4297 (const :tag "Only inactive timestamps" inactive)
4298 (const :tag "Only scheduled timestamps" scheduled)
4299 (const :tag "Only deadline timestamps" deadline))
4300 :group 'org-sparse-trees
4301 :version "24.2")
4303 (defun org-cycle-hide-archived-subtrees (state)
4304 "Re-hide all archived subtrees after a visibility state change."
4305 (when (and (not org-cycle-open-archived-trees)
4306 (not (memq state '(overview folded))))
4307 (save-excursion
4308 (let* ((globalp (memq state '(contents all)))
4309 (beg (if globalp (point-min) (point)))
4310 (end (if globalp (point-max) (org-end-of-subtree t))))
4311 (org-hide-archived-subtrees beg end)
4312 (goto-char beg)
4313 (if (looking-at (concat ".*:" org-archive-tag ":"))
4314 (message "%s" (substitute-command-keys
4315 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4317 (defun org-force-cycle-archived ()
4318 "Cycle subtree even if it is archived."
4319 (interactive)
4320 (setq this-command 'org-cycle)
4321 (let ((org-cycle-open-archived-trees t))
4322 (call-interactively 'org-cycle)))
4324 (defun org-hide-archived-subtrees (beg end)
4325 "Re-hide all archived subtrees after a visibility state change."
4326 (save-excursion
4327 (let* ((re (concat ":" org-archive-tag ":")))
4328 (goto-char beg)
4329 (while (re-search-forward re end t)
4330 (when (org-at-heading-p)
4331 (org-flag-subtree t)
4332 (org-end-of-subtree t))))))
4334 (declare-function outline-end-of-heading "outline" ())
4335 (declare-function outline-flag-region "outline" (from to flag))
4336 (defun org-flag-subtree (flag)
4337 (save-excursion
4338 (org-back-to-heading t)
4339 (outline-end-of-heading)
4340 (outline-flag-region (point)
4341 (progn (org-end-of-subtree t) (point))
4342 flag)))
4344 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4346 (eval-and-compile
4347 (org-autoload "org-archive"
4348 '(org-add-archive-files org-archive-subtree
4349 org-archive-to-archive-sibling org-toggle-archive-tag
4350 org-archive-subtree-default
4351 org-archive-subtree-default-with-confirmation)))
4353 ;; Autoload Column View Code
4355 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4356 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4357 (declare-function org-columns-compute "org-colview" (property))
4359 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4360 '(org-columns-number-to-string org-columns-get-format-and-top-level
4361 org-columns-compute org-agenda-columns org-columns-remove-overlays
4362 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4364 ;; Autoload ID code
4366 (declare-function org-id-store-link "org-id")
4367 (declare-function org-id-locations-load "org-id")
4368 (declare-function org-id-locations-save "org-id")
4369 (defvar org-id-track-globally)
4370 (org-autoload "org-id"
4371 '(org-id-get-create org-id-new org-id-copy org-id-get
4372 org-id-get-with-outline-path-completion
4373 org-id-get-with-outline-drilling org-id-store-link
4374 org-id-goto org-id-find org-id-store-link))
4376 ;; Autoload Plotting Code
4378 (org-autoload "org-plot"
4379 '(org-plot/gnuplot))
4381 ;;; Variables for pre-computed regular expressions, all buffer local
4383 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4384 "Matches first line of a hidden block.")
4385 (make-variable-buffer-local 'org-drawer-regexp)
4386 (defvar org-todo-regexp nil
4387 "Matches any of the TODO state keywords.")
4388 (make-variable-buffer-local 'org-todo-regexp)
4389 (defvar org-not-done-regexp nil
4390 "Matches any of the TODO state keywords except the last one.")
4391 (make-variable-buffer-local 'org-not-done-regexp)
4392 (defvar org-not-done-heading-regexp nil
4393 "Matches a TODO headline that is not done.")
4394 (make-variable-buffer-local 'org-not-done-regexp)
4395 (defvar org-todo-line-regexp nil
4396 "Matches a headline and puts TODO state into group 2 if present.")
4397 (make-variable-buffer-local 'org-todo-line-regexp)
4398 (defvar org-complex-heading-regexp nil
4399 "Matches a headline and puts everything into groups:
4400 group 1: the stars
4401 group 2: The todo keyword, maybe
4402 group 3: Priority cookie
4403 group 4: True headline
4404 group 5: Tags")
4405 (make-variable-buffer-local 'org-complex-heading-regexp)
4406 (defvar org-complex-heading-regexp-format nil
4407 "Printf format to make regexp to match an exact headline.
4408 This regexp will match the headline of any node which has the
4409 exact headline text that is put into the format, but may have any
4410 TODO state, priority and tags.")
4411 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4412 (defvar org-todo-line-tags-regexp nil
4413 "Matches a headline and puts TODO state into group 2 if present.
4414 Also put tags into group 4 if tags are present.")
4415 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4416 (defvar org-ds-keyword-length 12
4417 "Maximum length of the Deadline and SCHEDULED keywords.")
4418 (make-variable-buffer-local 'org-ds-keyword-length)
4419 (defvar org-deadline-regexp nil
4420 "Matches the DEADLINE keyword.")
4421 (make-variable-buffer-local 'org-deadline-regexp)
4422 (defvar org-deadline-time-regexp nil
4423 "Matches the DEADLINE keyword together with a time stamp.")
4424 (make-variable-buffer-local 'org-deadline-time-regexp)
4425 (defvar org-deadline-line-regexp nil
4426 "Matches the DEADLINE keyword and the rest of the line.")
4427 (make-variable-buffer-local 'org-deadline-line-regexp)
4428 (defvar org-scheduled-regexp nil
4429 "Matches the SCHEDULED keyword.")
4430 (make-variable-buffer-local 'org-scheduled-regexp)
4431 (defvar org-scheduled-time-regexp nil
4432 "Matches the SCHEDULED keyword together with a time stamp.")
4433 (make-variable-buffer-local 'org-scheduled-time-regexp)
4434 (defvar org-closed-time-regexp nil
4435 "Matches the CLOSED keyword together with a time stamp.")
4436 (make-variable-buffer-local 'org-closed-time-regexp)
4438 (defvar org-keyword-time-regexp nil
4439 "Matches any of the 4 keywords, together with the time stamp.")
4440 (make-variable-buffer-local 'org-keyword-time-regexp)
4441 (defvar org-keyword-time-not-clock-regexp nil
4442 "Matches any of the 3 keywords, together with the time stamp.")
4443 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4444 (defvar org-maybe-keyword-time-regexp nil
4445 "Matches a timestamp, possibly preceded by a keyword.")
4446 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4447 (defvar org-all-time-keywords nil
4448 "List of time keywords.")
4449 (make-variable-buffer-local 'org-all-time-keywords)
4451 (defconst org-plain-time-of-day-regexp
4452 (concat
4453 "\\(\\<[012]?[0-9]"
4454 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4455 "\\(--?"
4456 "\\(\\<[012]?[0-9]"
4457 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4458 "\\)?")
4459 "Regular expression to match a plain time or time range.
4460 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4461 groups carry important information:
4462 0 the full match
4463 1 the first time, range or not
4464 8 the second time, if it is a range.")
4466 (defconst org-plain-time-extension-regexp
4467 (concat
4468 "\\(\\<[012]?[0-9]"
4469 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4470 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4471 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4472 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4473 groups carry important information:
4474 0 the full match
4475 7 hours of duration
4476 9 minutes of duration")
4478 (defconst org-stamp-time-of-day-regexp
4479 (concat
4480 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4481 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4482 "\\(--?"
4483 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4484 "Regular expression to match a timestamp time or time range.
4485 After a match, the following groups carry important information:
4486 0 the full match
4487 1 date plus weekday, for back referencing to make sure both times are on the same day
4488 2 the first time, range or not
4489 4 the second time, if it is a range.")
4491 (defconst org-startup-options
4492 '(("fold" org-startup-folded t)
4493 ("overview" org-startup-folded t)
4494 ("nofold" org-startup-folded nil)
4495 ("showall" org-startup-folded nil)
4496 ("showeverything" org-startup-folded showeverything)
4497 ("content" org-startup-folded content)
4498 ("indent" org-startup-indented t)
4499 ("noindent" org-startup-indented nil)
4500 ("hidestars" org-hide-leading-stars t)
4501 ("showstars" org-hide-leading-stars nil)
4502 ("odd" org-odd-levels-only t)
4503 ("oddeven" org-odd-levels-only nil)
4504 ("align" org-startup-align-all-tables t)
4505 ("noalign" org-startup-align-all-tables nil)
4506 ("inlineimages" org-startup-with-inline-images t)
4507 ("noinlineimages" org-startup-with-inline-images nil)
4508 ("customtime" org-display-custom-times t)
4509 ("logdone" org-log-done time)
4510 ("lognotedone" org-log-done note)
4511 ("nologdone" org-log-done nil)
4512 ("lognoteclock-out" org-log-note-clock-out t)
4513 ("nolognoteclock-out" org-log-note-clock-out nil)
4514 ("logrepeat" org-log-repeat state)
4515 ("lognoterepeat" org-log-repeat note)
4516 ("nologrepeat" org-log-repeat nil)
4517 ("logreschedule" org-log-reschedule time)
4518 ("lognotereschedule" org-log-reschedule note)
4519 ("nologreschedule" org-log-reschedule nil)
4520 ("logredeadline" org-log-redeadline time)
4521 ("lognoteredeadline" org-log-redeadline note)
4522 ("nologredeadline" org-log-redeadline nil)
4523 ("logrefile" org-log-refile time)
4524 ("lognoterefile" org-log-refile note)
4525 ("nologrefile" org-log-refile nil)
4526 ("fninline" org-footnote-define-inline t)
4527 ("nofninline" org-footnote-define-inline nil)
4528 ("fnlocal" org-footnote-section nil)
4529 ("fnauto" org-footnote-auto-label t)
4530 ("fnprompt" org-footnote-auto-label nil)
4531 ("fnconfirm" org-footnote-auto-label confirm)
4532 ("fnplain" org-footnote-auto-label plain)
4533 ("fnadjust" org-footnote-auto-adjust t)
4534 ("nofnadjust" org-footnote-auto-adjust nil)
4535 ("constcgs" constants-unit-system cgs)
4536 ("constSI" constants-unit-system SI)
4537 ("noptag" org-tag-persistent-alist nil)
4538 ("hideblocks" org-hide-block-startup t)
4539 ("nohideblocks" org-hide-block-startup nil)
4540 ("beamer" org-startup-with-beamer-mode t)
4541 ("entitiespretty" org-pretty-entities t)
4542 ("entitiesplain" org-pretty-entities nil))
4543 "Variable associated with STARTUP options for org-mode.
4544 Each element is a list of three items: the startup options (as written
4545 in the #+STARTUP line), the corresponding variable, and the value to set
4546 this variable to if the option is found. An optional forth element PUSH
4547 means to push this value onto the list in the variable.")
4549 (defun org-update-property-plist (key val props)
4550 "Update PROPS with KEY and VAL."
4551 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4552 (key (if appending (substring key 0 (- (length key) 1)) key))
4553 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4554 (previous (cdr (assoc key props))))
4555 (if appending
4556 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4557 (cons (cons key val) remainder))))
4559 (defconst org-block-regexp
4560 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4561 "Regular expression for hiding blocks.")
4562 (defconst org-heading-keyword-regexp-format
4563 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4564 "Printf format for a regexp matching an headline with some keyword.
4565 This regexp will match the headline of any node which has the
4566 exact keyword that is put into the format. The keyword isn't in
4567 any group by default, but the stars and the body are.")
4568 (defconst org-heading-keyword-maybe-regexp-format
4569 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4570 "Printf format for a regexp matching an headline, possibly with some keyword.
4571 This regexp can match any headline with the specified keyword, or
4572 without a keyword. The keyword isn't in any group by default,
4573 but the stars and the body are.")
4575 (defun org-set-regexps-and-options ()
4576 "Precompute regular expressions for current buffer."
4577 (when (derived-mode-p 'org-mode)
4578 (org-set-local 'org-todo-kwd-alist nil)
4579 (org-set-local 'org-todo-key-alist nil)
4580 (org-set-local 'org-todo-key-trigger nil)
4581 (org-set-local 'org-todo-keywords-1 nil)
4582 (org-set-local 'org-done-keywords nil)
4583 (org-set-local 'org-todo-heads nil)
4584 (org-set-local 'org-todo-sets nil)
4585 (org-set-local 'org-todo-log-states nil)
4586 (org-set-local 'org-file-properties nil)
4587 (org-set-local 'org-file-tags nil)
4588 (let ((re (org-make-options-regexp
4589 '("CATEGORY" "TODO" "COLUMNS"
4590 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4591 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4592 "OPTIONS")
4593 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4594 (splitre "[ \t]+")
4595 (scripts org-use-sub-superscripts)
4596 kwds kws0 kwsa key log value cat arch tags const links hw dws
4597 tail sep kws1 prio props ftags drawers beamer-p
4598 ext-setup-or-nil setup-contents (start 0))
4599 (save-excursion
4600 (save-restriction
4601 (widen)
4602 (goto-char (point-min))
4603 (while (or (and ext-setup-or-nil
4604 (string-match re ext-setup-or-nil start)
4605 (setq start (match-end 0)))
4606 (and (setq ext-setup-or-nil nil start 0)
4607 (re-search-forward re nil t)))
4608 (setq key (upcase (match-string 1 ext-setup-or-nil))
4609 value (org-match-string-no-properties 2 ext-setup-or-nil))
4610 (if (stringp value) (setq value (org-trim value)))
4611 (cond
4612 ((equal key "CATEGORY")
4613 (setq cat value))
4614 ((member key '("SEQ_TODO" "TODO"))
4615 (push (cons 'sequence (org-split-string value splitre)) kwds))
4616 ((equal key "TYP_TODO")
4617 (push (cons 'type (org-split-string value splitre)) kwds))
4618 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4619 ;; general TODO-like setup
4620 (push (cons (intern (downcase (match-string 1 key)))
4621 (org-split-string value splitre)) kwds))
4622 ((equal key "TAGS")
4623 (setq tags (append tags (if tags '("\\n") nil)
4624 (org-split-string value splitre))))
4625 ((equal key "COLUMNS")
4626 (org-set-local 'org-columns-default-format value))
4627 ((equal key "LINK")
4628 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4629 (push (cons (match-string 1 value)
4630 (org-trim (match-string 2 value)))
4631 links)))
4632 ((equal key "PRIORITIES")
4633 (setq prio (org-split-string value " +")))
4634 ((equal key "PROPERTY")
4635 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4636 (setq props (org-update-property-plist (match-string 1 value)
4637 (match-string 2 value)
4638 props))))
4639 ((equal key "FILETAGS")
4640 (when (string-match "\\S-" value)
4641 (setq ftags
4642 (append
4643 ftags
4644 (apply 'append
4645 (mapcar (lambda (x) (org-split-string x ":"))
4646 (org-split-string value)))))))
4647 ((equal key "DRAWERS")
4648 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4649 ((equal key "CONSTANTS")
4650 (setq const (append const (org-split-string value splitre))))
4651 ((equal key "STARTUP")
4652 (let ((opts (org-split-string value splitre))
4653 l var val)
4654 (while (setq l (pop opts))
4655 (when (setq l (assoc l org-startup-options))
4656 (setq var (nth 1 l) val (nth 2 l))
4657 (if (not (nth 3 l))
4658 (set (make-local-variable var) val)
4659 (if (not (listp (symbol-value var)))
4660 (set (make-local-variable var) nil))
4661 (set (make-local-variable var) (symbol-value var))
4662 (add-to-list var val))))))
4663 ((equal key "ARCHIVE")
4664 (setq arch value)
4665 (remove-text-properties 0 (length arch)
4666 '(face t fontified t) arch))
4667 ((equal key "LATEX_CLASS")
4668 (setq beamer-p (equal value "beamer")))
4669 ((equal key "OPTIONS")
4670 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4671 (setq scripts (read (match-string 2 value)))))
4672 ((equal key "SETUPFILE")
4673 (setq setup-contents (org-file-contents
4674 (expand-file-name
4675 (org-remove-double-quotes value))
4676 'noerror))
4677 (if (not ext-setup-or-nil)
4678 (setq ext-setup-or-nil setup-contents start 0)
4679 (setq ext-setup-or-nil
4680 (concat (substring ext-setup-or-nil 0 start)
4681 "\n" setup-contents "\n"
4682 (substring ext-setup-or-nil start)))))))
4683 ;; search for property blocks
4684 (goto-char (point-min))
4685 (while (re-search-forward org-block-regexp nil t)
4686 (when (equal "PROPERTY" (upcase (match-string 1)))
4687 (setq value (replace-regexp-in-string
4688 "[\n\r]" " " (match-string 4)))
4689 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4690 (setq props (org-update-property-plist (match-string 1 value)
4691 (match-string 2 value)
4692 props)))))))
4693 (org-set-local 'org-use-sub-superscripts scripts)
4694 (when cat
4695 (org-set-local 'org-category (intern cat))
4696 (push (cons "CATEGORY" cat) props))
4697 (when prio
4698 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4699 (setq prio (mapcar 'string-to-char prio))
4700 (org-set-local 'org-highest-priority (nth 0 prio))
4701 (org-set-local 'org-lowest-priority (nth 1 prio))
4702 (org-set-local 'org-default-priority (nth 2 prio)))
4703 (and props (org-set-local 'org-file-properties (nreverse props)))
4704 (and ftags (org-set-local 'org-file-tags
4705 (mapcar 'org-add-prop-inherited ftags)))
4706 (and drawers (org-set-local 'org-drawers drawers))
4707 (and arch (org-set-local 'org-archive-location arch))
4708 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4709 ;; Process the TODO keywords
4710 (unless kwds
4711 ;; Use the global values as if they had been given locally.
4712 (setq kwds (default-value 'org-todo-keywords))
4713 (if (stringp (car kwds))
4714 (setq kwds (list (cons org-todo-interpretation
4715 (default-value 'org-todo-keywords)))))
4716 (setq kwds (reverse kwds)))
4717 (setq kwds (nreverse kwds))
4718 (let (inter kws kw)
4719 (while (setq kws (pop kwds))
4720 (let ((kws (or
4721 (run-hook-with-args-until-success
4722 'org-todo-setup-filter-hook kws)
4723 kws)))
4724 (setq inter (pop kws) sep (member "|" kws)
4725 kws0 (delete "|" (copy-sequence kws))
4726 kwsa nil
4727 kws1 (mapcar
4728 (lambda (x)
4729 ;; 1 2
4730 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4731 (progn
4732 (setq kw (match-string 1 x)
4733 key (and (match-end 2) (match-string 2 x))
4734 log (org-extract-log-state-settings x))
4735 (push (cons kw (and key (string-to-char key))) kwsa)
4736 (and log (push log org-todo-log-states))
4738 (error "Invalid TODO keyword %s" x)))
4739 kws0)
4740 kwsa (if kwsa (append '((:startgroup))
4741 (nreverse kwsa)
4742 '((:endgroup))))
4743 hw (car kws1)
4744 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4745 tail (list inter hw (car dws) (org-last dws))))
4746 (add-to-list 'org-todo-heads hw 'append)
4747 (push kws1 org-todo-sets)
4748 (setq org-done-keywords (append org-done-keywords dws nil))
4749 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4750 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4751 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4752 (setq org-todo-sets (nreverse org-todo-sets)
4753 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4754 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4755 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4756 ;; Process the constants
4757 (when const
4758 (let (e cst)
4759 (while (setq e (pop const))
4760 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4761 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4762 (setq org-table-formula-constants-local cst)))
4764 ;; Process the tags.
4765 (when tags
4766 (let (e tgs)
4767 (while (setq e (pop tags))
4768 (cond
4769 ((equal e "{") (push '(:startgroup) tgs))
4770 ((equal e "}") (push '(:endgroup) tgs))
4771 ((equal e "\\n") (push '(:newline) tgs))
4772 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4773 (push (cons (match-string 1 e)
4774 (string-to-char (match-string 2 e)))
4775 tgs))
4776 (t (push (list e) tgs))))
4777 (org-set-local 'org-tag-alist nil)
4778 (while (setq e (pop tgs))
4779 (or (and (stringp (car e))
4780 (assoc (car e) org-tag-alist))
4781 (push e org-tag-alist)))))
4783 ;; Compute the regular expressions and other local variables.
4784 ;; Using `org-outline-regexp-bol' would complicate them much,
4785 ;; because of the fixed white space at the end of that string.
4786 (if (not org-done-keywords)
4787 (setq org-done-keywords (and org-todo-keywords-1
4788 (list (org-last org-todo-keywords-1)))))
4789 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4790 (length org-scheduled-string)
4791 (length org-clock-string)
4792 (length org-closed-string)))
4793 org-drawer-regexp
4794 (concat "^[ \t]*:\\("
4795 (mapconcat 'regexp-quote org-drawers "\\|")
4796 "\\):[ \t]*$")
4797 org-not-done-keywords
4798 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4799 org-todo-regexp
4800 (concat "\\("
4801 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4802 "\\)")
4803 org-not-done-regexp
4804 (concat "\\("
4805 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4806 "\\)")
4807 org-not-done-heading-regexp
4808 (format org-heading-keyword-regexp-format org-not-done-regexp)
4809 org-todo-line-regexp
4810 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4811 org-complex-heading-regexp
4812 (concat "^\\(\\*+\\)"
4813 "\\(?: +" org-todo-regexp "\\)?"
4814 "\\(?: +\\(\\[#.\\]\\)\\)?"
4815 "\\(?: +\\(.*?\\)\\)?"
4816 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4817 "[ \t]*$")
4818 org-complex-heading-regexp-format
4819 (concat "^\\(\\*+\\)"
4820 "\\(?: +" org-todo-regexp "\\)?"
4821 "\\(?: +\\(\\[#.\\]\\)\\)?"
4822 "\\(?: +"
4823 ;; Stats cookies can be stuck to body.
4824 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4825 "\\(%s\\)"
4826 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4827 "\\)"
4828 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4829 "[ \t]*$")
4830 org-todo-line-tags-regexp
4831 (concat "^\\(\\*+\\)"
4832 "\\(?: +" org-todo-regexp "\\)?"
4833 "\\(?: +\\(.*?\\)\\)?"
4834 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4835 "[ \t]*$")
4836 org-deadline-regexp (concat "\\<" org-deadline-string)
4837 org-deadline-time-regexp
4838 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4839 org-deadline-line-regexp
4840 (concat "\\<\\(" org-deadline-string "\\).*")
4841 org-scheduled-regexp
4842 (concat "\\<" org-scheduled-string)
4843 org-scheduled-time-regexp
4844 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4845 org-closed-time-regexp
4846 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4847 org-keyword-time-regexp
4848 (concat "\\<\\(" org-scheduled-string
4849 "\\|" org-deadline-string
4850 "\\|" org-closed-string
4851 "\\|" org-clock-string "\\)"
4852 " *[[<]\\([^]>]+\\)[]>]")
4853 org-keyword-time-not-clock-regexp
4854 (concat "\\<\\(" org-scheduled-string
4855 "\\|" org-deadline-string
4856 "\\|" org-closed-string
4857 "\\)"
4858 " *[[<]\\([^]>]+\\)[]>]")
4859 org-maybe-keyword-time-regexp
4860 (concat "\\(\\<\\(" org-scheduled-string
4861 "\\|" org-deadline-string
4862 "\\|" org-closed-string
4863 "\\|" org-clock-string "\\)\\)?"
4864 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4865 org-all-time-keywords
4866 (mapcar (lambda (w) (substring w 0 -1))
4867 (list org-scheduled-string org-deadline-string
4868 org-clock-string org-closed-string))
4870 (org-compute-latex-and-specials-regexp)
4871 (org-set-font-lock-defaults))))
4873 (defun org-file-contents (file &optional noerror)
4874 "Return the contents of FILE, as a string."
4875 (if (or (not file)
4876 (not (file-readable-p file)))
4877 (if noerror
4878 (progn
4879 (message "Cannot read file \"%s\"" file)
4880 (ding) (sit-for 2)
4882 (error "Cannot read file \"%s\"" file))
4883 (with-temp-buffer
4884 (insert-file-contents file)
4885 (buffer-string))))
4887 (defun org-extract-log-state-settings (x)
4888 "Extract the log state setting from a TODO keyword string.
4889 This will extract info from a string like \"WAIT(w@/!)\"."
4890 (let (kw key log1 log2)
4891 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4892 (setq kw (match-string 1 x)
4893 key (and (match-end 2) (match-string 2 x))
4894 log1 (and (match-end 3) (match-string 3 x))
4895 log2 (and (match-end 4) (match-string 4 x)))
4896 (and (or log1 log2)
4897 (list kw
4898 (and log1 (if (equal log1 "!") 'time 'note))
4899 (and log2 (if (equal log2 "!") 'time 'note)))))))
4901 (defun org-remove-keyword-keys (list)
4902 "Remove a pair of parenthesis at the end of each string in LIST."
4903 (mapcar (lambda (x)
4904 (if (string-match "(.*)$" x)
4905 (substring x 0 (match-beginning 0))
4907 list))
4909 (defun org-assign-fast-keys (alist)
4910 "Assign fast keys to a keyword-key alist.
4911 Respect keys that are already there."
4912 (let (new e (alt ?0))
4913 (while (setq e (pop alist))
4914 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4915 (cdr e)) ;; Key already assigned.
4916 (push e new)
4917 (let ((clist (string-to-list (downcase (car e))))
4918 (used (append new alist)))
4919 (when (= (car clist) ?@)
4920 (pop clist))
4921 (while (and clist (rassoc (car clist) used))
4922 (pop clist))
4923 (unless clist
4924 (while (rassoc alt used)
4925 (incf alt)))
4926 (push (cons (car e) (or (car clist) alt)) new))))
4927 (nreverse new)))
4929 ;;; Some variables used in various places
4931 (defvar org-window-configuration nil
4932 "Used in various places to store a window configuration.")
4933 (defvar org-selected-window nil
4934 "Used in various places to store a window configuration.")
4935 (defvar org-finish-function nil
4936 "Function to be called when `C-c C-c' is used.
4937 This is for getting out of special buffers like remember.")
4940 ;; FIXME: Occasionally check by commenting these, to make sure
4941 ;; no other functions uses these, forgetting to let-bind them.
4942 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4943 (defvar org-last-state)
4944 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4946 ;; Defined somewhere in this file, but used before definition.
4947 (defvar org-entities) ;; defined in org-entities.el
4948 (defvar org-struct-menu)
4949 (defvar org-org-menu)
4950 (defvar org-tbl-menu)
4952 ;;;; Define the Org-mode
4954 ;; We use a before-change function to check if a table might need
4955 ;; an update.
4956 (defvar org-table-may-need-update t
4957 "Indicates that a table might need an update.
4958 This variable is set by `org-before-change-function'.
4959 `org-table-align' sets it back to nil.")
4960 (defun org-before-change-function (beg end)
4961 "Every change indicates that a table might need an update."
4962 (setq org-table-may-need-update t))
4963 (defvar org-mode-map)
4964 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4965 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4966 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4967 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4968 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4969 (defvar org-table-buffer-is-an nil)
4971 (defvar bidi-paragraph-direction)
4972 (defvar buffer-face-mode-face)
4974 (require 'outline)
4975 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4976 (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"))
4977 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4979 ;; Other stuff we need.
4980 (require 'time-date)
4981 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4982 (require 'easymenu)
4983 (require 'overlay)
4985 (require 'org-macs)
4986 (require 'org-entities)
4987 ;; (require 'org-compat) moved higher up in the file before it is first used
4988 (require 'org-faces)
4989 (require 'org-list)
4990 (require 'org-pcomplete)
4991 (require 'org-src)
4992 (require 'org-footnote)
4994 ;; babel
4995 (require 'ob)
4996 (require 'ob-table)
4997 (require 'ob-lob)
4998 (require 'ob-ref)
4999 (require 'ob-tangle)
5000 (require 'ob-comint)
5001 (require 'ob-keys)
5003 ;;;###autoload
5004 (define-derived-mode org-mode outline-mode "Org"
5005 "Outline-based notes management and organizer, alias
5006 \"Carsten's outline-mode for keeping track of everything.\"
5008 Org-mode develops organizational tasks around a NOTES file which
5009 contains information about projects as plain text. Org-mode is
5010 implemented on top of outline-mode, which is ideal to keep the content
5011 of large files well structured. It supports ToDo items, deadlines and
5012 time stamps, which magically appear in the diary listing of the Emacs
5013 calendar. Tables are easily created with a built-in table editor.
5014 Plain text URL-like links connect to websites, emails (VM), Usenet
5015 messages (Gnus), BBDB entries, and any files related to the project.
5016 For printing and sharing of notes, an Org-mode file (or a part of it)
5017 can be exported as a structured ASCII or HTML file.
5019 The following commands are available:
5021 \\{org-mode-map}"
5023 ;; Get rid of Outline menus, they are not needed
5024 ;; Need to do this here because define-derived-mode sets up
5025 ;; the keymap so late. Still, it is a waste to call this each time
5026 ;; we switch another buffer into org-mode.
5027 (if (featurep 'xemacs)
5028 (when (boundp 'outline-mode-menu-heading)
5029 ;; Assume this is Greg's port, it uses easymenu
5030 (easy-menu-remove outline-mode-menu-heading)
5031 (easy-menu-remove outline-mode-menu-show)
5032 (easy-menu-remove outline-mode-menu-hide))
5033 (define-key org-mode-map [menu-bar headings] 'undefined)
5034 (define-key org-mode-map [menu-bar hide] 'undefined)
5035 (define-key org-mode-map [menu-bar show] 'undefined))
5037 (org-load-modules-maybe)
5038 (easy-menu-add org-org-menu)
5039 (easy-menu-add org-tbl-menu)
5040 (org-install-agenda-files-menu)
5041 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5042 (add-to-invisibility-spec '(org-cwidth))
5043 (add-to-invisibility-spec '(org-hide-block . t))
5044 (when (featurep 'xemacs)
5045 (org-set-local 'line-move-ignore-invisible t))
5046 (org-set-local 'outline-regexp org-outline-regexp)
5047 (org-set-local 'outline-level 'org-outline-level)
5048 (setq bidi-paragraph-direction 'left-to-right)
5049 (when (and org-ellipsis
5050 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5051 (fboundp 'make-glyph-code))
5052 (unless org-display-table
5053 (setq org-display-table (make-display-table)))
5054 (set-display-table-slot
5055 org-display-table 4
5056 (vconcat (mapcar
5057 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5058 org-ellipsis)))
5059 (if (stringp org-ellipsis) org-ellipsis "..."))))
5060 (setq buffer-display-table org-display-table))
5061 (org-set-regexps-and-options)
5062 (when (and org-tag-faces (not org-tags-special-faces-re))
5063 ;; tag faces set outside customize.... force initialization.
5064 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5065 ;; Calc embedded
5066 (org-set-local 'calc-embedded-open-mode "# ")
5067 (modify-syntax-entry ?@ "w")
5068 (if org-startup-truncated (setq truncate-lines t))
5069 (org-set-local 'font-lock-unfontify-region-function
5070 'org-unfontify-region)
5071 ;; Activate before-change-function
5072 (org-set-local 'org-table-may-need-update t)
5073 (org-add-hook 'before-change-functions 'org-before-change-function nil
5074 'local)
5075 ;; Check for running clock before killing a buffer
5076 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5077 ;; Paragraphs and auto-filling
5078 (org-set-autofill-regexps)
5079 (org-set-local 'indent-line-function 'org-indent-line)
5080 (org-set-local 'indent-region-function 'org-indent-region)
5081 (org-update-radio-target-regexp)
5082 ;; Comments
5083 (org-set-local 'comment-use-syntax nil)
5084 (org-set-local 'comment-start "#")
5085 (org-set-local 'comment-start-skip "# ?")
5086 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
5087 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
5088 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region)
5089 ;; Beginning/end of defun
5090 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5091 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5092 ;; Next error for sparse trees
5093 (org-set-local 'next-error-function 'org-occur-next-match)
5094 ;; Make sure dependence stuff works reliably, even for users who set it
5095 ;; too late :-(
5096 (if org-enforce-todo-dependencies
5097 (add-hook 'org-blocker-hook
5098 'org-block-todo-from-children-or-siblings-or-parent)
5099 (remove-hook 'org-blocker-hook
5100 'org-block-todo-from-children-or-siblings-or-parent))
5101 (if org-enforce-todo-checkbox-dependencies
5102 (add-hook 'org-blocker-hook
5103 'org-block-todo-from-checkboxes)
5104 (remove-hook 'org-blocker-hook
5105 'org-block-todo-from-checkboxes))
5107 ;; Align options lines
5108 (org-set-local
5109 'align-mode-rules-list
5110 '((org-in-buffer-settings
5111 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5112 (modes . '(org-mode)))))
5114 ;; Imenu
5115 (org-set-local 'imenu-create-index-function
5116 'org-imenu-get-tree)
5118 ;; Make isearch reveal context
5119 (if (or (featurep 'xemacs)
5120 (not (boundp 'outline-isearch-open-invisible-function)))
5121 ;; Emacs 21 and XEmacs make use of the hook
5122 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5123 ;; Emacs 22 deals with this through a special variable
5124 (org-set-local 'outline-isearch-open-invisible-function
5125 (lambda (&rest ignore) (org-show-context 'isearch))))
5127 ;; Turn on org-beamer-mode?
5128 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5130 ;; Setup the pcomplete hooks
5131 (set (make-local-variable 'pcomplete-command-completion-function)
5132 'org-pcomplete-initial)
5133 (set (make-local-variable 'pcomplete-command-name-function)
5134 'org-command-at-point)
5135 (set (make-local-variable 'pcomplete-default-completion-function)
5136 'ignore)
5137 (set (make-local-variable 'pcomplete-parse-arguments-function)
5138 'org-parse-arguments)
5139 (set (make-local-variable 'pcomplete-termination-string) "")
5140 (when (>= emacs-major-version 23)
5141 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5143 ;; If empty file that did not turn on org-mode automatically, make it to.
5144 (if (and org-insert-mode-line-in-empty-file
5145 (org-called-interactively-p 'any)
5146 (= (point-min) (point-max)))
5147 (insert "# -*- mode: org -*-\n\n"))
5148 (unless org-inhibit-startup
5149 (when org-startup-align-all-tables
5150 (let ((bmp (buffer-modified-p)))
5151 (org-table-map-tables 'org-table-align 'quietly)
5152 (set-buffer-modified-p bmp)))
5153 (when org-startup-with-inline-images
5154 (org-display-inline-images))
5155 (when org-startup-indented
5156 (require 'org-indent)
5157 (org-indent-mode 1))
5158 (unless org-inhibit-startup-visibility-stuff
5159 (org-set-startup-visibility))))
5161 (when (fboundp 'abbrev-table-put)
5162 (abbrev-table-put org-mode-abbrev-table
5163 :parents (list text-mode-abbrev-table)))
5165 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5167 (defun org-current-time ()
5168 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5169 (if (> (car org-time-stamp-rounding-minutes) 1)
5170 (let ((r (car org-time-stamp-rounding-minutes))
5171 (time (decode-time)))
5172 (apply 'encode-time
5173 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5174 (nthcdr 2 time))))
5175 (current-time)))
5177 (defun org-today ()
5178 "Return today date, considering `org-extend-today-until'."
5179 (time-to-days
5180 (time-subtract (current-time)
5181 (list 0 (* 3600 org-extend-today-until) 0))))
5183 ;;;; Font-Lock stuff, including the activators
5185 (defvar org-mouse-map (make-sparse-keymap))
5186 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5187 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5188 (when org-mouse-1-follows-link
5189 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5190 (when org-tab-follows-link
5191 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5192 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5194 (require 'font-lock)
5196 (defconst org-non-link-chars "]\t\n\r<>")
5197 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5198 "shell" "elisp" "doi" "message"))
5199 (defvar org-link-types-re nil
5200 "Matches a link that has a url-like prefix like \"http:\"")
5201 (defvar org-link-re-with-space nil
5202 "Matches a link with spaces, optional angular brackets around it.")
5203 (defvar org-link-re-with-space2 nil
5204 "Matches a link with spaces, optional angular brackets around it.")
5205 (defvar org-link-re-with-space3 nil
5206 "Matches a link with spaces, only for internal part in bracket links.")
5207 (defvar org-angle-link-re nil
5208 "Matches link with angular brackets, spaces are allowed.")
5209 (defvar org-plain-link-re nil
5210 "Matches plain link, without spaces.")
5211 (defvar org-bracket-link-regexp nil
5212 "Matches a link in double brackets.")
5213 (defvar org-bracket-link-analytic-regexp nil
5214 "Regular expression used to analyze links.
5215 Here is what the match groups contain after a match:
5216 1: http:
5217 2: http
5218 3: path
5219 4: [desc]
5220 5: desc")
5221 (defvar org-bracket-link-analytic-regexp++ nil
5222 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5223 (defvar org-any-link-re nil
5224 "Regular expression matching any link.")
5226 (defcustom org-match-sexp-depth 3
5227 "Number of stacked braces for sub/superscript matching.
5228 This has to be set before loading org.el to be effective."
5229 :group 'org-export-translation ; ??????????????????????????/
5230 :type 'integer)
5232 (defun org-create-multibrace-regexp (left right n)
5233 "Create a regular expression which will match a balanced sexp.
5234 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5235 as single character strings.
5236 The regexp returned will match the entire expression including the
5237 delimiters. It will also define a single group which contains the
5238 match except for the outermost delimiters. The maximum depth of
5239 stacked delimiters is N. Escaping delimiters is not possible."
5240 (let* ((nothing (concat "[^" left right "]*?"))
5241 (or "\\|")
5242 (re nothing)
5243 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5244 (while (> n 1)
5245 (setq n (1- n)
5246 re (concat re or next)
5247 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5248 (concat left "\\(" re "\\)" right)))
5250 (defvar org-match-substring-regexp
5251 (concat
5252 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5253 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5254 "\\|"
5255 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5256 "\\|"
5257 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5258 "The regular expression matching a sub- or superscript.")
5260 (defvar org-match-substring-with-braces-regexp
5261 (concat
5262 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5263 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5264 "\\)")
5265 "The regular expression matching a sub- or superscript, forcing braces.")
5267 (defun org-make-link-regexps ()
5268 "Update the link regular expressions.
5269 This should be called after the variable `org-link-types' has changed."
5270 (setq org-link-types-re
5271 (concat
5272 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5273 org-link-re-with-space
5274 (concat
5275 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5276 "\\([^" org-non-link-chars " ]"
5277 "[^" org-non-link-chars "]*"
5278 "[^" org-non-link-chars " ]\\)>?")
5279 org-link-re-with-space2
5280 (concat
5281 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5282 "\\([^" org-non-link-chars " ]"
5283 "[^\t\n\r]*"
5284 "[^" org-non-link-chars " ]\\)>?")
5285 org-link-re-with-space3
5286 (concat
5287 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5288 "\\([^" org-non-link-chars " ]"
5289 "[^\t\n\r]*\\)")
5290 org-angle-link-re
5291 (concat
5292 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5293 "\\([^" org-non-link-chars " ]"
5294 "[^" org-non-link-chars "]*"
5295 "\\)>")
5296 org-plain-link-re
5297 (concat
5298 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5299 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5300 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5301 org-bracket-link-regexp
5302 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5303 org-bracket-link-analytic-regexp
5304 (concat
5305 "\\[\\["
5306 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5307 "\\([^]]+\\)"
5308 "\\]"
5309 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5310 "\\]")
5311 org-bracket-link-analytic-regexp++
5312 (concat
5313 "\\[\\["
5314 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5315 "\\([^]]+\\)"
5316 "\\]"
5317 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5318 "\\]")
5319 org-any-link-re
5320 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5321 org-angle-link-re "\\)\\|\\("
5322 org-plain-link-re "\\)")))
5324 (org-make-link-regexps)
5326 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5327 "Regular expression for fast time stamp matching.")
5328 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5329 "Regular expression for fast time stamp matching.")
5330 (defconst org-ts-regexp0
5331 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5332 "Regular expression matching time strings for analysis.
5333 This one does not require the space after the date, so it can be used
5334 on a string that terminates immediately after the date.")
5335 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5336 "Regular expression matching time strings for analysis.")
5337 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5338 "Regular expression matching time stamps, with groups.")
5339 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5340 "Regular expression matching time stamps (also [..]), with groups.")
5341 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5342 "Regular expression matching a time stamp range.")
5343 (defconst org-tr-regexp-both
5344 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5345 "Regular expression matching a time stamp range.")
5346 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5347 org-ts-regexp "\\)?")
5348 "Regular expression matching a time stamp or time stamp range.")
5349 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5350 org-ts-regexp-both "\\)?")
5351 "Regular expression matching a time stamp or time stamp range.
5352 The time stamps may be either active or inactive.")
5354 (defvar org-emph-face nil)
5356 (defun org-do-emphasis-faces (limit)
5357 "Run through the buffer and add overlays to emphasized strings."
5358 (let (rtn a)
5359 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5360 (if (not (= (char-after (match-beginning 3))
5361 (char-after (match-beginning 4))))
5362 (progn
5363 (setq rtn t)
5364 (setq a (assoc (match-string 3) org-emphasis-alist))
5365 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5366 'face
5367 (nth 1 a))
5368 (and (nth 4 a)
5369 (org-remove-flyspell-overlays-in
5370 (match-beginning 0) (match-end 0)))
5371 (add-text-properties (match-beginning 2) (match-end 2)
5372 '(font-lock-multiline t org-emphasis t))
5373 (when org-hide-emphasis-markers
5374 (add-text-properties (match-end 4) (match-beginning 5)
5375 '(invisible org-link))
5376 (add-text-properties (match-beginning 3) (match-end 3)
5377 '(invisible org-link)))))
5378 (backward-char 1))
5379 rtn))
5381 (defun org-emphasize (&optional char)
5382 "Insert or change an emphasis, i.e. a font like bold or italic.
5383 If there is an active region, change that region to a new emphasis.
5384 If there is no region, just insert the marker characters and position
5385 the cursor between them.
5386 CHAR should be either the marker character, or the first character of the
5387 HTML tag associated with that emphasis. If CHAR is a space, the means
5388 to remove the emphasis of the selected region.
5389 If char is not given (for example in an interactive call) it
5390 will be prompted for."
5391 (interactive)
5392 (let ((eal org-emphasis-alist) e det
5393 (erc org-emphasis-regexp-components)
5394 (prompt "")
5395 (string "") beg end move tag c s)
5396 (if (org-region-active-p)
5397 (setq beg (region-beginning) end (region-end)
5398 string (buffer-substring beg end))
5399 (setq move t))
5401 (while (setq e (pop eal))
5402 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5403 c (aref tag 0))
5404 (push (cons c (string-to-char (car e))) det)
5405 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5406 (substring tag 1)))))
5407 (setq det (nreverse det))
5408 (unless char
5409 (message "%s" (concat "Emphasis marker or tag:" prompt))
5410 (setq char (read-char-exclusive)))
5411 (setq char (or (cdr (assoc char det)) char))
5412 (if (equal char ?\ )
5413 (setq s "" move nil)
5414 (unless (assoc (char-to-string char) org-emphasis-alist)
5415 (error "No such emphasis marker: \"%c\"" char))
5416 (setq s (char-to-string char)))
5417 (while (and (> (length string) 1)
5418 (equal (substring string 0 1) (substring string -1))
5419 (assoc (substring string 0 1) org-emphasis-alist))
5420 (setq string (substring string 1 -1)))
5421 (setq string (concat s string s))
5422 (if beg (delete-region beg end))
5423 (unless (or (bolp)
5424 (string-match (concat "[" (nth 0 erc) "\n]")
5425 (char-to-string (char-before (point)))))
5426 (insert " "))
5427 (unless (or (eobp)
5428 (string-match (concat "[" (nth 1 erc) "\n]")
5429 (char-to-string (char-after (point)))))
5430 (insert " ") (backward-char 1))
5431 (insert string)
5432 (and move (backward-char 1))))
5434 (defconst org-nonsticky-props
5435 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5437 (defsubst org-rear-nonsticky-at (pos)
5438 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5440 (defun org-activate-plain-links (limit)
5441 "Run through the buffer and add overlays to links."
5442 (catch 'exit
5443 (let (f)
5444 (if (re-search-forward org-plain-link-re limit t)
5445 (progn
5446 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5447 (setq f (get-text-property (match-beginning 0) 'face))
5448 (if (or (eq f 'org-tag)
5449 (and (listp f) (memq 'org-tag f)))
5451 (add-text-properties (match-beginning 0) (match-end 0)
5452 (list 'mouse-face 'highlight
5453 'face 'org-link
5454 'keymap org-mouse-map))
5455 (org-rear-nonsticky-at (match-end 0)))
5456 t)))))
5458 (defun org-activate-code (limit)
5459 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5460 (progn
5461 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5462 (remove-text-properties (match-beginning 0) (match-end 0)
5463 '(display t invisible t intangible t))
5464 t)))
5466 (defcustom org-src-fontify-natively nil
5467 "When non-nil, fontify code in code blocks."
5468 :type 'boolean
5469 :version "24.1"
5470 :group 'org-appearance
5471 :group 'org-babel)
5473 (defcustom org-src-prevent-auto-filling nil
5474 "When non-nil, prevent auto-filling in src blocks."
5475 :type 'boolean
5476 :version "24.1"
5477 :group 'org-appearance
5478 :group 'org-babel)
5480 (defcustom org-allow-promoting-top-level-subtree nil
5481 "When non-nil, allow promoting a top level subtree.
5482 The leading star of the top level headline will be replaced
5483 by a #."
5484 :type 'boolean
5485 :version "24.1"
5486 :group 'org-appearance)
5488 (defun org-fontify-meta-lines-and-blocks (limit)
5489 (condition-case nil
5490 (org-fontify-meta-lines-and-blocks-1 limit)
5491 (error (message "org-mode fontification error"))))
5493 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5494 "Fontify #+ lines and blocks, in the correct ways."
5495 (let ((case-fold-search t))
5496 (if (re-search-forward
5497 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5498 limit t)
5499 (let ((beg (match-beginning 0))
5500 (block-start (match-end 0))
5501 (block-end nil)
5502 (lang (match-string 7))
5503 (beg1 (line-beginning-position 2))
5504 (dc1 (downcase (match-string 2)))
5505 (dc3 (downcase (match-string 3)))
5506 end end1 quoting block-type ovl)
5507 (cond
5508 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5509 ;; a single line of backend-specific content
5510 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5511 (remove-text-properties (match-beginning 0) (match-end 0)
5512 '(display t invisible t intangible t))
5513 (add-text-properties (match-beginning 1) (match-end 3)
5514 '(font-lock-fontified t face org-meta-line))
5515 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5516 '(font-lock-fontified t face org-block))
5517 ; for backend-specific code
5519 ((and (match-end 4) (equal dc3 "+begin"))
5520 ;; Truly a block
5521 (setq block-type (downcase (match-string 5))
5522 quoting (member block-type org-protecting-blocks))
5523 (when (re-search-forward
5524 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5525 nil t) ;; on purpose, we look further than LIMIT
5526 (setq end (min (point-max) (match-end 0))
5527 end1 (min (point-max) (1- (match-beginning 0))))
5528 (setq block-end (match-beginning 0))
5529 (when quoting
5530 (remove-text-properties beg end
5531 '(display t invisible t intangible t)))
5532 (add-text-properties
5533 beg end
5534 '(font-lock-fontified t font-lock-multiline t))
5535 (add-text-properties beg beg1 '(face org-meta-line))
5536 (add-text-properties end1 (min (point-max) (1+ end))
5537 '(face org-meta-line)) ; for end_src
5538 (cond
5539 ((and lang (not (string= lang "")) org-src-fontify-natively)
5540 (org-src-font-lock-fontify-block lang block-start block-end)
5541 ;; remove old background overlays
5542 (mapc (lambda (ov)
5543 (if (eq (overlay-get ov 'face) 'org-block-background)
5544 (delete-overlay ov)))
5545 (overlays-at (/ (+ beg1 block-end) 2)))
5546 ;; add a background overlay
5547 (setq ovl (make-overlay beg1 block-end))
5548 (overlay-put ovl 'face 'org-block-background)
5549 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5550 (quoting
5551 (add-text-properties beg1 (min (point-max) (1+ end1))
5552 '(face org-block))) ; end of source block
5553 ((not org-fontify-quote-and-verse-blocks))
5554 ((string= block-type "quote")
5555 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5556 ((string= block-type "verse")
5557 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5558 (add-text-properties beg beg1 '(face org-block-begin-line))
5559 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5560 '(face org-block-end-line))
5562 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5563 (add-text-properties
5564 beg (match-end 3)
5565 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5566 '(font-lock-fontified t invisible t)
5567 '(font-lock-fontified t face org-document-info-keyword)))
5568 (add-text-properties
5569 (match-beginning 6) (match-end 6)
5570 (if (string-equal dc1 "+title:")
5571 '(font-lock-fontified t face org-document-title)
5572 '(font-lock-fontified t face org-document-info))))
5573 ((or (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5574 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5575 "+call:" "+header:" "+headers:" "+name:"))
5576 (and (match-end 4) (equal dc3 "+attr")))
5577 (add-text-properties
5578 beg (match-end 0)
5579 '(font-lock-fontified t face org-meta-line))
5581 ((member dc3 '(" " ""))
5582 (add-text-properties
5583 beg (match-end 0)
5584 '(font-lock-fontified t face font-lock-comment-face)))
5585 ((not (member (char-after beg) '(?\ ?\t)))
5586 ;; just any other in-buffer setting, but not indented
5587 (add-text-properties
5588 beg (match-end 0)
5589 '(font-lock-fontified t face org-meta-line))
5591 (t nil))))))
5593 (defun org-strip-protective-commas (beg end)
5594 "Strip protective commas between BEG and END in the current buffer."
5595 (interactive "r")
5596 (save-excursion
5597 (save-match-data
5598 (goto-char beg)
5599 (let ((front-line (save-excursion
5600 (re-search-forward
5601 "[^[:space:]]" end t)
5602 (goto-char (match-beginning 0))
5603 (current-column))))
5604 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5605 (goto-char (match-beginning 1))
5606 (when (= (current-column) front-line)
5607 (replace-match "" nil nil nil 1)))))))
5609 (defun org-activate-angle-links (limit)
5610 "Run through the buffer and add overlays to links."
5611 (if (re-search-forward org-angle-link-re limit t)
5612 (progn
5613 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5614 (add-text-properties (match-beginning 0) (match-end 0)
5615 (list 'mouse-face 'highlight
5616 'keymap org-mouse-map))
5617 (org-rear-nonsticky-at (match-end 0))
5618 t)))
5620 (defun org-activate-footnote-links (limit)
5621 "Run through the buffer and add overlays to footnotes."
5622 (let ((fn (org-footnote-next-reference-or-definition limit)))
5623 (when fn
5624 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5625 (org-remove-flyspell-overlays-in beg end)
5626 (add-text-properties beg end
5627 (list 'mouse-face 'highlight
5628 'keymap org-mouse-map
5629 'help-echo
5630 (if (= (point-at-bol) beg)
5631 "Footnote definition"
5632 "Footnote reference")
5633 'font-lock-fontified t
5634 'font-lock-multiline t
5635 'face 'org-footnote))))))
5637 (defun org-activate-bracket-links (limit)
5638 "Run through the buffer and add overlays to bracketed links."
5639 (if (re-search-forward org-bracket-link-regexp limit t)
5640 (let* ((help (concat "LINK: "
5641 (org-match-string-no-properties 1)))
5642 ;; FIXME: above we should remove the escapes.
5643 ;; but that requires another match, protecting match data,
5644 ;; a lot of overhead for font-lock.
5645 (ip (org-maybe-intangible
5646 (list 'invisible 'org-link
5647 'keymap org-mouse-map 'mouse-face 'highlight
5648 'font-lock-multiline t 'help-echo help)))
5649 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5650 'font-lock-multiline t 'help-echo help)))
5651 ;; We need to remove the invisible property here. Table narrowing
5652 ;; may have made some of this invisible.
5653 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5654 (remove-text-properties (match-beginning 0) (match-end 0)
5655 '(invisible nil))
5656 (if (match-end 3)
5657 (progn
5658 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5659 (org-rear-nonsticky-at (match-beginning 3))
5660 (add-text-properties (match-beginning 3) (match-end 3) vp)
5661 (org-rear-nonsticky-at (match-end 3))
5662 (add-text-properties (match-end 3) (match-end 0) ip)
5663 (org-rear-nonsticky-at (match-end 0)))
5664 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5665 (org-rear-nonsticky-at (match-beginning 1))
5666 (add-text-properties (match-beginning 1) (match-end 1) vp)
5667 (org-rear-nonsticky-at (match-end 1))
5668 (add-text-properties (match-end 1) (match-end 0) ip)
5669 (org-rear-nonsticky-at (match-end 0)))
5670 t)))
5672 (defun org-activate-dates (limit)
5673 "Run through the buffer and add overlays to dates."
5674 (if (re-search-forward org-tsr-regexp-both limit t)
5675 (progn
5676 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5677 (add-text-properties (match-beginning 0) (match-end 0)
5678 (list 'mouse-face 'highlight
5679 'keymap org-mouse-map))
5680 (org-rear-nonsticky-at (match-end 0))
5681 (when org-display-custom-times
5682 (if (match-end 3)
5683 (org-display-custom-time (match-beginning 3) (match-end 3)))
5684 (org-display-custom-time (match-beginning 1) (match-end 1)))
5685 t)))
5687 (defvar org-target-link-regexp nil
5688 "Regular expression matching radio targets in plain text.")
5689 (make-variable-buffer-local 'org-target-link-regexp)
5690 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5691 "Regular expression matching a link target.")
5692 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5693 "Regular expression matching a radio target.")
5694 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5695 "Regular expression matching any target.")
5697 (defun org-activate-target-links (limit)
5698 "Run through the buffer and add overlays to target matches."
5699 (when org-target-link-regexp
5700 (let ((case-fold-search t))
5701 (if (re-search-forward org-target-link-regexp limit t)
5702 (progn
5703 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5704 (add-text-properties (match-beginning 0) (match-end 0)
5705 (list 'mouse-face 'highlight
5706 'keymap org-mouse-map
5707 'help-echo "Radio target link"
5708 'org-linked-text t))
5709 (org-rear-nonsticky-at (match-end 0))
5710 t)))))
5712 (defun org-update-radio-target-regexp ()
5713 "Find all radio targets in this file and update the regular expression."
5714 (interactive)
5715 (when (memq 'radio org-activate-links)
5716 (setq org-target-link-regexp
5717 (org-make-target-link-regexp (org-all-targets 'radio)))
5718 (org-restart-font-lock)))
5720 (defun org-hide-wide-columns (limit)
5721 (let (s e)
5722 (setq s (text-property-any (point) (or limit (point-max))
5723 'org-cwidth t))
5724 (when s
5725 (setq e (next-single-property-change s 'org-cwidth))
5726 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5727 (goto-char e)
5728 t)))
5730 (defvar org-latex-and-specials-regexp nil
5731 "Regular expression for highlighting export special stuff.")
5732 (defvar org-match-substring-regexp)
5733 (defvar org-match-substring-with-braces-regexp)
5735 ;; This should be with the exporter code, but we also use if for font-locking
5736 (defconst org-export-html-special-string-regexps
5737 '(("\\\\-" . "&shy;")
5738 ("---\\([^-]\\)" . "&mdash;\\1")
5739 ("--\\([^-]\\)" . "&ndash;\\1")
5740 ("\\.\\.\\." . "&hellip;"))
5741 "Regular expressions for special string conversion.")
5744 (defun org-compute-latex-and-specials-regexp ()
5745 "Compute regular expression for stuff treated specially by exporters."
5746 (if (not org-highlight-latex-fragments-and-specials)
5747 (org-set-local 'org-latex-and-specials-regexp nil)
5748 (require 'org-exp)
5749 (let*
5750 ((matchers (plist-get org-format-latex-options :matchers))
5751 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5752 org-latex-regexps)))
5753 (org-export-allow-BIND nil)
5754 (options (org-combine-plists (org-default-export-plist)
5755 (org-infile-export-plist)))
5756 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5757 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5758 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5759 (org-export-html-expand (plist-get options :expand-quoted-html))
5760 (org-export-with-special-strings (plist-get options :special-strings))
5761 (re-sub
5762 (cond
5763 ((equal org-export-with-sub-superscripts '{})
5764 (list org-match-substring-with-braces-regexp))
5765 (org-export-with-sub-superscripts
5766 (list org-match-substring-regexp))
5767 (t nil)))
5768 (re-latex
5769 (if org-export-with-LaTeX-fragments
5770 (mapcar (lambda (x) (nth 1 x)) latexs)))
5771 (re-macros
5772 (if org-export-with-TeX-macros
5773 (list (concat "\\\\"
5774 (regexp-opt
5775 (append
5777 (delq nil
5778 (mapcar 'car-safe
5779 (append org-entities-user
5780 org-entities)))
5781 (if (boundp 'org-latex-entities)
5782 (mapcar (lambda (x)
5783 (or (car-safe x) x))
5784 org-latex-entities)
5785 nil))
5786 'words))) ; FIXME
5788 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5789 (re-special (if org-export-with-special-strings
5790 (mapcar (lambda (x) (car x))
5791 org-export-html-special-string-regexps)))
5792 (re-rest
5793 (delq nil
5794 (list
5795 (if org-export-html-expand "@<[^>\n]+>")
5796 ))))
5797 (org-set-local
5798 'org-latex-and-specials-regexp
5799 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5800 re-rest) "\\|")))))
5802 (defun org-do-latex-and-special-faces (limit)
5803 "Run through the buffer and add overlays to links."
5804 (when org-latex-and-specials-regexp
5805 (let (rtn d)
5806 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5807 limit t))
5808 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5809 'face))
5810 '(org-code org-verbatim underline)))
5811 (progn
5812 (setq rtn t
5813 d (cond ((member (char-after (1+ (match-beginning 0)))
5814 '(?_ ?^)) 1)
5815 (t 0)))
5816 (font-lock-prepend-text-property
5817 (+ d (match-beginning 0)) (match-end 0)
5818 'face 'org-latex-and-export-specials)
5819 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5820 '(font-lock-multiline t)))))
5821 rtn)))
5823 (defun org-restart-font-lock ()
5824 "Restart `font-lock-mode', to force refontification."
5825 (when (and (boundp 'font-lock-mode) font-lock-mode)
5826 (font-lock-mode -1)
5827 (font-lock-mode 1)))
5829 (defun org-all-targets (&optional radio)
5830 "Return a list of all targets in this file.
5831 With optional argument RADIO, only find radio targets."
5832 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5833 rtn)
5834 (save-excursion
5835 (goto-char (point-min))
5836 (while (re-search-forward re nil t)
5837 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5838 rtn)))
5840 (defun org-make-target-link-regexp (targets)
5841 "Make regular expression matching all strings in TARGETS.
5842 The regular expression finds the targets also if there is a line break
5843 between words."
5844 (and targets
5845 (concat
5846 "\\<\\("
5847 (mapconcat
5848 (lambda (x)
5849 (setq x (regexp-quote x))
5850 (while (string-match " +" x)
5851 (setq x (replace-match "\\s-+" t t x)))
5853 targets
5854 "\\|")
5855 "\\)\\>")))
5857 (defun org-activate-tags (limit)
5858 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5859 (progn
5860 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5861 (add-text-properties (match-beginning 1) (match-end 1)
5862 (list 'mouse-face 'highlight
5863 'keymap org-mouse-map))
5864 (org-rear-nonsticky-at (match-end 1))
5865 t)))
5867 (defun org-outline-level ()
5868 "Compute the outline level of the heading at point.
5869 This function assumes that the cursor is at the beginning of a line matched
5870 by `outline-regexp'. Otherwise it returns garbage.
5871 If this is called at a normal headline, the level is the number of stars.
5872 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5873 (save-excursion
5874 (looking-at org-outline-regexp)
5875 (1- (- (match-end 0) (match-beginning 0)))))
5877 (defvar org-font-lock-keywords nil)
5879 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5880 "Regular expression matching a property line.")
5882 (defvar org-font-lock-hook nil
5883 "Functions to be called for special font lock stuff.")
5885 (defvar org-font-lock-set-keywords-hook nil
5886 "Functions that can manipulate `org-font-lock-extra-keywords'.
5887 This is called after `org-font-lock-extra-keywords' is defined, but before
5888 it is installed to be used by font lock. This can be useful if something
5889 needs to be inserted at a specific position in the font-lock sequence.")
5891 (defun org-font-lock-hook (limit)
5892 (run-hook-with-args 'org-font-lock-hook limit))
5894 (defun org-set-font-lock-defaults ()
5895 (let* ((em org-fontify-emphasized-text)
5896 (lk org-activate-links)
5897 (org-font-lock-extra-keywords
5898 (list
5899 ;; Call the hook
5900 '(org-font-lock-hook)
5901 ;; Headlines
5902 `(,(if org-fontify-whole-heading-line
5903 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5904 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5905 (1 (org-get-level-face 1))
5906 (2 (org-get-level-face 2))
5907 (3 (org-get-level-face 3)))
5908 ;; Table lines
5909 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5910 (1 'org-table t))
5911 ;; Table internals
5912 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5913 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5914 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5915 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5916 ;; Drawers
5917 (list org-drawer-regexp '(0 'org-special-keyword t))
5918 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5919 ;; Properties
5920 (list org-property-re
5921 '(1 'org-special-keyword t)
5922 '(3 'org-property-value t))
5923 ;; Links
5924 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5925 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5926 (if (memq 'plain lk) '(org-activate-plain-links))
5927 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5928 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5929 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5930 (if (memq 'footnote lk) '(org-activate-footnote-links))
5931 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5932 '(org-hide-wide-columns (0 nil append))
5933 ;; TODO keyword
5934 (list (format org-heading-keyword-regexp-format
5935 org-todo-regexp)
5936 '(2 (org-get-todo-face 2) t))
5937 ;; DONE
5938 (if org-fontify-done-headline
5939 (list (format org-heading-keyword-regexp-format
5940 (concat
5941 "\\(?:"
5942 (mapconcat 'regexp-quote org-done-keywords "\\|")
5943 "\\)"))
5944 '(2 'org-headline-done t))
5945 nil)
5946 ;; Priorities
5947 '(org-font-lock-add-priority-faces)
5948 ;; Tags
5949 '(org-font-lock-add-tag-faces)
5950 ;; Special keywords
5951 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5952 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5953 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5954 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5955 ;; Emphasis
5956 (if em
5957 (if (featurep 'xemacs)
5958 '(org-do-emphasis-faces (0 nil append))
5959 '(org-do-emphasis-faces)))
5960 ;; Checkboxes
5961 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5962 1 'org-checkbox prepend)
5963 (if (cdr (assq 'checkbox org-list-automatic-rules))
5964 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5965 (0 (org-get-checkbox-statistics-face) t)))
5966 ;; Description list items
5967 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5968 1 'org-list-dt prepend)
5969 ;; ARCHIVEd headings
5970 (list (concat
5971 org-outline-regexp-bol
5972 "\\(.*:" org-archive-tag ":.*\\)")
5973 '(1 'org-archived prepend))
5974 ;; Specials
5975 '(org-do-latex-and-special-faces)
5976 '(org-fontify-entities)
5977 '(org-raise-scripts)
5978 ;; Code
5979 '(org-activate-code (1 'org-code t))
5980 ;; COMMENT
5981 (list (format org-heading-keyword-regexp-format
5982 (concat "\\("
5983 org-comment-string "\\|" org-quote-string
5984 "\\)"))
5985 '(2 'org-special-keyword t))
5986 '("^[ \t]*#.*" (0 'font-lock-comment-face t))
5987 ;; Blocks and meta lines
5988 '(org-fontify-meta-lines-and-blocks)
5990 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5991 (run-hooks 'org-font-lock-set-keywords-hook)
5992 ;; Now set the full font-lock-keywords
5993 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5994 (org-set-local 'font-lock-defaults
5995 '(org-font-lock-keywords t nil nil backward-paragraph))
5996 (kill-local-variable 'font-lock-keywords) nil))
5998 (defun org-toggle-pretty-entities ()
5999 "Toggle the composition display of entities as UTF8 characters."
6000 (interactive)
6001 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6002 (org-restart-font-lock)
6003 (if org-pretty-entities
6004 (message "Entities are displayed as UTF8 characters")
6005 (save-restriction
6006 (widen)
6007 (org-decompose-region (point-min) (point-max))
6008 (message "Entities are displayed plain"))))
6010 (defun org-fontify-entities (limit)
6011 "Find an entity to fontify."
6012 (let (ee)
6013 (when org-pretty-entities
6014 (catch 'match
6015 (while (re-search-forward
6016 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6017 limit t)
6018 (if (and (not (org-in-indented-comment-line))
6019 (setq ee (org-entity-get (match-string 1)))
6020 (= (length (nth 6 ee)) 1))
6021 (let*
6022 ((end (if (equal (match-string 2) "{}")
6023 (match-end 2)
6024 (match-end 1))))
6025 (add-text-properties
6026 (match-beginning 0) end
6027 (list 'font-lock-fontified t))
6028 (compose-region (match-beginning 0) end
6029 (nth 6 ee) nil)
6030 (backward-char 1)
6031 (throw 'match t))))
6032 nil))))
6034 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6035 "Fontify string S like in Org-mode."
6036 (with-temp-buffer
6037 (insert s)
6038 (let ((org-odd-levels-only odd-levels))
6039 (org-mode)
6040 (font-lock-fontify-buffer)
6041 (buffer-string))))
6043 (defvar org-m nil)
6044 (defvar org-l nil)
6045 (defvar org-f nil)
6046 (defun org-get-level-face (n)
6047 "Get the right face for match N in font-lock matching of headlines."
6048 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6049 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6050 (if org-cycle-level-faces
6051 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6052 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6053 (cond
6054 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6055 ((eq n 2) org-f)
6056 (t (if org-level-color-stars-only nil org-f))))
6059 (defun org-get-todo-face (kwd)
6060 "Get the right face for a TODO keyword KWD.
6061 If KWD is a number, get the corresponding match group."
6062 (if (numberp kwd) (setq kwd (match-string kwd)))
6063 (or (org-face-from-face-or-color
6064 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6065 (and (member kwd org-done-keywords) 'org-done)
6066 'org-todo))
6068 (defun org-face-from-face-or-color (context inherit face-or-color)
6069 "Create a face list that inherits INHERIT, but sets the foreground color.
6070 When FACE-OR-COLOR is not a string, just return it."
6071 (if (stringp face-or-color)
6072 (list :inherit inherit
6073 (cdr (assoc context org-faces-easy-properties))
6074 face-or-color)
6075 face-or-color))
6077 (defun org-font-lock-add-tag-faces (limit)
6078 "Add the special tag faces."
6079 (when (and org-tag-faces org-tags-special-faces-re)
6080 (while (re-search-forward org-tags-special-faces-re limit t)
6081 (add-text-properties (match-beginning 1) (match-end 1)
6082 (list 'face (org-get-tag-face 1)
6083 'font-lock-fontified t))
6084 (backward-char 1))))
6086 (defun org-font-lock-add-priority-faces (limit)
6087 "Add the special priority faces."
6088 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6089 (when (save-match-data (org-at-heading-p))
6090 (add-text-properties
6091 (match-beginning 0) (match-end 0)
6092 (list 'face (or (org-face-from-face-or-color
6093 'priority 'org-special-keyword
6094 (cdr (assoc (char-after (match-beginning 1))
6095 org-priority-faces)))
6096 'org-special-keyword)
6097 'font-lock-fontified t)))))
6099 (defun org-get-tag-face (kwd)
6100 "Get the right face for a TODO keyword KWD.
6101 If KWD is a number, get the corresponding match group."
6102 (if (numberp kwd) (setq kwd (match-string kwd)))
6103 (or (org-face-from-face-or-color
6104 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6105 'org-tag))
6107 (defun org-unfontify-region (beg end &optional maybe_loudly)
6108 "Remove fontification and activation overlays from links."
6109 (font-lock-default-unfontify-region beg end)
6110 (let* ((buffer-undo-list t)
6111 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6112 (inhibit-modification-hooks t)
6113 deactivate-mark buffer-file-name buffer-file-truename)
6114 (org-decompose-region beg end)
6115 (remove-text-properties beg end
6116 '(mouse-face t keymap t org-linked-text t
6117 invisible t intangible t
6118 org-no-flyspell t org-emphasis t))
6119 (org-remove-font-lock-display-properties beg end)))
6121 (defconst org-script-display '(((raise -0.3) (height 0.7))
6122 ((raise 0.3) (height 0.7))
6123 ((raise -0.5))
6124 ((raise 0.5)))
6125 "Display properties for showing superscripts and subscripts.")
6127 (defun org-remove-font-lock-display-properties (beg end)
6128 "Remove specific display properties that have been added by font lock.
6129 The will remove the raise properties that are used to show superscripts
6130 and subscripts."
6131 (let (next prop)
6132 (while (< beg end)
6133 (setq next (next-single-property-change beg 'display nil end)
6134 prop (get-text-property beg 'display))
6135 (if (member prop org-script-display)
6136 (put-text-property beg next 'display nil))
6137 (setq beg next))))
6139 (defun org-raise-scripts (limit)
6140 "Add raise properties to sub/superscripts."
6141 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6142 (if (re-search-forward
6143 (if (eq org-use-sub-superscripts t)
6144 org-match-substring-regexp
6145 org-match-substring-with-braces-regexp)
6146 limit t)
6147 (let* ((pos (point)) table-p comment-p
6148 (mpos (match-beginning 3))
6149 (emph-p (get-text-property mpos 'org-emphasis))
6150 (link-p (get-text-property mpos 'mouse-face))
6151 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6152 (goto-char (point-at-bol))
6153 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6154 comment-p (org-looking-at-p "[ \t]*#"))
6155 (goto-char pos)
6156 ;; FIXME: Should we go back one character here, for a_b^c
6157 ;; (goto-char (1- pos)) ;????????????????????
6158 (if (or comment-p emph-p link-p keyw-p)
6160 (put-text-property (match-beginning 3) (match-end 0)
6161 'display
6162 (if (equal (char-after (match-beginning 2)) ?^)
6163 (nth (if table-p 3 1) org-script-display)
6164 (nth (if table-p 2 0) org-script-display)))
6165 (add-text-properties (match-beginning 2) (match-end 2)
6166 (list 'invisible t
6167 'org-dwidth t 'org-dwidth-n 1))
6168 (if (and (eq (char-after (match-beginning 3)) ?{)
6169 (eq (char-before (match-end 3)) ?}))
6170 (progn
6171 (add-text-properties
6172 (match-beginning 3) (1+ (match-beginning 3))
6173 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6174 (add-text-properties
6175 (1- (match-end 3)) (match-end 3)
6176 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6177 t)))))
6179 ;;;; Visibility cycling, including org-goto and indirect buffer
6181 ;;; Cycling
6183 (defvar org-cycle-global-status nil)
6184 (make-variable-buffer-local 'org-cycle-global-status)
6185 (defvar org-cycle-subtree-status nil)
6186 (make-variable-buffer-local 'org-cycle-subtree-status)
6188 ;;;###autoload
6190 (defvar org-inlinetask-min-level)
6192 (defun org-cycle (&optional arg)
6193 "TAB-action and visibility cycling for Org-mode.
6195 This is the command invoked in Org-mode by the TAB key. Its main purpose
6196 is outline visibility cycling, but it also invokes other actions
6197 in special contexts.
6199 - When this function is called with a prefix argument, rotate the entire
6200 buffer through 3 states (global cycling)
6201 1. OVERVIEW: Show only top-level headlines.
6202 2. CONTENTS: Show all headlines of all levels, but no body text.
6203 3. SHOW ALL: Show everything.
6204 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6205 determined by the variable `org-startup-folded', and by any VISIBILITY
6206 properties in the buffer.
6207 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6208 including any drawers.
6210 - When inside a table, re-align the table and move to the next field.
6212 - When point is at the beginning of a headline, rotate the subtree started
6213 by this line through 3 different states (local cycling)
6214 1. FOLDED: Only the main headline is shown.
6215 2. CHILDREN: The main headline and the direct children are shown.
6216 From this state, you can move to one of the children
6217 and zoom in further.
6218 3. SUBTREE: Show the entire subtree, including body text.
6219 If there is no subtree, switch directly from CHILDREN to FOLDED.
6221 - When point is at the beginning of an empty headline and the variable
6222 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6223 of the headline by demoting and promoting it to likely levels. This
6224 speeds up creation document structure by pressing TAB once or several
6225 times right after creating a new headline.
6227 - When there is a numeric prefix, go up to a heading with level ARG, do
6228 a `show-subtree' and return to the previous cursor position. If ARG
6229 is negative, go up that many levels.
6231 - When point is not at the beginning of a headline, execute the global
6232 binding for TAB, which is re-indenting the line. See the option
6233 `org-cycle-emulate-tab' for details.
6235 - Special case: if point is at the beginning of the buffer and there is
6236 no headline in line 1, this function will act as if called with prefix arg
6237 (C-u TAB, same as S-TAB) also when called without prefix arg.
6238 But only if also the variable `org-cycle-global-at-bob' is t."
6239 (interactive "P")
6240 (org-load-modules-maybe)
6241 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6242 (and org-cycle-level-after-item/entry-creation
6243 (or (org-cycle-level)
6244 (org-cycle-item-indentation))))
6245 (let* ((limit-level
6246 (or org-cycle-max-level
6247 (and (boundp 'org-inlinetask-min-level)
6248 org-inlinetask-min-level
6249 (1- org-inlinetask-min-level))))
6250 (nstars (and limit-level
6251 (if org-odd-levels-only
6252 (and limit-level (1- (* limit-level 2)))
6253 limit-level)))
6254 (org-outline-regexp
6255 (if (not (derived-mode-p 'org-mode))
6256 outline-regexp
6257 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6258 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6259 (not (looking-at org-outline-regexp))))
6260 (org-cycle-hook
6261 (if bob-special
6262 (delq 'org-optimize-window-after-visibility-change
6263 (copy-sequence org-cycle-hook))
6264 org-cycle-hook))
6265 (pos (point)))
6267 (if (or bob-special (equal arg '(4)))
6268 ;; special case: use global cycling
6269 (setq arg t))
6271 (cond
6273 ((equal arg '(16))
6274 (setq last-command 'dummy)
6275 (org-set-startup-visibility)
6276 (message "Startup visibility, plus VISIBILITY properties"))
6278 ((equal arg '(64))
6279 (show-all)
6280 (message "Entire buffer visible, including drawers"))
6282 ;; Table: enter it or move to the next field.
6283 ((org-at-table-p 'any)
6284 (if (org-at-table.el-p)
6285 (message "Use C-c ' to edit table.el tables")
6286 (if arg (org-table-edit-field t)
6287 (org-table-justify-field-maybe)
6288 (call-interactively 'org-table-next-field))))
6290 ((run-hook-with-args-until-success
6291 'org-tab-after-check-for-table-hook))
6293 ;; Global cycling: delegate to `org-cycle-internal-global'.
6294 ((eq arg t) (org-cycle-internal-global))
6296 ;; Drawers: delegate to `org-flag-drawer'.
6297 ((and org-drawers org-drawer-regexp
6298 (save-excursion
6299 (beginning-of-line 1)
6300 (looking-at org-drawer-regexp)))
6301 (org-flag-drawer ; toggle block visibility
6302 (not (get-char-property (match-end 0) 'invisible))))
6304 ;; Show-subtree, ARG levels up from here.
6305 ((integerp arg)
6306 (save-excursion
6307 (org-back-to-heading)
6308 (outline-up-heading (if (< arg 0) (- arg)
6309 (- (funcall outline-level) arg)))
6310 (org-show-subtree)))
6312 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6313 ((and (featurep 'org-inlinetask)
6314 (org-inlinetask-at-task-p)
6315 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6316 (org-inlinetask-toggle-visibility))
6318 ((org-try-cdlatex-tab))
6320 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6321 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6322 (save-excursion (beginning-of-line 1)
6323 (looking-at org-outline-regexp)))
6324 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6325 (org-cycle-internal-local))
6327 ;; From there: TAB emulation and template completion.
6328 (buffer-read-only (org-back-to-heading))
6330 ((run-hook-with-args-until-success
6331 'org-tab-after-check-for-cycling-hook))
6333 ((org-try-structure-completion))
6335 ((run-hook-with-args-until-success
6336 'org-tab-before-tab-emulation-hook))
6338 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6339 (or (not (bolp))
6340 (not (looking-at org-outline-regexp))))
6341 (call-interactively (global-key-binding "\t")))
6343 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6344 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6345 (or (and (eq org-cycle-emulate-tab 'white)
6346 (= (match-end 0) (point-at-eol)))
6347 (and (eq org-cycle-emulate-tab 'whitestart)
6348 (>= (match-end 0) pos))))
6350 (eq org-cycle-emulate-tab t))
6351 (call-interactively (global-key-binding "\t")))
6353 (t (save-excursion
6354 (org-back-to-heading)
6355 (org-cycle)))))))
6357 (defun org-cycle-internal-global ()
6358 "Do the global cycling action."
6359 ;; Hack to avoid display of messages for .org attachments in Gnus
6360 (let ((ga (string-match "\\*fontification" (buffer-name))))
6361 (cond
6362 ((and (eq last-command this-command)
6363 (eq org-cycle-global-status 'overview))
6364 ;; We just created the overview - now do table of contents
6365 ;; This can be slow in very large buffers, so indicate action
6366 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6367 (unless ga (message "CONTENTS..."))
6368 (org-content)
6369 (unless ga (message "CONTENTS...done"))
6370 (setq org-cycle-global-status 'contents)
6371 (run-hook-with-args 'org-cycle-hook 'contents))
6373 ((and (eq last-command this-command)
6374 (eq org-cycle-global-status 'contents))
6375 ;; We just showed the table of contents - now show everything
6376 (run-hook-with-args 'org-pre-cycle-hook 'all)
6377 (show-all)
6378 (unless ga (message "SHOW ALL"))
6379 (setq org-cycle-global-status 'all)
6380 (run-hook-with-args 'org-cycle-hook 'all))
6383 ;; Default action: go to overview
6384 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6385 (org-overview)
6386 (unless ga (message "OVERVIEW"))
6387 (setq org-cycle-global-status 'overview)
6388 (run-hook-with-args 'org-cycle-hook 'overview)))))
6390 (defun org-cycle-internal-local ()
6391 "Do the local cycling action."
6392 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6393 ;; First, determine end of headline (EOH), end of subtree or item
6394 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6395 (save-excursion
6396 (if (org-at-item-p)
6397 (progn
6398 (beginning-of-line)
6399 (setq struct (org-list-struct))
6400 (setq eoh (point-at-eol))
6401 (setq eos (org-list-get-item-end-before-blank (point) struct))
6402 (setq has-children (org-list-has-child-p (point) struct)))
6403 (org-back-to-heading)
6404 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6405 (setq eos (save-excursion
6406 (org-end-of-subtree t)
6407 (unless (eobp)
6408 (skip-chars-forward " \t\n"))
6409 (if (eobp) (point) (1- (point)))))
6410 (setq has-children
6411 (or (save-excursion
6412 (let ((level (funcall outline-level)))
6413 (outline-next-heading)
6414 (and (org-at-heading-p t)
6415 (> (funcall outline-level) level))))
6416 (save-excursion
6417 (org-list-search-forward (org-item-beginning-re) eos t)))))
6418 ;; Determine end invisible part of buffer (EOL)
6419 (beginning-of-line 2)
6420 ;; XEmacs doesn't have `next-single-char-property-change'
6421 (if (featurep 'xemacs)
6422 (while (and (not (eobp)) ;; this is like `next-line'
6423 (get-char-property (1- (point)) 'invisible))
6424 (beginning-of-line 2))
6425 (while (and (not (eobp)) ;; this is like `next-line'
6426 (get-char-property (1- (point)) 'invisible))
6427 (goto-char (next-single-char-property-change (point) 'invisible))
6428 (and (eolp) (beginning-of-line 2))))
6429 (setq eol (point)))
6430 ;; Find out what to do next and set `this-command'
6431 (cond
6432 ((= eos eoh)
6433 ;; Nothing is hidden behind this heading
6434 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6435 (message "EMPTY ENTRY")
6436 (setq org-cycle-subtree-status nil)
6437 (save-excursion
6438 (goto-char eos)
6439 (outline-next-heading)
6440 (if (outline-invisible-p) (org-flag-heading nil))))
6441 ((and (or (>= eol eos)
6442 (not (string-match "\\S-" (buffer-substring eol eos))))
6443 (or has-children
6444 (not (setq children-skipped
6445 org-cycle-skip-children-state-if-no-children))))
6446 ;; Entire subtree is hidden in one line: children view
6447 (run-hook-with-args 'org-pre-cycle-hook 'children)
6448 (if (org-at-item-p)
6449 (org-list-set-item-visibility (point-at-bol) struct 'children)
6450 (org-show-entry)
6451 (org-with-limited-levels (show-children))
6452 ;; FIXME: This slows down the func way too much.
6453 ;; How keep drawers hidden in subtree anyway?
6454 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6455 ;; (org-cycle-hide-drawers 'subtree))
6457 ;; Fold every list in subtree to top-level items.
6458 (when (eq org-cycle-include-plain-lists 'integrate)
6459 (save-excursion
6460 (org-back-to-heading)
6461 (while (org-list-search-forward (org-item-beginning-re) eos t)
6462 (beginning-of-line 1)
6463 (let* ((struct (org-list-struct))
6464 (prevs (org-list-prevs-alist struct))
6465 (end (org-list-get-bottom-point struct)))
6466 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6467 (org-list-get-all-items (point) struct prevs))
6468 (goto-char end))))))
6469 (message "CHILDREN")
6470 (save-excursion
6471 (goto-char eos)
6472 (outline-next-heading)
6473 (if (outline-invisible-p) (org-flag-heading nil)))
6474 (setq org-cycle-subtree-status 'children)
6475 (run-hook-with-args 'org-cycle-hook 'children))
6476 ((or children-skipped
6477 (and (eq last-command this-command)
6478 (eq org-cycle-subtree-status 'children)))
6479 ;; We just showed the children, or no children are there,
6480 ;; now show everything.
6481 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6482 (outline-flag-region eoh eos nil)
6483 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6484 (setq org-cycle-subtree-status 'subtree)
6485 (run-hook-with-args 'org-cycle-hook 'subtree))
6487 ;; Default action: hide the subtree.
6488 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6489 (outline-flag-region eoh eos t)
6490 (message "FOLDED")
6491 (setq org-cycle-subtree-status 'folded)
6492 (run-hook-with-args 'org-cycle-hook 'folded)))))
6494 ;;;###autoload
6495 (defun org-global-cycle (&optional arg)
6496 "Cycle the global visibility. For details see `org-cycle'.
6497 With \\[universal-argument] prefix arg, switch to startup visibility.
6498 With a numeric prefix, show all headlines up to that level."
6499 (interactive "P")
6500 (let ((org-cycle-include-plain-lists
6501 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6502 (cond
6503 ((integerp arg)
6504 (show-all)
6505 (hide-sublevels arg)
6506 (setq org-cycle-global-status 'contents))
6507 ((equal arg '(4))
6508 (org-set-startup-visibility)
6509 (message "Startup visibility, plus VISIBILITY properties."))
6511 (org-cycle '(4))))))
6513 (defun org-set-startup-visibility ()
6514 "Set the visibility required by startup options and properties."
6515 (cond
6516 ((eq org-startup-folded t)
6517 (org-cycle '(4)))
6518 ((eq org-startup-folded 'content)
6519 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6520 (org-cycle '(4)) (org-cycle '(4)))))
6521 (unless (eq org-startup-folded 'showeverything)
6522 (if org-hide-block-startup (org-hide-block-all))
6523 (org-set-visibility-according-to-property 'no-cleanup)
6524 (org-cycle-hide-archived-subtrees 'all)
6525 (org-cycle-hide-drawers 'all)
6526 (org-cycle-show-empty-lines t)))
6528 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6529 "Switch subtree visibilities according to :VISIBILITY: property."
6530 (interactive)
6531 (let (org-show-entry-below state)
6532 (save-excursion
6533 (goto-char (point-min))
6534 (while (re-search-forward
6535 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6536 nil t)
6537 (setq state (match-string 1))
6538 (save-excursion
6539 (org-back-to-heading t)
6540 (hide-subtree)
6541 (org-reveal)
6542 (cond
6543 ((equal state '("fold" "folded"))
6544 (hide-subtree))
6545 ((equal state "children")
6546 (org-show-hidden-entry)
6547 (show-children))
6548 ((equal state "content")
6549 (save-excursion
6550 (save-restriction
6551 (org-narrow-to-subtree)
6552 (org-content))))
6553 ((member state '("all" "showall"))
6554 (show-subtree)))))
6555 (unless no-cleanup
6556 (org-cycle-hide-archived-subtrees 'all)
6557 (org-cycle-hide-drawers 'all)
6558 (org-cycle-show-empty-lines 'all)))))
6560 ;; This function uses outline-regexp instead of the more fundamental
6561 ;; org-outline-regexp so that org-cycle-global works outside of Org
6562 ;; buffers, where outline-regexp is needed.
6563 (defun org-overview ()
6564 "Switch to overview mode, showing only top-level headlines.
6565 Really, this shows all headlines with level equal or greater than the level
6566 of the first headline in the buffer. This is important, because if the
6567 first headline is not level one, then (hide-sublevels 1) gives confusing
6568 results."
6569 (interactive)
6570 (let ((level (save-excursion
6571 (goto-char (point-min))
6572 (if (re-search-forward (concat "^" outline-regexp) nil t)
6573 (progn
6574 (goto-char (match-beginning 0))
6575 (funcall outline-level))))))
6576 (and level (hide-sublevels level))))
6578 (defun org-content (&optional arg)
6579 "Show all headlines in the buffer, like a table of contents.
6580 With numerical argument N, show content up to level N."
6581 (interactive "P")
6582 (save-excursion
6583 ;; Visit all headings and show their offspring
6584 (and (integerp arg) (org-overview))
6585 (goto-char (point-max))
6586 (catch 'exit
6587 (while (and (progn (condition-case nil
6588 (outline-previous-visible-heading 1)
6589 (error (goto-char (point-min))))
6591 (looking-at org-outline-regexp))
6592 (if (integerp arg)
6593 (show-children (1- arg))
6594 (show-branches))
6595 (if (bobp) (throw 'exit nil))))))
6598 (defun org-optimize-window-after-visibility-change (state)
6599 "Adjust the window after a change in outline visibility.
6600 This function is the default value of the hook `org-cycle-hook'."
6601 (when (get-buffer-window (current-buffer))
6602 (cond
6603 ((eq state 'content) nil)
6604 ((eq state 'all) nil)
6605 ((eq state 'folded) nil)
6606 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6607 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6609 (defun org-remove-empty-overlays-at (pos)
6610 "Remove outline overlays that do not contain non-white stuff."
6611 (mapc
6612 (lambda (o)
6613 (and (eq 'outline (overlay-get o 'invisible))
6614 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6615 (overlay-end o))))
6616 (delete-overlay o)))
6617 (overlays-at pos)))
6619 (defun org-clean-visibility-after-subtree-move ()
6620 "Fix visibility issues after moving a subtree."
6621 ;; First, find a reasonable region to look at:
6622 ;; Start two siblings above, end three below
6623 (let* ((beg (save-excursion
6624 (and (org-get-last-sibling)
6625 (org-get-last-sibling))
6626 (point)))
6627 (end (save-excursion
6628 (and (org-get-next-sibling)
6629 (org-get-next-sibling)
6630 (org-get-next-sibling))
6631 (if (org-at-heading-p)
6632 (point-at-eol)
6633 (point))))
6634 (level (looking-at "\\*+"))
6635 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6636 (save-excursion
6637 (save-restriction
6638 (narrow-to-region beg end)
6639 (when re
6640 ;; Properly fold already folded siblings
6641 (goto-char (point-min))
6642 (while (re-search-forward re nil t)
6643 (if (and (not (outline-invisible-p))
6644 (save-excursion
6645 (goto-char (point-at-eol)) (outline-invisible-p)))
6646 (hide-entry))))
6647 (org-cycle-show-empty-lines 'overview)
6648 (org-cycle-hide-drawers 'overview)))))
6650 (defun org-cycle-show-empty-lines (state)
6651 "Show empty lines above all visible headlines.
6652 The region to be covered depends on STATE when called through
6653 `org-cycle-hook'. Lisp program can use t for STATE to get the
6654 entire buffer covered. Note that an empty line is only shown if there
6655 are at least `org-cycle-separator-lines' empty lines before the headline."
6656 (when (not (= org-cycle-separator-lines 0))
6657 (save-excursion
6658 (let* ((n (abs org-cycle-separator-lines))
6659 (re (cond
6660 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6661 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6662 (t (let ((ns (number-to-string (- n 2))))
6663 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6664 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6665 beg end b e)
6666 (cond
6667 ((memq state '(overview contents t))
6668 (setq beg (point-min) end (point-max)))
6669 ((memq state '(children folded))
6670 (setq beg (point) end (progn (org-end-of-subtree t t)
6671 (beginning-of-line 2)
6672 (point)))))
6673 (when beg
6674 (goto-char beg)
6675 (while (re-search-forward re end t)
6676 (unless (get-char-property (match-end 1) 'invisible)
6677 (setq e (match-end 1))
6678 (if (< org-cycle-separator-lines 0)
6679 (setq b (save-excursion
6680 (goto-char (match-beginning 0))
6681 (org-back-over-empty-lines)
6682 (if (save-excursion
6683 (goto-char (max (point-min) (1- (point))))
6684 (org-at-heading-p))
6685 (1- (point))
6686 (point))))
6687 (setq b (match-beginning 1)))
6688 (outline-flag-region b e nil)))))))
6689 ;; Never hide empty lines at the end of the file.
6690 (save-excursion
6691 (goto-char (point-max))
6692 (outline-previous-heading)
6693 (outline-end-of-heading)
6694 (if (and (looking-at "[ \t\n]+")
6695 (= (match-end 0) (point-max)))
6696 (outline-flag-region (point) (match-end 0) nil))))
6698 (defun org-show-empty-lines-in-parent ()
6699 "Move to the parent and re-show empty lines before visible headlines."
6700 (save-excursion
6701 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6702 (org-cycle-show-empty-lines context))))
6704 (defun org-files-list ()
6705 "Return `org-agenda-files' list, plus all open org-mode files.
6706 This is useful for operations that need to scan all of a user's
6707 open and agenda-wise Org files."
6708 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6709 (dolist (buf (buffer-list))
6710 (with-current-buffer buf
6711 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6712 (let ((file (expand-file-name (buffer-file-name))))
6713 (unless (member file files)
6714 (push file files))))))
6715 files))
6717 (defsubst org-entry-beginning-position ()
6718 "Return the beginning position of the current entry."
6719 (save-excursion (outline-back-to-heading t) (point)))
6721 (defsubst org-entry-end-position ()
6722 "Return the end position of the current entry."
6723 (save-excursion (outline-next-heading) (point)))
6725 (defun org-cycle-hide-drawers (state)
6726 "Re-hide all drawers after a visibility state change."
6727 (when (and (derived-mode-p 'org-mode)
6728 (not (memq state '(overview folded contents))))
6729 (save-excursion
6730 (let* ((globalp (memq state '(contents all)))
6731 (beg (if globalp (point-min) (point)))
6732 (end (if globalp (point-max)
6733 (if (eq state 'children)
6734 (save-excursion (outline-next-heading) (point))
6735 (org-end-of-subtree t)))))
6736 (goto-char beg)
6737 (while (re-search-forward org-drawer-regexp end t)
6738 (org-flag-drawer t))))))
6740 (defun org-flag-drawer (flag)
6741 "When FLAG is non-nil, hide the drawer we are within.
6742 Otherwise make it visible."
6743 (save-excursion
6744 (beginning-of-line 1)
6745 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6746 (let ((b (match-end 0)))
6747 (if (re-search-forward
6748 "^[ \t]*:END:"
6749 (save-excursion (outline-next-heading) (point)) t)
6750 (outline-flag-region b (point-at-eol) flag)
6751 (error ":END: line missing at position %s" b))))))
6753 (defun org-subtree-end-visible-p ()
6754 "Is the end of the current subtree visible?"
6755 (pos-visible-in-window-p
6756 (save-excursion (org-end-of-subtree t) (point))))
6758 (defun org-first-headline-recenter (&optional N)
6759 "Move cursor to the first headline and recenter the headline.
6760 Optional argument N means put the headline into the Nth line of the window."
6761 (goto-char (point-min))
6762 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6763 (beginning-of-line)
6764 (recenter (prefix-numeric-value N))))
6766 ;;; Saving and restoring visibility
6768 (defun org-outline-overlay-data (&optional use-markers)
6769 "Return a list of the locations of all outline overlays.
6770 These are overlays with the `invisible' property value `outline'.
6771 The return value is a list of cons cells, with start and stop
6772 positions for each overlay.
6773 If USE-MARKERS is set, return the positions as markers."
6774 (let (beg end)
6775 (save-excursion
6776 (save-restriction
6777 (widen)
6778 (delq nil
6779 (mapcar (lambda (o)
6780 (when (eq (overlay-get o 'invisible) 'outline)
6781 (setq beg (overlay-start o)
6782 end (overlay-end o))
6783 (and beg end (> end beg)
6784 (if use-markers
6785 (cons (move-marker (make-marker) beg)
6786 (move-marker (make-marker) end))
6787 (cons beg end)))))
6788 (overlays-in (point-min) (point-max))))))))
6790 (defun org-set-outline-overlay-data (data)
6791 "Create visibility overlays for all positions in DATA.
6792 DATA should have been made by `org-outline-overlay-data'."
6793 (let (o)
6794 (save-excursion
6795 (save-restriction
6796 (widen)
6797 (show-all)
6798 (mapc (lambda (c)
6799 (outline-flag-region (car c) (cdr c) t))
6800 data)))))
6802 ;;; Folding of blocks
6804 (defvar org-hide-block-overlays nil
6805 "Overlays hiding blocks.")
6806 (make-variable-buffer-local 'org-hide-block-overlays)
6808 (defun org-block-map (function &optional start end)
6809 "Call FUNCTION at the head of all source blocks in the current buffer.
6810 Optional arguments START and END can be used to limit the range."
6811 (let ((start (or start (point-min)))
6812 (end (or end (point-max))))
6813 (save-excursion
6814 (goto-char start)
6815 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6816 (save-excursion
6817 (save-match-data
6818 (goto-char (match-beginning 0))
6819 (funcall function)))))))
6821 (defun org-hide-block-toggle-all ()
6822 "Toggle the visibility of all blocks in the current buffer."
6823 (org-block-map #'org-hide-block-toggle))
6825 (defun org-hide-block-all ()
6826 "Fold all blocks in the current buffer."
6827 (interactive)
6828 (org-show-block-all)
6829 (org-block-map #'org-hide-block-toggle-maybe))
6831 (defun org-show-block-all ()
6832 "Unfold all blocks in the current buffer."
6833 (interactive)
6834 (mapc 'delete-overlay org-hide-block-overlays)
6835 (setq org-hide-block-overlays nil))
6837 (defun org-hide-block-toggle-maybe ()
6838 "Toggle visibility of block at point."
6839 (interactive)
6840 (let ((case-fold-search t))
6841 (if (save-excursion
6842 (beginning-of-line 1)
6843 (looking-at org-block-regexp))
6844 (progn (org-hide-block-toggle)
6845 t) ;; to signal that we took action
6846 nil))) ;; to signal that we did not
6848 (defun org-hide-block-toggle (&optional force)
6849 "Toggle the visibility of the current block."
6850 (interactive)
6851 (save-excursion
6852 (beginning-of-line)
6853 (if (re-search-forward org-block-regexp nil t)
6854 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6855 (end (match-end 0)) ;; end of entire body
6857 (if (memq t (mapcar (lambda (overlay)
6858 (eq (overlay-get overlay 'invisible)
6859 'org-hide-block))
6860 (overlays-at start)))
6861 (if (or (not force) (eq force 'off))
6862 (mapc (lambda (ov)
6863 (when (member ov org-hide-block-overlays)
6864 (setq org-hide-block-overlays
6865 (delq ov org-hide-block-overlays)))
6866 (when (eq (overlay-get ov 'invisible)
6867 'org-hide-block)
6868 (delete-overlay ov)))
6869 (overlays-at start)))
6870 (setq ov (make-overlay start end))
6871 (overlay-put ov 'invisible 'org-hide-block)
6872 ;; make the block accessible to isearch
6873 (overlay-put
6874 ov 'isearch-open-invisible
6875 (lambda (ov)
6876 (when (member ov org-hide-block-overlays)
6877 (setq org-hide-block-overlays
6878 (delq ov org-hide-block-overlays)))
6879 (when (eq (overlay-get ov 'invisible)
6880 'org-hide-block)
6881 (delete-overlay ov))))
6882 (push ov org-hide-block-overlays)))
6883 (error "Not looking at a source block"))))
6885 ;; org-tab-after-check-for-cycling-hook
6886 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6887 ;; Remove overlays when changing major mode
6888 (add-hook 'org-mode-hook
6889 (lambda () (org-add-hook 'change-major-mode-hook
6890 'org-show-block-all 'append 'local)))
6892 ;;; Org-goto
6894 (defvar org-goto-window-configuration nil)
6895 (defvar org-goto-marker nil)
6896 (defvar org-goto-map
6897 (let ((map (make-sparse-keymap)))
6898 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6899 (while (setq cmd (pop cmds))
6900 (substitute-key-definition cmd cmd map global-map)))
6901 (suppress-keymap map)
6902 (org-defkey map "\C-m" 'org-goto-ret)
6903 (org-defkey map [(return)] 'org-goto-ret)
6904 (org-defkey map [(left)] 'org-goto-left)
6905 (org-defkey map [(right)] 'org-goto-right)
6906 (org-defkey map [(control ?g)] 'org-goto-quit)
6907 (org-defkey map "\C-i" 'org-cycle)
6908 (org-defkey map [(tab)] 'org-cycle)
6909 (org-defkey map [(down)] 'outline-next-visible-heading)
6910 (org-defkey map [(up)] 'outline-previous-visible-heading)
6911 (if org-goto-auto-isearch
6912 (if (fboundp 'define-key-after)
6913 (define-key-after map [t] 'org-goto-local-auto-isearch)
6914 nil)
6915 (org-defkey map "q" 'org-goto-quit)
6916 (org-defkey map "n" 'outline-next-visible-heading)
6917 (org-defkey map "p" 'outline-previous-visible-heading)
6918 (org-defkey map "f" 'outline-forward-same-level)
6919 (org-defkey map "b" 'outline-backward-same-level)
6920 (org-defkey map "u" 'outline-up-heading))
6921 (org-defkey map "/" 'org-occur)
6922 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6923 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6924 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6925 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6926 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6927 map))
6929 (defconst org-goto-help
6930 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6931 RET=jump to location [Q]uit and return to previous location
6932 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6934 (defvar org-goto-start-pos) ; dynamically scoped parameter
6936 ;; FIXME: Docstring does not mention both interfaces
6937 (defun org-goto (&optional alternative-interface)
6938 "Look up a different location in the current file, keeping current visibility.
6940 When you want look-up or go to a different location in a
6941 document, the fastest way is often to fold the entire buffer and
6942 then dive into the tree. This method has the disadvantage, that
6943 the previous location will be folded, which may not be what you
6944 want.
6946 This command works around this by showing a copy of the current
6947 buffer in an indirect buffer, in overview mode. You can dive
6948 into the tree in that copy, use org-occur and incremental search
6949 to find a location. When pressing RET or `Q', the command
6950 returns to the original buffer in which the visibility is still
6951 unchanged. After RET it will also jump to the location selected
6952 in the indirect buffer and expose the headline hierarchy above.
6954 With a prefix argument, use the alternative interface: e.g. if
6955 `org-goto-interface' is 'outline use 'outline-path-completion."
6956 (interactive "P")
6957 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6958 (org-refile-use-outline-path t)
6959 (org-refile-target-verify-function nil)
6960 (interface
6961 (if (not alternative-interface)
6962 org-goto-interface
6963 (if (eq org-goto-interface 'outline)
6964 'outline-path-completion
6965 'outline)))
6966 (org-goto-start-pos (point))
6967 (selected-point
6968 (if (eq interface 'outline)
6969 (car (org-get-location (current-buffer) org-goto-help))
6970 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6971 (org-refile-check-position pa)
6972 (nth 3 pa)))))
6973 (if selected-point
6974 (progn
6975 (org-mark-ring-push org-goto-start-pos)
6976 (goto-char selected-point)
6977 (if (or (outline-invisible-p) (org-invisible-p2))
6978 (org-show-context 'org-goto)))
6979 (message "Quit"))))
6981 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6982 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6983 (defvar org-goto-local-auto-isearch-map) ; defined below
6985 (defun org-get-location (buf help)
6986 "Let the user select a location in the Org-mode buffer BUF.
6987 This function uses a recursive edit. It returns the selected position
6988 or nil."
6989 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6990 (isearch-hide-immediately nil)
6991 (isearch-search-fun-function
6992 (lambda () 'org-goto-local-search-headings))
6993 (org-goto-selected-point org-goto-exit-command)
6994 (pop-up-frames nil)
6995 (special-display-buffer-names nil)
6996 (special-display-regexps nil)
6997 (special-display-function nil))
6998 (save-excursion
6999 (save-window-excursion
7000 (delete-other-windows)
7001 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7002 (org-pop-to-buffer-same-window
7003 (condition-case nil
7004 (make-indirect-buffer (current-buffer) "*org-goto*")
7005 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7006 (with-output-to-temp-buffer "*Help*"
7007 (princ help))
7008 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7009 (setq buffer-read-only nil)
7010 (let ((org-startup-truncated t)
7011 (org-startup-folded nil)
7012 (org-startup-align-all-tables nil))
7013 (org-mode)
7014 (org-overview))
7015 (setq buffer-read-only t)
7016 (if (and (boundp 'org-goto-start-pos)
7017 (integer-or-marker-p org-goto-start-pos))
7018 (let ((org-show-hierarchy-above t)
7019 (org-show-siblings t)
7020 (org-show-following-heading t))
7021 (goto-char org-goto-start-pos)
7022 (and (outline-invisible-p) (org-show-context)))
7023 (goto-char (point-min)))
7024 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7025 (message "Select location and press RET")
7026 (use-local-map org-goto-map)
7027 (recursive-edit)
7029 (kill-buffer "*org-goto*")
7030 (cons org-goto-selected-point org-goto-exit-command)))
7032 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7033 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7034 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7035 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7037 (defun org-goto-local-search-headings (string bound noerror)
7038 "Search and make sure that any matches are in headlines."
7039 (catch 'return
7040 (while (if isearch-forward
7041 (search-forward string bound noerror)
7042 (search-backward string bound noerror))
7043 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7044 (and (member :headline context)
7045 (not (member :tags context))))
7046 (throw 'return (point))))))
7048 (defun org-goto-local-auto-isearch ()
7049 "Start isearch."
7050 (interactive)
7051 (goto-char (point-min))
7052 (let ((keys (this-command-keys)))
7053 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7054 (isearch-mode t)
7055 (isearch-process-search-char (string-to-char keys)))))
7057 (defun org-goto-ret (&optional arg)
7058 "Finish `org-goto' by going to the new location."
7059 (interactive "P")
7060 (setq org-goto-selected-point (point)
7061 org-goto-exit-command 'return)
7062 (throw 'exit nil))
7064 (defun org-goto-left ()
7065 "Finish `org-goto' by going to the new location."
7066 (interactive)
7067 (if (org-at-heading-p)
7068 (progn
7069 (beginning-of-line 1)
7070 (setq org-goto-selected-point (point)
7071 org-goto-exit-command 'left)
7072 (throw 'exit nil))
7073 (error "Not on a heading")))
7075 (defun org-goto-right ()
7076 "Finish `org-goto' by going to the new location."
7077 (interactive)
7078 (if (org-at-heading-p)
7079 (progn
7080 (setq org-goto-selected-point (point)
7081 org-goto-exit-command 'right)
7082 (throw 'exit nil))
7083 (error "Not on a heading")))
7085 (defun org-goto-quit ()
7086 "Finish `org-goto' without cursor motion."
7087 (interactive)
7088 (setq org-goto-selected-point nil)
7089 (setq org-goto-exit-command 'quit)
7090 (throw 'exit nil))
7092 ;;; Indirect buffer display of subtrees
7094 (defvar org-indirect-dedicated-frame nil
7095 "This is the frame being used for indirect tree display.")
7096 (defvar org-last-indirect-buffer nil)
7098 (defun org-tree-to-indirect-buffer (&optional arg)
7099 "Create indirect buffer and narrow it to current subtree.
7100 With numerical prefix ARG, go up to this level and then take that tree.
7101 If ARG is negative, go up that many levels.
7102 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7103 indirect buffer previously made with this command, to avoid proliferation of
7104 indirect buffers. However, when you call the command with a \
7105 \\[universal-argument] prefix, or
7106 when `org-indirect-buffer-display' is `new-frame', the last buffer
7107 is kept so that you can work with several indirect buffers at the same time.
7108 If `org-indirect-buffer-display' is `dedicated-frame', the \
7109 \\[universal-argument] prefix also
7110 requests that a new frame be made for the new buffer, so that the dedicated
7111 frame is not changed."
7112 (interactive "P")
7113 (let ((cbuf (current-buffer))
7114 (cwin (selected-window))
7115 (pos (point))
7116 beg end level heading ibuf)
7117 (save-excursion
7118 (org-back-to-heading t)
7119 (when (numberp arg)
7120 (setq level (org-outline-level))
7121 (if (< arg 0) (setq arg (+ level arg)))
7122 (while (> (setq level (org-outline-level)) arg)
7123 (outline-up-heading 1 t)))
7124 (setq beg (point)
7125 heading (org-get-heading))
7126 (org-end-of-subtree t t)
7127 (if (org-at-heading-p) (backward-char 1))
7128 (setq end (point)))
7129 (if (and (buffer-live-p org-last-indirect-buffer)
7130 (not (eq org-indirect-buffer-display 'new-frame))
7131 (not arg))
7132 (kill-buffer org-last-indirect-buffer))
7133 (setq ibuf (org-get-indirect-buffer cbuf)
7134 org-last-indirect-buffer ibuf)
7135 (cond
7136 ((or (eq org-indirect-buffer-display 'new-frame)
7137 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7138 (select-frame (make-frame))
7139 (delete-other-windows)
7140 (org-pop-to-buffer-same-window ibuf)
7141 (org-set-frame-title heading))
7142 ((eq org-indirect-buffer-display 'dedicated-frame)
7143 (raise-frame
7144 (select-frame (or (and org-indirect-dedicated-frame
7145 (frame-live-p org-indirect-dedicated-frame)
7146 org-indirect-dedicated-frame)
7147 (setq org-indirect-dedicated-frame (make-frame)))))
7148 (delete-other-windows)
7149 (org-pop-to-buffer-same-window ibuf)
7150 (org-set-frame-title (concat "Indirect: " heading)))
7151 ((eq org-indirect-buffer-display 'current-window)
7152 (org-pop-to-buffer-same-window ibuf))
7153 ((eq org-indirect-buffer-display 'other-window)
7154 (pop-to-buffer ibuf))
7155 (t (error "Invalid value")))
7156 (if (featurep 'xemacs)
7157 (save-excursion (org-mode) (turn-on-font-lock)))
7158 (narrow-to-region beg end)
7159 (show-all)
7160 (goto-char pos)
7161 (run-hook-with-args 'org-cycle-hook 'all)
7162 (and (window-live-p cwin) (select-window cwin))))
7164 (defun org-get-indirect-buffer (&optional buffer)
7165 (setq buffer (or buffer (current-buffer)))
7166 (let ((n 1) (base (buffer-name buffer)) bname)
7167 (while (buffer-live-p
7168 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7169 (setq n (1+ n)))
7170 (condition-case nil
7171 (make-indirect-buffer buffer bname 'clone)
7172 (error (make-indirect-buffer buffer bname)))))
7174 (defun org-set-frame-title (title)
7175 "Set the title of the current frame to the string TITLE."
7176 ;; FIXME: how to name a single frame in XEmacs???
7177 (unless (featurep 'xemacs)
7178 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7180 ;;;; Structure editing
7182 ;;; Inserting headlines
7184 (defun org-previous-line-empty-p ()
7185 (save-excursion
7186 (and (not (bobp))
7187 (or (beginning-of-line 0) t)
7188 (save-match-data
7189 (looking-at "[ \t]*$")))))
7191 (defun org-insert-heading (&optional force-heading invisible-ok)
7192 "Insert a new heading or item with same depth at point.
7193 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7194 If point is at the beginning of a headline, insert a sibling before the
7195 current headline. If point is not at the beginning, split the line,
7196 create the new headline with the text in the current line after point
7197 \(but see also the variable `org-M-RET-may-split-line').
7199 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7200 This is important for non-interactive uses of the command."
7201 (interactive "P")
7202 (if (or (= (buffer-size) 0)
7203 (and (not (save-excursion
7204 (and (ignore-errors (org-back-to-heading invisible-ok))
7205 (org-at-heading-p))))
7206 (or force-heading (not (org-in-item-p)))))
7207 (progn
7208 (insert "\n* ")
7209 (run-hooks 'org-insert-heading-hook))
7210 (when (or force-heading (not (org-insert-item)))
7211 (let* ((empty-line-p nil)
7212 (level nil)
7213 (on-heading (org-at-heading-p))
7214 (head (save-excursion
7215 (condition-case nil
7216 (progn
7217 (org-back-to-heading invisible-ok)
7218 (when (and (not on-heading)
7219 (featurep 'org-inlinetask)
7220 (integerp org-inlinetask-min-level)
7221 (>= (length (match-string 0))
7222 org-inlinetask-min-level))
7223 ;; Find a heading level before the inline task
7224 (while (and (setq level (org-up-heading-safe))
7225 (>= level org-inlinetask-min-level)))
7226 (if (org-at-heading-p)
7227 (org-back-to-heading invisible-ok)
7228 (error "This should not happen")))
7229 (setq empty-line-p (org-previous-line-empty-p))
7230 (match-string 0))
7231 (error "*"))))
7232 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7233 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7234 pos hide-previous previous-pos)
7235 (cond
7236 ((and (org-at-heading-p) (bolp)
7237 (or (bobp)
7238 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7239 ;; insert before the current line
7240 (open-line (if blank 2 1)))
7241 ((and (bolp)
7242 (not org-insert-heading-respect-content)
7243 (or (bobp)
7244 (save-excursion
7245 (backward-char 1) (not (outline-invisible-p)))))
7246 ;; insert right here
7247 nil)
7249 ;; somewhere in the line
7250 (save-excursion
7251 (setq previous-pos (point-at-bol))
7252 (end-of-line)
7253 (setq hide-previous (outline-invisible-p)))
7254 (and org-insert-heading-respect-content (org-show-subtree))
7255 (let ((split
7256 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7257 (save-excursion
7258 (let ((p (point)))
7259 (goto-char (point-at-bol))
7260 (and (looking-at org-complex-heading-regexp)
7261 (match-beginning 4)
7262 (> p (match-beginning 4)))))))
7263 tags pos)
7264 (cond
7265 (org-insert-heading-respect-content
7266 (org-end-of-subtree nil t)
7267 (when (featurep 'org-inlinetask)
7268 (while (and (not (eobp))
7269 (looking-at "\\(\\*+\\)[ \t]+")
7270 (>= (length (match-string 1))
7271 org-inlinetask-min-level))
7272 (org-end-of-subtree nil t)))
7273 (or (bolp) (newline))
7274 (or (org-previous-line-empty-p)
7275 (and blank (newline)))
7276 (open-line 1))
7277 ((org-at-heading-p)
7278 (when hide-previous
7279 (show-children)
7280 (org-show-entry))
7281 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7282 (setq tags (and (match-end 2) (match-string 2)))
7283 (and (match-end 1)
7284 (delete-region (match-beginning 1) (match-end 1)))
7285 (setq pos (point-at-bol))
7286 (or split (end-of-line 1))
7287 (delete-horizontal-space)
7288 (if (string-match "\\`\\*+\\'"
7289 (buffer-substring (point-at-bol) (point)))
7290 (insert " "))
7291 (newline (if blank 2 1))
7292 (when tags
7293 (save-excursion
7294 (goto-char pos)
7295 (end-of-line 1)
7296 (insert " " tags)
7297 (org-set-tags nil 'align))))
7299 (or split (end-of-line 1))
7300 (newline (if blank 2 1)))))))
7301 (insert head) (just-one-space)
7302 (setq pos (point))
7303 (end-of-line 1)
7304 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7305 (when (and org-insert-heading-respect-content hide-previous)
7306 (save-excursion
7307 (goto-char previous-pos)
7308 (hide-subtree)))
7309 (run-hooks 'org-insert-heading-hook)))))
7311 (defun org-get-heading (&optional no-tags no-todo)
7312 "Return the heading of the current entry, without the stars.
7313 When NO-TAGS is non-nil, don't include tags.
7314 When NO-TODO is non-nil, don't include TODO keywords."
7315 (save-excursion
7316 (org-back-to-heading t)
7317 (cond
7318 ((and no-tags no-todo)
7319 (looking-at org-complex-heading-regexp)
7320 (match-string 4))
7321 (no-tags
7322 (looking-at (concat org-outline-regexp
7323 "\\(.*?\\)"
7324 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7325 (match-string 1))
7326 (no-todo
7327 (looking-at org-todo-line-regexp)
7328 (match-string 3))
7329 (t (looking-at org-heading-regexp)
7330 (match-string 2)))))
7332 (defun org-heading-components ()
7333 "Return the components of the current heading.
7334 This is a list with the following elements:
7335 - the level as an integer
7336 - the reduced level, different if `org-odd-levels-only' is set.
7337 - the TODO keyword, or nil
7338 - the priority character, like ?A, or nil if no priority is given
7339 - the headline text itself, or the tags string if no headline text
7340 - the tags string, or nil."
7341 (save-excursion
7342 (org-back-to-heading t)
7343 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7344 (list (length (match-string 1))
7345 (org-reduced-level (length (match-string 1)))
7346 (org-match-string-no-properties 2)
7347 (and (match-end 3) (aref (match-string 3) 2))
7348 (org-match-string-no-properties 4)
7349 (org-match-string-no-properties 5)))))
7351 (defun org-get-entry ()
7352 "Get the entry text, after heading, entire subtree."
7353 (save-excursion
7354 (org-back-to-heading t)
7355 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7357 (defun org-insert-heading-after-current ()
7358 "Insert a new heading with same level as current, after current subtree."
7359 (interactive)
7360 (org-back-to-heading)
7361 (org-insert-heading)
7362 (org-move-subtree-down)
7363 (end-of-line 1))
7365 (defun org-insert-heading-respect-content ()
7366 (interactive)
7367 (let ((org-insert-heading-respect-content t))
7368 (org-insert-heading t)))
7370 (defun org-insert-todo-heading-respect-content (&optional force-state)
7371 (interactive "P")
7372 (let ((org-insert-heading-respect-content t))
7373 (org-insert-todo-heading force-state t)))
7375 (defun org-insert-todo-heading (arg &optional force-heading)
7376 "Insert a new heading with the same level and TODO state as current heading.
7377 If the heading has no TODO state, or if the state is DONE, use the first
7378 state (TODO by default). Also with prefix arg, force first state."
7379 (interactive "P")
7380 (when (or force-heading (not (org-insert-item 'checkbox)))
7381 (org-insert-heading force-heading)
7382 (save-excursion
7383 (org-back-to-heading)
7384 (outline-previous-heading)
7385 (looking-at org-todo-line-regexp))
7386 (let*
7387 ((new-mark-x
7388 (if (or arg
7389 (not (match-beginning 2))
7390 (member (match-string 2) org-done-keywords))
7391 (car org-todo-keywords-1)
7392 (match-string 2)))
7393 (new-mark
7395 (run-hook-with-args-until-success
7396 'org-todo-get-default-hook new-mark-x nil)
7397 new-mark-x)))
7398 (beginning-of-line 1)
7399 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7400 (if org-treat-insert-todo-heading-as-state-change
7401 (org-todo new-mark)
7402 (insert new-mark " "))))
7403 (when org-provide-todo-statistics
7404 (org-update-parent-todo-statistics))))
7406 (defun org-insert-subheading (arg)
7407 "Insert a new subheading and demote it.
7408 Works for outline headings and for plain lists alike."
7409 (interactive "P")
7410 (org-insert-heading arg)
7411 (cond
7412 ((org-at-heading-p) (org-do-demote))
7413 ((org-at-item-p) (org-indent-item))))
7415 (defun org-insert-todo-subheading (arg)
7416 "Insert a new subheading with TODO keyword or checkbox and demote it.
7417 Works for outline headings and for plain lists alike."
7418 (interactive "P")
7419 (org-insert-todo-heading arg)
7420 (cond
7421 ((org-at-heading-p) (org-do-demote))
7422 ((org-at-item-p) (org-indent-item))))
7424 ;;; Promotion and Demotion
7426 (defvar org-after-demote-entry-hook nil
7427 "Hook run after an entry has been demoted.
7428 The cursor will be at the beginning of the entry.
7429 When a subtree is being demoted, the hook will be called for each node.")
7431 (defvar org-after-promote-entry-hook nil
7432 "Hook run after an entry has been promoted.
7433 The cursor will be at the beginning of the entry.
7434 When a subtree is being promoted, the hook will be called for each node.")
7436 (defun org-promote-subtree ()
7437 "Promote the entire subtree.
7438 See also `org-promote'."
7439 (interactive)
7440 (save-excursion
7441 (org-with-limited-levels (org-map-tree 'org-promote)))
7442 (org-fix-position-after-promote))
7444 (defun org-demote-subtree ()
7445 "Demote the entire subtree. See `org-demote'.
7446 See also `org-promote'."
7447 (interactive)
7448 (save-excursion
7449 (org-with-limited-levels (org-map-tree 'org-demote)))
7450 (org-fix-position-after-promote))
7453 (defun org-do-promote ()
7454 "Promote the current heading higher up the tree.
7455 If the region is active in `transient-mark-mode', promote all headings
7456 in the region."
7457 (interactive)
7458 (save-excursion
7459 (if (org-region-active-p)
7460 (org-map-region 'org-promote (region-beginning) (region-end))
7461 (org-promote)))
7462 (org-fix-position-after-promote))
7464 (defun org-do-demote ()
7465 "Demote the current heading lower down the tree.
7466 If the region is active in `transient-mark-mode', demote all headings
7467 in the region."
7468 (interactive)
7469 (save-excursion
7470 (if (org-region-active-p)
7471 (org-map-region 'org-demote (region-beginning) (region-end))
7472 (org-demote)))
7473 (org-fix-position-after-promote))
7475 (defun org-fix-position-after-promote ()
7476 "Make sure that after pro/demotion cursor position is right."
7477 (let ((pos (point)))
7478 (when (save-excursion
7479 (beginning-of-line 1)
7480 (looking-at org-todo-line-regexp)
7481 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7482 (cond ((eobp) (insert " "))
7483 ((eolp) (insert " "))
7484 ((equal (char-after) ?\ ) (forward-char 1))))))
7486 (defun org-current-level ()
7487 "Return the level of the current entry, or nil if before the first headline.
7488 The level is the number of stars at the beginning of the headline."
7489 (save-excursion
7490 (org-with-limited-levels
7491 (if (ignore-errors (org-back-to-heading t))
7492 (funcall outline-level)))))
7494 (defun org-get-previous-line-level ()
7495 "Return the outline depth of the last headline before the current line.
7496 Returns 0 for the first headline in the buffer, and nil if before the
7497 first headline."
7498 (let ((current-level (org-current-level))
7499 (prev-level (when (> (line-number-at-pos) 1)
7500 (save-excursion
7501 (beginning-of-line 0)
7502 (org-current-level)))))
7503 (cond ((null current-level) nil) ; Before first headline
7504 ((null prev-level) 0) ; At first headline
7505 (prev-level))))
7507 (defun org-reduced-level (l)
7508 "Compute the effective level of a heading.
7509 This takes into account the setting of `org-odd-levels-only'."
7510 (cond
7511 ((zerop l) 0)
7512 (org-odd-levels-only (1+ (floor (/ l 2))))
7513 (t l)))
7515 (defun org-level-increment ()
7516 "Return the number of stars that will be added or removed at a
7517 time to headlines when structure editing, based on the value of
7518 `org-odd-levels-only'."
7519 (if org-odd-levels-only 2 1))
7521 (defun org-get-valid-level (level &optional change)
7522 "Rectify a level change under the influence of `org-odd-levels-only'
7523 LEVEL is a current level, CHANGE is by how much the level should be
7524 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7525 even level numbers will become the next higher odd number."
7526 (if org-odd-levels-only
7527 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7528 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7529 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7530 (max 1 (+ level (or change 0)))))
7532 (if (boundp 'define-obsolete-function-alias)
7533 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7534 (define-obsolete-function-alias 'org-get-legal-level
7535 'org-get-valid-level)
7536 (define-obsolete-function-alias 'org-get-legal-level
7537 'org-get-valid-level "23.1")))
7539 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7540 ;; ̀org-with-limited-levels'
7541 (defun org-promote ()
7542 "Promote the current heading higher up the tree.
7543 If the region is active in `transient-mark-mode', promote all headings
7544 in the region."
7545 (org-back-to-heading t)
7546 (let* ((level (save-match-data (funcall outline-level)))
7547 (after-change-functions (remove 'flyspell-after-change-function
7548 after-change-functions))
7549 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7550 (diff (abs (- level (length up-head) -1))))
7551 (cond ((and (= level 1) org-called-with-limited-levels
7552 org-allow-promoting-top-level-subtree)
7553 (replace-match "# " nil t))
7554 ((= level 1)
7555 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7556 (t (replace-match up-head nil t)))
7557 ;; Fixup tag positioning
7558 (unless (= level 1)
7559 (and org-auto-align-tags (org-set-tags nil t))
7560 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7561 (run-hooks 'org-after-promote-entry-hook)))
7563 (defun org-demote ()
7564 "Demote the current heading lower down the tree.
7565 If the region is active in `transient-mark-mode', demote all headings
7566 in the region."
7567 (org-back-to-heading t)
7568 (let* ((level (save-match-data (funcall outline-level)))
7569 (after-change-functions (remove 'flyspell-after-change-function
7570 after-change-functions))
7571 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7572 (diff (abs (- level (length down-head) -1))))
7573 (replace-match down-head nil t)
7574 ;; Fixup tag positioning
7575 (and org-auto-align-tags (org-set-tags nil t))
7576 (if org-adapt-indentation (org-fixup-indentation diff))
7577 (run-hooks 'org-after-demote-entry-hook)))
7579 (defun org-cycle-level ()
7580 "Cycle the level of an empty headline through possible states.
7581 This goes first to child, then to parent, level, then up the hierarchy.
7582 After top level, it switches back to sibling level."
7583 (interactive)
7584 (let ((org-adapt-indentation nil))
7585 (when (org-point-at-end-of-empty-headline)
7586 (setq this-command 'org-cycle-level) ; Only needed for caching
7587 (let ((cur-level (org-current-level))
7588 (prev-level (org-get-previous-line-level)))
7589 (cond
7590 ;; If first headline in file, promote to top-level.
7591 ((= prev-level 0)
7592 (loop repeat (/ (- cur-level 1) (org-level-increment))
7593 do (org-do-promote)))
7594 ;; If same level as prev, demote one.
7595 ((= prev-level cur-level)
7596 (org-do-demote))
7597 ;; If parent is top-level, promote to top level if not already.
7598 ((= prev-level 1)
7599 (loop repeat (/ (- cur-level 1) (org-level-increment))
7600 do (org-do-promote)))
7601 ;; If top-level, return to prev-level.
7602 ((= cur-level 1)
7603 (loop repeat (/ (- prev-level 1) (org-level-increment))
7604 do (org-do-demote)))
7605 ;; If less than prev-level, promote one.
7606 ((< cur-level prev-level)
7607 (org-do-promote))
7608 ;; If deeper than prev-level, promote until higher than
7609 ;; prev-level.
7610 ((> cur-level prev-level)
7611 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7612 do (org-do-promote))))
7613 t))))
7615 (defun org-map-tree (fun)
7616 "Call FUN for every heading underneath the current one."
7617 (org-back-to-heading)
7618 (let ((level (funcall outline-level)))
7619 (save-excursion
7620 (funcall fun)
7621 (while (and (progn
7622 (outline-next-heading)
7623 (> (funcall outline-level) level))
7624 (not (eobp)))
7625 (funcall fun)))))
7627 (defun org-map-region (fun beg end)
7628 "Call FUN for every heading between BEG and END."
7629 (let ((org-ignore-region t))
7630 (save-excursion
7631 (setq end (copy-marker end))
7632 (goto-char beg)
7633 (if (and (re-search-forward org-outline-regexp-bol nil t)
7634 (< (point) end))
7635 (funcall fun))
7636 (while (and (progn
7637 (outline-next-heading)
7638 (< (point) end))
7639 (not (eobp)))
7640 (funcall fun)))))
7642 (defvar org-property-end-re) ; silence byte-compiler
7643 (defun org-fixup-indentation (diff)
7644 "Change the indentation in the current entry by DIFF.
7645 However, if any line in the current entry has no indentation, or if it
7646 would end up with no indentation after the change, nothing at all is done."
7647 (save-excursion
7648 (let ((end (save-excursion (outline-next-heading)
7649 (point-marker)))
7650 (prohibit (if (> diff 0)
7651 "^\\S-"
7652 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7653 col)
7654 (unless (save-excursion (end-of-line 1)
7655 (re-search-forward prohibit end t))
7656 (while (and (< (point) end)
7657 (re-search-forward "^[ \t]+" end t))
7658 (goto-char (match-end 0))
7659 (setq col (current-column))
7660 (if (< diff 0) (replace-match ""))
7661 (org-indent-to-column (+ diff col))))
7662 (move-marker end nil))))
7664 (defun org-convert-to-odd-levels ()
7665 "Convert an org-mode file with all levels allowed to one with odd levels.
7666 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7667 level 5 etc."
7668 (interactive)
7669 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7670 (let ((outline-level 'org-outline-level)
7671 (org-odd-levels-only nil) n)
7672 (save-excursion
7673 (goto-char (point-min))
7674 (while (re-search-forward "^\\*\\*+ " nil t)
7675 (setq n (- (length (match-string 0)) 2))
7676 (while (>= (setq n (1- n)) 0)
7677 (org-demote))
7678 (end-of-line 1))))))
7680 (defun org-convert-to-oddeven-levels ()
7681 "Convert an org-mode file with only odd levels to one with odd/even levels.
7682 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7683 file contains a section with an even level, conversion would
7684 destroy the structure of the file. An error is signaled in this
7685 case."
7686 (interactive)
7687 (goto-char (point-min))
7688 ;; First check if there are no even levels
7689 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7690 (org-show-context t)
7691 (error "Not all levels are odd in this file. Conversion not possible"))
7692 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7693 (let ((outline-regexp org-outline-regexp)
7694 (outline-level 'org-outline-level)
7695 (org-odd-levels-only nil) n)
7696 (save-excursion
7697 (goto-char (point-min))
7698 (while (re-search-forward "^\\*\\*+ " nil t)
7699 (setq n (/ (1- (length (match-string 0))) 2))
7700 (while (>= (setq n (1- n)) 0)
7701 (org-promote))
7702 (end-of-line 1))))))
7704 (defun org-tr-level (n)
7705 "Make N odd if required."
7706 (if org-odd-levels-only (1+ (/ n 2)) n))
7708 ;;; Vertical tree motion, cutting and pasting of subtrees
7710 (defun org-move-subtree-up (&optional arg)
7711 "Move the current subtree up past ARG headlines of the same level."
7712 (interactive "p")
7713 (org-move-subtree-down (- (prefix-numeric-value arg))))
7715 (defun org-move-subtree-down (&optional arg)
7716 "Move the current subtree down past ARG headlines of the same level."
7717 (interactive "p")
7718 (setq arg (prefix-numeric-value arg))
7719 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7720 'org-get-last-sibling))
7721 (ins-point (make-marker))
7722 (cnt (abs arg))
7723 (col (current-column))
7724 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7725 ;; Select the tree
7726 (org-back-to-heading)
7727 (setq beg0 (point))
7728 (save-excursion
7729 (setq ne-beg (org-back-over-empty-lines))
7730 (setq beg (point)))
7731 (save-match-data
7732 (save-excursion (outline-end-of-heading)
7733 (setq folded (outline-invisible-p)))
7734 (outline-end-of-subtree))
7735 (outline-next-heading)
7736 (setq ne-end (org-back-over-empty-lines))
7737 (setq end (point))
7738 (goto-char beg0)
7739 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7740 ;; include less whitespace
7741 (save-excursion
7742 (goto-char beg)
7743 (forward-line (- ne-beg ne-end))
7744 (setq beg (point))))
7745 ;; Find insertion point, with error handling
7746 (while (> cnt 0)
7747 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7748 (progn (goto-char beg0)
7749 (error "Cannot move past superior level or buffer limit")))
7750 (setq cnt (1- cnt)))
7751 (if (> arg 0)
7752 ;; Moving forward - still need to move over subtree
7753 (progn (org-end-of-subtree t t)
7754 (save-excursion
7755 (org-back-over-empty-lines)
7756 (or (bolp) (newline)))))
7757 (setq ne-ins (org-back-over-empty-lines))
7758 (move-marker ins-point (point))
7759 (setq txt (buffer-substring beg end))
7760 (org-save-markers-in-region beg end)
7761 (delete-region beg end)
7762 (org-remove-empty-overlays-at beg)
7763 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7764 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7765 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7766 (let ((bbb (point)))
7767 (insert-before-markers txt)
7768 (org-reinstall-markers-in-region bbb)
7769 (move-marker ins-point bbb))
7770 (or (bolp) (insert "\n"))
7771 (setq ins-end (point))
7772 (goto-char ins-point)
7773 (org-skip-whitespace)
7774 (when (and (< arg 0)
7775 (org-first-sibling-p)
7776 (> ne-ins ne-beg))
7777 ;; Move whitespace back to beginning
7778 (save-excursion
7779 (goto-char ins-end)
7780 (let ((kill-whole-line t))
7781 (kill-line (- ne-ins ne-beg)) (point)))
7782 (insert (make-string (- ne-ins ne-beg) ?\n)))
7783 (move-marker ins-point nil)
7784 (if folded
7785 (hide-subtree)
7786 (org-show-entry)
7787 (show-children)
7788 (org-cycle-hide-drawers 'children))
7789 (org-clean-visibility-after-subtree-move)
7790 ;; move back to the initial column we were at
7791 (move-to-column col)))
7793 (defvar org-subtree-clip ""
7794 "Clipboard for cut and paste of subtrees.
7795 This is actually only a copy of the kill, because we use the normal kill
7796 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7798 (defvar org-subtree-clip-folded nil
7799 "Was the last copied subtree folded?
7800 This is used to fold the tree back after pasting.")
7802 (defun org-cut-subtree (&optional n)
7803 "Cut the current subtree into the clipboard.
7804 With prefix arg N, cut this many sequential subtrees.
7805 This is a short-hand for marking the subtree and then cutting it."
7806 (interactive "p")
7807 (org-copy-subtree n 'cut))
7809 (defun org-copy-subtree (&optional n cut force-store-markers)
7810 "Cut the current subtree into the clipboard.
7811 With prefix arg N, cut this many sequential subtrees.
7812 This is a short-hand for marking the subtree and then copying it.
7813 If CUT is non-nil, actually cut the subtree.
7814 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7815 of some markers in the region, even if CUT is non-nil. This is
7816 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7817 (interactive "p")
7818 (let (beg end folded (beg0 (point)))
7819 (if (org-called-interactively-p 'any)
7820 (org-back-to-heading nil) ; take what looks like a subtree
7821 (org-back-to-heading t)) ; take what is really there
7822 (org-back-over-empty-lines)
7823 (setq beg (point))
7824 (skip-chars-forward " \t\r\n")
7825 (save-match-data
7826 (save-excursion (outline-end-of-heading)
7827 (setq folded (outline-invisible-p)))
7828 (condition-case nil
7829 (org-forward-heading-same-level (1- n) t)
7830 (error nil))
7831 (org-end-of-subtree t t))
7832 (org-back-over-empty-lines)
7833 (setq end (point))
7834 (goto-char beg0)
7835 (when (> end beg)
7836 (setq org-subtree-clip-folded folded)
7837 (when (or cut force-store-markers)
7838 (org-save-markers-in-region beg end))
7839 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7840 (setq org-subtree-clip (current-kill 0))
7841 (message "%s: Subtree(s) with %d characters"
7842 (if cut "Cut" "Copied")
7843 (length org-subtree-clip)))))
7845 (defun org-paste-subtree (&optional level tree for-yank)
7846 "Paste the clipboard as a subtree, with modification of headline level.
7847 The entire subtree is promoted or demoted in order to match a new headline
7848 level.
7850 If the cursor is at the beginning of a headline, the same level as
7851 that headline is used to paste the tree
7853 If not, the new level is derived from the *visible* headings
7854 before and after the insertion point, and taken to be the inferior headline
7855 level of the two. So if the previous visible heading is level 3 and the
7856 next is level 4 (or vice versa), level 4 will be used for insertion.
7857 This makes sure that the subtree remains an independent subtree and does
7858 not swallow low level entries.
7860 You can also force a different level, either by using a numeric prefix
7861 argument, or by inserting the heading marker by hand. For example, if the
7862 cursor is after \"*****\", then the tree will be shifted to level 5.
7864 If optional TREE is given, use this text instead of the kill ring.
7866 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7867 move back over whitespace before inserting, and move point to the end of
7868 the inserted text when done."
7869 (interactive "P")
7870 (setq tree (or tree (and kill-ring (current-kill 0))))
7871 (unless (org-kill-is-subtree-p tree)
7872 (error "%s"
7873 (substitute-command-keys
7874 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7875 (org-with-limited-levels
7876 (let* ((visp (not (outline-invisible-p)))
7877 (txt tree)
7878 (^re_ "\\(\\*+\\)[ \t]*")
7879 (old-level (if (string-match org-outline-regexp-bol txt)
7880 (- (match-end 0) (match-beginning 0) 1)
7881 -1))
7882 (force-level (cond (level (prefix-numeric-value level))
7883 ((and (looking-at "[ \t]*$")
7884 (string-match
7885 "^\\*+$" (buffer-substring
7886 (point-at-bol) (point))))
7887 (- (match-end 1) (match-beginning 1)))
7888 ((and (bolp)
7889 (looking-at org-outline-regexp))
7890 (- (match-end 0) (point) 1))
7891 (t nil)))
7892 (previous-level (save-excursion
7893 (condition-case nil
7894 (progn
7895 (outline-previous-visible-heading 1)
7896 (if (looking-at ^re_)
7897 (- (match-end 0) (match-beginning 0) 1)
7899 (error 1))))
7900 (next-level (save-excursion
7901 (condition-case nil
7902 (progn
7903 (or (looking-at org-outline-regexp)
7904 (outline-next-visible-heading 1))
7905 (if (looking-at ^re_)
7906 (- (match-end 0) (match-beginning 0) 1)
7908 (error 1))))
7909 (new-level (or force-level (max previous-level next-level)))
7910 (shift (if (or (= old-level -1)
7911 (= new-level -1)
7912 (= old-level new-level))
7914 (- new-level old-level)))
7915 (delta (if (> shift 0) -1 1))
7916 (func (if (> shift 0) 'org-demote 'org-promote))
7917 (org-odd-levels-only nil)
7918 beg end newend)
7919 ;; Remove the forced level indicator
7920 (if force-level
7921 (delete-region (point-at-bol) (point)))
7922 ;; Paste
7923 (beginning-of-line (if (bolp) 1 2))
7924 (unless for-yank (org-back-over-empty-lines))
7925 (setq beg (point))
7926 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7927 (insert-before-markers txt)
7928 (unless (string-match "\n\\'" txt) (insert "\n"))
7929 (setq newend (point))
7930 (org-reinstall-markers-in-region beg)
7931 (setq end (point))
7932 (goto-char beg)
7933 (skip-chars-forward " \t\n\r")
7934 (setq beg (point))
7935 (if (and (outline-invisible-p) visp)
7936 (save-excursion (outline-show-heading)))
7937 ;; Shift if necessary
7938 (unless (= shift 0)
7939 (save-restriction
7940 (narrow-to-region beg end)
7941 (while (not (= shift 0))
7942 (org-map-region func (point-min) (point-max))
7943 (setq shift (+ delta shift)))
7944 (goto-char (point-min))
7945 (setq newend (point-max))))
7946 (when (or (org-called-interactively-p 'interactive) for-yank)
7947 (message "Clipboard pasted as level %d subtree" new-level))
7948 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7949 kill-ring
7950 (eq org-subtree-clip (current-kill 0))
7951 org-subtree-clip-folded)
7952 ;; The tree was folded before it was killed/copied
7953 (hide-subtree))
7954 (and for-yank (goto-char newend)))))
7956 (defun org-kill-is-subtree-p (&optional txt)
7957 "Check if the current kill is an outline subtree, or a set of trees.
7958 Returns nil if kill does not start with a headline, or if the first
7959 headline level is not the largest headline level in the tree.
7960 So this will actually accept several entries of equal levels as well,
7961 which is OK for `org-paste-subtree'.
7962 If optional TXT is given, check this string instead of the current kill."
7963 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7964 (re (org-get-limited-outline-regexp))
7965 (^re (concat "^" re))
7966 (start-level (and kill
7967 (string-match
7968 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7969 kill)
7970 (- (match-end 2) (match-beginning 2) 1)))
7971 (start (1+ (or (match-beginning 2) -1))))
7972 (if (not start-level)
7973 (progn
7974 nil) ;; does not even start with a heading
7975 (catch 'exit
7976 (while (setq start (string-match ^re kill (1+ start)))
7977 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7978 (throw 'exit nil)))
7979 t))))
7981 (defvar org-markers-to-move nil
7982 "Markers that should be moved with a cut-and-paste operation.
7983 Those markers are stored together with their positions relative to
7984 the start of the region.")
7986 (defun org-save-markers-in-region (beg end)
7987 "Check markers in region.
7988 If these markers are between BEG and END, record their position relative
7989 to BEG, so that after moving the block of text, we can put the markers back
7990 into place.
7991 This function gets called just before an entry or tree gets cut from the
7992 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7993 called immediately, to move the markers with the entries."
7994 (setq org-markers-to-move nil)
7995 (when (featurep 'org-clock)
7996 (org-clock-save-markers-for-cut-and-paste beg end))
7997 (when (featurep 'org-agenda)
7998 (org-agenda-save-markers-for-cut-and-paste beg end)))
8000 (defun org-check-and-save-marker (marker beg end)
8001 "Check if MARKER is between BEG and END.
8002 If yes, remember the marker and the distance to BEG."
8003 (when (and (marker-buffer marker)
8004 (equal (marker-buffer marker) (current-buffer)))
8005 (if (and (>= marker beg) (< marker end))
8006 (push (cons marker (- marker beg)) org-markers-to-move))))
8008 (defun org-reinstall-markers-in-region (beg)
8009 "Move all remembered markers to their position relative to BEG."
8010 (mapc (lambda (x)
8011 (move-marker (car x) (+ beg (cdr x))))
8012 org-markers-to-move)
8013 (setq org-markers-to-move nil))
8015 (defun org-narrow-to-subtree ()
8016 "Narrow buffer to the current subtree."
8017 (interactive)
8018 (save-excursion
8019 (save-match-data
8020 (org-with-limited-levels
8021 (narrow-to-region
8022 (progn (org-back-to-heading t) (point))
8023 (progn (org-end-of-subtree t t)
8024 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8025 (point)))))))
8027 (defun org-narrow-to-block ()
8028 "Narrow buffer to the current block."
8029 (interactive)
8030 (let* ((case-fold-search t)
8031 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8032 "^[ \t]*#\\+end_.*")))
8033 (if blockp
8034 (narrow-to-region (car blockp) (cdr blockp))
8035 (error "Not in a block"))))
8037 (eval-when-compile
8038 (defvar org-property-drawer-re))
8040 (defvar org-property-start-re) ;; defined below
8041 (defun org-clone-subtree-with-time-shift (n &optional shift)
8042 "Clone the task (subtree) at point N times.
8043 The clones will be inserted as siblings.
8045 In interactive use, the user will be prompted for the number of
8046 clones to be produced, and for a time SHIFT, which may be a
8047 repeater as used in time stamps, for example `+3d'.
8049 When a valid repeater is given and the entry contains any time
8050 stamps, the clones will become a sequence in time, with time
8051 stamps in the subtree shifted for each clone produced. If SHIFT
8052 is nil or the empty string, time stamps will be left alone. The
8053 ID property of the original subtree is removed.
8055 If the original subtree did contain time stamps with a repeater,
8056 the following will happen:
8057 - the repeater will be removed in each clone
8058 - an additional clone will be produced, with the current, unshifted
8059 date(s) in the entry.
8060 - the original entry will be placed *after* all the clones, with
8061 repeater intact.
8062 - the start days in the repeater in the original entry will be shifted
8063 to past the last clone.
8064 In this way you can spell out a number of instances of a repeating task,
8065 and still retain the repeater to cover future instances of the task."
8066 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8067 (let (beg end template task idprop
8068 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8069 (drawer-re org-drawer-regexp))
8070 (if (not (and (integerp n) (> n 0)))
8071 (error "Invalid number of replications %s" n))
8072 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8073 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8074 shift)))
8075 (error "Invalid shift specification %s" shift))
8076 (when doshift
8077 (setq shift-n (string-to-number (match-string 1 shift))
8078 shift-what (cdr (assoc (match-string 2 shift)
8079 '(("d" . day) ("w" . week)
8080 ("m" . month) ("y" . year))))))
8081 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8082 (setq nmin 1 nmax n)
8083 (org-back-to-heading t)
8084 (setq beg (point))
8085 (setq idprop (org-entry-get nil "ID"))
8086 (org-end-of-subtree t t)
8087 (or (bolp) (insert "\n"))
8088 (setq end (point))
8089 (setq template (buffer-substring beg end))
8090 (when (and doshift
8091 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8092 (delete-region beg end)
8093 (setq end beg)
8094 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8095 (goto-char end)
8096 (loop for n from nmin to nmax do
8097 ;; prepare clone
8098 (with-temp-buffer
8099 (insert template)
8100 (org-mode)
8101 (goto-char (point-min))
8102 (org-show-subtree)
8103 (and idprop (if org-clone-delete-id
8104 (org-entry-delete nil "ID")
8105 (org-id-get-create t)))
8106 (unless (= n 0)
8107 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8108 (kill-whole-line))
8109 (goto-char (point-min))
8110 (while (re-search-forward drawer-re nil t)
8111 (mapc (lambda (d)
8112 (org-remove-empty-drawer-at d (point))) org-drawers)))
8113 (goto-char (point-min))
8114 (when doshift
8115 (while (re-search-forward org-ts-regexp-both nil t)
8116 (org-timestamp-change (* n shift-n) shift-what))
8117 (unless (= n n-no-remove)
8118 (goto-char (point-min))
8119 (while (re-search-forward org-ts-regexp nil t)
8120 (save-excursion
8121 (goto-char (match-beginning 0))
8122 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8123 (delete-region (match-beginning 1) (match-end 1)))))))
8124 (setq task (buffer-string)))
8125 (insert task))
8126 (goto-char beg)))
8128 ;;; Outline Sorting
8130 (defun org-sort (with-case)
8131 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8132 Optional argument WITH-CASE means sort case-sensitively."
8133 (interactive "P")
8134 (cond
8135 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8136 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8138 (org-call-with-arg 'org-sort-entries with-case))))
8140 (defun org-sort-remove-invisible (s)
8141 (remove-text-properties 0 (length s) org-rm-props s)
8142 (while (string-match org-bracket-link-regexp s)
8143 (setq s (replace-match (if (match-end 2)
8144 (match-string 3 s)
8145 (match-string 1 s)) t t s)))
8148 (defvar org-priority-regexp) ; defined later in the file
8150 (defvar org-after-sorting-entries-or-items-hook nil
8151 "Hook that is run after a bunch of entries or items have been sorted.
8152 When children are sorted, the cursor is in the parent line when this
8153 hook gets called. When a region or a plain list is sorted, the cursor
8154 will be in the first entry of the sorted region/list.")
8156 (defun org-sort-entries
8157 (&optional with-case sorting-type getkey-func compare-func property)
8158 "Sort entries on a certain level of an outline tree.
8159 If there is an active region, the entries in the region are sorted.
8160 Else, if the cursor is before the first entry, sort the top-level items.
8161 Else, the children of the entry at point are sorted.
8163 Sorting can be alphabetically, numerically, by date/time as given by
8164 a time stamp, by a property or by priority.
8166 The command prompts for the sorting type unless it has been given to the
8167 function through the SORTING-TYPE argument, which needs to be a character,
8168 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8169 precise meaning of each character:
8171 n Numerically, by converting the beginning of the entry/item to a number.
8172 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8173 t By date/time, either the first active time stamp in the entry, or, if
8174 none exist, by the first inactive one.
8175 s By the scheduled date/time.
8176 d By deadline date/time.
8177 c By creation time, which is assumed to be the first inactive time stamp
8178 at the beginning of a line.
8179 p By priority according to the cookie.
8180 r By the value of a property.
8182 Capital letters will reverse the sort order.
8184 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8185 called with point at the beginning of the record. It must return either
8186 a string or a number that should serve as the sorting key for that record.
8188 Comparing entries ignores case by default. However, with an optional argument
8189 WITH-CASE, the sorting considers case as well."
8190 (interactive "P")
8191 (let ((case-func (if with-case 'identity 'downcase))
8192 start beg end stars re re2
8193 txt what tmp)
8194 ;; Find beginning and end of region to sort
8195 (cond
8196 ((org-region-active-p)
8197 ;; we will sort the region
8198 (setq end (region-end)
8199 what "region")
8200 (goto-char (region-beginning))
8201 (if (not (org-at-heading-p)) (outline-next-heading))
8202 (setq start (point)))
8203 ((or (org-at-heading-p)
8204 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8205 ;; we will sort the children of the current headline
8206 (org-back-to-heading)
8207 (setq start (point)
8208 end (progn (org-end-of-subtree t t)
8209 (or (bolp) (insert "\n"))
8210 (org-back-over-empty-lines)
8211 (point))
8212 what "children")
8213 (goto-char start)
8214 (show-subtree)
8215 (outline-next-heading))
8217 ;; we will sort the top-level entries in this file
8218 (goto-char (point-min))
8219 (or (org-at-heading-p) (outline-next-heading))
8220 (setq start (point))
8221 (goto-char (point-max))
8222 (beginning-of-line 1)
8223 (when (looking-at ".*?\\S-")
8224 ;; File ends in a non-white line
8225 (end-of-line 1)
8226 (insert "\n"))
8227 (setq end (point-max))
8228 (setq what "top-level")
8229 (goto-char start)
8230 (show-all)))
8232 (setq beg (point))
8233 (if (>= beg end) (error "Nothing to sort"))
8235 (looking-at "\\(\\*+\\)")
8236 (setq stars (match-string 1)
8237 re (concat "^" (regexp-quote stars) " +")
8238 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8239 txt (buffer-substring beg end))
8240 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8241 (if (and (not (equal stars "*")) (string-match re2 txt))
8242 (error "Region to sort contains a level above the first entry"))
8244 (unless sorting-type
8245 (message
8246 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8247 [t]ime [s]cheduled [d]eadline [c]reated
8248 A/N/T/S/D/C/P/O/F means reversed:"
8249 what)
8250 (setq sorting-type (read-char-exclusive))
8252 (and (= (downcase sorting-type) ?f)
8253 (setq getkey-func
8254 (org-icompleting-read "Sort using function: "
8255 obarray 'fboundp t nil nil))
8256 (setq getkey-func (intern getkey-func)))
8258 (and (= (downcase sorting-type) ?r)
8259 (setq property
8260 (org-icompleting-read "Property: "
8261 (mapcar 'list (org-buffer-property-keys t))
8262 nil t))))
8264 (message "Sorting entries...")
8266 (save-restriction
8267 (narrow-to-region start end)
8268 (let ((dcst (downcase sorting-type))
8269 (case-fold-search nil)
8270 (now (current-time)))
8271 (sort-subr
8272 (/= dcst sorting-type)
8273 ;; This function moves to the beginning character of the "record" to
8274 ;; be sorted.
8275 (lambda nil
8276 (if (re-search-forward re nil t)
8277 (goto-char (match-beginning 0))
8278 (goto-char (point-max))))
8279 ;; This function moves to the last character of the "record" being
8280 ;; sorted.
8281 (lambda nil
8282 (save-match-data
8283 (condition-case nil
8284 (outline-forward-same-level 1)
8285 (error
8286 (goto-char (point-max))))))
8287 ;; This function returns the value that gets sorted against.
8288 (lambda nil
8289 (cond
8290 ((= dcst ?n)
8291 (if (looking-at org-complex-heading-regexp)
8292 (string-to-number (match-string 4))
8293 nil))
8294 ((= dcst ?a)
8295 (if (looking-at org-complex-heading-regexp)
8296 (funcall case-func (match-string 4))
8297 nil))
8298 ((= dcst ?t)
8299 (let ((end (save-excursion (outline-next-heading) (point))))
8300 (if (or (re-search-forward org-ts-regexp end t)
8301 (re-search-forward org-ts-regexp-both end t))
8302 (org-time-string-to-seconds (match-string 0))
8303 (org-float-time now))))
8304 ((= dcst ?c)
8305 (let ((end (save-excursion (outline-next-heading) (point))))
8306 (if (re-search-forward
8307 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8308 end t)
8309 (org-time-string-to-seconds (match-string 0))
8310 (org-float-time now))))
8311 ((= dcst ?s)
8312 (let ((end (save-excursion (outline-next-heading) (point))))
8313 (if (re-search-forward org-scheduled-time-regexp end t)
8314 (org-time-string-to-seconds (match-string 1))
8315 (org-float-time now))))
8316 ((= dcst ?d)
8317 (let ((end (save-excursion (outline-next-heading) (point))))
8318 (if (re-search-forward org-deadline-time-regexp end t)
8319 (org-time-string-to-seconds (match-string 1))
8320 (org-float-time now))))
8321 ((= dcst ?p)
8322 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8323 (string-to-char (match-string 2))
8324 org-default-priority))
8325 ((= dcst ?r)
8326 (or (org-entry-get nil property) ""))
8327 ((= dcst ?o)
8328 (if (looking-at org-complex-heading-regexp)
8329 (- 9999 (length (member (match-string 2)
8330 org-todo-keywords-1)))))
8331 ((= dcst ?f)
8332 (if getkey-func
8333 (progn
8334 (setq tmp (funcall getkey-func))
8335 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8336 tmp)
8337 (error "Invalid key function `%s'" getkey-func)))
8338 (t (error "Invalid sorting type `%c'" sorting-type))))
8340 (cond
8341 ((= dcst ?a) 'string<)
8342 ((= dcst ?f) compare-func)
8343 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8344 (t nil)))))
8345 (run-hooks 'org-after-sorting-entries-or-items-hook)
8346 (message "Sorting entries...done")))
8348 (defun org-do-sort (table what &optional with-case sorting-type)
8349 "Sort TABLE of WHAT according to SORTING-TYPE.
8350 The user will be prompted for the SORTING-TYPE if the call to this
8351 function does not specify it. WHAT is only for the prompt, to indicate
8352 what is being sorted. The sorting key will be extracted from
8353 the car of the elements of the table.
8354 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8355 (unless sorting-type
8356 (message
8357 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8358 what)
8359 (setq sorting-type (read-char-exclusive)))
8360 (let ((dcst (downcase sorting-type))
8361 extractfun comparefun)
8362 ;; Define the appropriate functions
8363 (cond
8364 ((= dcst ?n)
8365 (setq extractfun 'string-to-number
8366 comparefun (if (= dcst sorting-type) '< '>)))
8367 ((= dcst ?a)
8368 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8369 (lambda(x) (downcase (org-sort-remove-invisible x))))
8370 comparefun (if (= dcst sorting-type)
8371 'string<
8372 (lambda (a b) (and (not (string< a b))
8373 (not (string= a b)))))))
8374 ((= dcst ?t)
8375 (setq extractfun
8376 (lambda (x)
8377 (if (or (string-match org-ts-regexp x)
8378 (string-match org-ts-regexp-both x))
8379 (org-float-time
8380 (org-time-string-to-time (match-string 0 x)))
8382 comparefun (if (= dcst sorting-type) '< '>)))
8383 (t (error "Invalid sorting type `%c'" sorting-type)))
8385 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8386 table)
8387 (lambda (a b) (funcall comparefun (car a) (car b))))))
8390 ;;; The orgstruct minor mode
8392 ;; Define a minor mode which can be used in other modes in order to
8393 ;; integrate the org-mode structure editing commands.
8395 ;; This is really a hack, because the org-mode structure commands use
8396 ;; keys which normally belong to the major mode. Here is how it
8397 ;; works: The minor mode defines all the keys necessary to operate the
8398 ;; structure commands, but wraps the commands into a function which
8399 ;; tests if the cursor is currently at a headline or a plain list
8400 ;; item. If that is the case, the structure command is used,
8401 ;; temporarily setting many Org-mode variables like regular
8402 ;; expressions for filling etc. However, when any of those keys is
8403 ;; used at a different location, function uses `key-binding' to look
8404 ;; up if the key has an associated command in another currently active
8405 ;; keymap (minor modes, major mode, global), and executes that
8406 ;; command. There might be problems if any of the keys is otherwise
8407 ;; used as a prefix key.
8409 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8410 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8411 ;; addresses this by checking explicitly for both bindings.
8413 (defvar orgstruct-mode-map (make-sparse-keymap)
8414 "Keymap for the minor `orgstruct-mode'.")
8416 (defvar org-local-vars nil
8417 "List of local variables, for use by `orgstruct-mode'.")
8419 ;;;###autoload
8420 (define-minor-mode orgstruct-mode
8421 "Toggle the minor mode `orgstruct-mode'.
8422 This mode is for using Org-mode structure commands in other
8423 modes. The following keys behave as if Org-mode were active, if
8424 the cursor is on a headline, or on a plain list item (both as
8425 defined by Org-mode).
8427 M-up Move entry/item up
8428 M-down Move entry/item down
8429 M-left Promote
8430 M-right Demote
8431 M-S-up Move entry/item up
8432 M-S-down Move entry/item down
8433 M-S-left Promote subtree
8434 M-S-right Demote subtree
8435 M-q Fill paragraph and items like in Org-mode
8436 C-c ^ Sort entries
8437 C-c - Cycle list bullet
8438 TAB Cycle item visibility
8439 M-RET Insert new heading/item
8440 S-M-RET Insert new TODO heading / Checkbox item
8441 C-c C-c Set tags / toggle checkbox"
8442 nil " OrgStruct" nil
8443 (org-load-modules-maybe)
8444 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8446 ;;;###autoload
8447 (defun turn-on-orgstruct ()
8448 "Unconditionally turn on `orgstruct-mode'."
8449 (orgstruct-mode 1))
8451 (defvar org-fb-vars nil)
8452 (make-variable-buffer-local 'org-fb-vars)
8453 (defun orgstruct++-mode (&optional arg)
8454 "Toggle `orgstruct-mode', the enhanced version of it.
8455 In addition to setting orgstruct-mode, this also exports all
8456 indentation and autofilling variables from org-mode into the
8457 buffer. It will also recognize item context in multiline items."
8458 (interactive "P")
8459 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8460 (if (< arg 1)
8461 (progn (orgstruct-mode -1)
8462 (mapc (lambda(v)
8463 (org-set-local (car v)
8464 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8465 org-fb-vars))
8466 (orgstruct-mode 1)
8467 (setq org-fb-vars nil)
8468 (let (var val)
8469 (mapc
8470 (lambda (x)
8471 (when (string-match
8472 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8473 (symbol-name (car x)))
8474 (setq var (car x) val (nth 1 x))
8475 (push (list var `(quote ,(eval var))) org-fb-vars)
8476 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8477 org-local-vars)
8478 (org-set-local 'orgstruct-is-++ t))))
8480 (defvar orgstruct-is-++ nil
8481 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8482 (make-variable-buffer-local 'orgstruct-is-++)
8484 ;;;###autoload
8485 (defun turn-on-orgstruct++ ()
8486 "Unconditionally turn on `orgstruct++-mode'."
8487 (orgstruct++-mode 1))
8489 (defun orgstruct-error ()
8490 "Error when there is no default binding for a structure key."
8491 (interactive)
8492 (error "This key has no function outside structure elements"))
8494 (defun orgstruct-setup ()
8495 "Setup orgstruct keymaps."
8496 (let ((nfunc 0)
8497 (bindings
8498 (list
8499 '([(meta up)] org-metaup)
8500 '([(meta down)] org-metadown)
8501 '([(meta left)] org-metaleft)
8502 '([(meta right)] org-metaright)
8503 '([(meta shift up)] org-shiftmetaup)
8504 '([(meta shift down)] org-shiftmetadown)
8505 '([(meta shift left)] org-shiftmetaleft)
8506 '([(meta shift right)] org-shiftmetaright)
8507 '([?\e (up)] org-metaup)
8508 '([?\e (down)] org-metadown)
8509 '([?\e (left)] org-metaleft)
8510 '([?\e (right)] org-metaright)
8511 '([?\e (shift up)] org-shiftmetaup)
8512 '([?\e (shift down)] org-shiftmetadown)
8513 '([?\e (shift left)] org-shiftmetaleft)
8514 '([?\e (shift right)] org-shiftmetaright)
8515 '([(shift up)] org-shiftup)
8516 '([(shift down)] org-shiftdown)
8517 '([(shift left)] org-shiftleft)
8518 '([(shift right)] org-shiftright)
8519 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8520 '("\M-q" fill-paragraph)
8521 '("\C-c^" org-sort)
8522 '("\C-c-" org-cycle-list-bullet)))
8523 elt key fun cmd)
8524 (while (setq elt (pop bindings))
8525 (setq nfunc (1+ nfunc))
8526 (setq key (org-key (car elt))
8527 fun (nth 1 elt)
8528 cmd (orgstruct-make-binding fun nfunc key))
8529 (org-defkey orgstruct-mode-map key cmd))
8531 ;; Special treatment needed for TAB and RET
8532 (org-defkey orgstruct-mode-map [(tab)]
8533 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8534 (org-defkey orgstruct-mode-map "\C-i"
8535 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8537 (org-defkey orgstruct-mode-map "\M-\C-m"
8538 (orgstruct-make-binding 'org-insert-heading 105
8539 "\M-\C-m" [(meta return)]))
8540 (org-defkey orgstruct-mode-map [(meta return)]
8541 (orgstruct-make-binding 'org-insert-heading 106
8542 [(meta return)] "\M-\C-m"))
8544 (org-defkey orgstruct-mode-map [(shift meta return)]
8545 (orgstruct-make-binding 'org-insert-todo-heading 107
8546 [(meta return)] "\M-\C-m"))
8548 (org-defkey orgstruct-mode-map "\e\C-m"
8549 (orgstruct-make-binding 'org-insert-heading 108
8550 "\e\C-m" [?\e (return)]))
8551 (org-defkey orgstruct-mode-map [?\e (return)]
8552 (orgstruct-make-binding 'org-insert-heading 109
8553 [?\e (return)] "\e\C-m"))
8554 (org-defkey orgstruct-mode-map [?\e (shift return)]
8555 (orgstruct-make-binding 'org-insert-todo-heading 110
8556 [?\e (return)] "\e\C-m"))
8558 (unless org-local-vars
8559 (setq org-local-vars (org-get-local-variables)))
8563 (defun orgstruct-make-binding (fun n &rest keys)
8564 "Create a function for binding in the structure minor mode.
8565 FUN is the command to call inside a table. N is used to create a unique
8566 command name. KEYS are keys that should be checked in for a command
8567 to execute outside of tables."
8568 (eval
8569 (list 'defun
8570 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8571 '(arg)
8572 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8573 "Outside of structure, run the binding of `"
8574 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8575 "'.")
8576 '(interactive "p")
8577 (list 'if
8578 `(org-context-p 'headline 'item
8579 (and orgstruct-is-++
8580 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8581 'item-body))
8582 (list 'org-run-like-in-org-mode (list 'quote fun))
8583 (list 'let '(orgstruct-mode)
8584 (list 'call-interactively
8585 (append '(or)
8586 (mapcar (lambda (k)
8587 (list 'key-binding k))
8588 keys)
8589 '('orgstruct-error))))))))
8591 (defun org-context-p (&rest contexts)
8592 "Check if local context is any of CONTEXTS.
8593 Possible values in the list of contexts are `table', `headline', and `item'."
8594 (let ((pos (point)))
8595 (goto-char (point-at-bol))
8596 (prog1 (or (and (memq 'table contexts)
8597 (looking-at "[ \t]*|"))
8598 (and (memq 'headline contexts)
8599 (looking-at org-outline-regexp))
8600 (and (memq 'item contexts)
8601 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8602 (and (memq 'item-body contexts)
8603 (org-in-item-p)))
8604 (goto-char pos))))
8606 (defun org-get-local-variables ()
8607 "Return a list of all local variables in an Org mode buffer."
8608 (let (varlist)
8609 (with-current-buffer (get-buffer-create "*Org tmp*")
8610 (erase-buffer)
8611 (org-mode)
8612 (setq varlist (buffer-local-variables)))
8613 (kill-buffer "*Org tmp*")
8614 (delq nil
8615 (mapcar
8616 (lambda (x)
8617 (setq x
8618 (if (symbolp x)
8619 (list x)
8620 (list (car x) (list 'quote (cdr x)))))
8621 (if (string-match
8622 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8623 (symbol-name (car x)))
8624 x nil))
8625 varlist))))
8627 (defun org-clone-local-variables (from-buffer &optional regexp)
8628 "Clone local variables from FROM-BUFFER.
8629 Optional argument REGEXP selects variables to clone."
8630 (mapc
8631 (lambda (pair)
8632 (and (symbolp (car pair))
8633 (or (null regexp)
8634 (string-match regexp (symbol-name (car pair))))
8635 (set (make-local-variable (car pair))
8636 (cdr pair))))
8637 (buffer-local-variables from-buffer)))
8639 ;;;###autoload
8640 (defun org-run-like-in-org-mode (cmd)
8641 "Run a command, pretending that the current buffer is in Org-mode.
8642 This will temporarily bind local variables that are typically bound in
8643 Org-mode to the values they have in Org-mode, and then interactively
8644 call CMD."
8645 (org-load-modules-maybe)
8646 (unless org-local-vars
8647 (setq org-local-vars (org-get-local-variables)))
8648 (eval (list 'let org-local-vars
8649 (list 'call-interactively (list 'quote cmd)))))
8651 ;;;; Archiving
8653 (defun org-get-category (&optional pos force-refresh)
8654 "Get the category applying to position POS."
8655 (save-match-data
8656 (if force-refresh (org-refresh-category-properties))
8657 (let ((pos (or pos (point))))
8658 (or (get-text-property pos 'org-category)
8659 (progn (org-refresh-category-properties)
8660 (get-text-property pos 'org-category))))))
8662 (defun org-refresh-category-properties ()
8663 "Refresh category text properties in the buffer."
8664 (let ((inhibit-read-only t)
8665 (def-cat (cond
8666 ((null org-category)
8667 (if buffer-file-name
8668 (file-name-sans-extension
8669 (file-name-nondirectory buffer-file-name))
8670 "???"))
8671 ((symbolp org-category) (symbol-name org-category))
8672 (t org-category)))
8673 beg end cat pos optionp)
8674 (org-unmodified
8675 (save-excursion
8676 (save-restriction
8677 (widen)
8678 (goto-char (point-min))
8679 (put-text-property (point) (point-max) 'org-category def-cat)
8680 (while (re-search-forward
8681 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8682 (setq pos (match-end 0)
8683 optionp (equal (char-after (match-beginning 0)) ?#)
8684 cat (org-trim (match-string 2)))
8685 (if optionp
8686 (setq beg (point-at-bol) end (point-max))
8687 (org-back-to-heading t)
8688 (setq beg (point) end (org-end-of-subtree t t)))
8689 (put-text-property beg end 'org-category cat)
8690 (put-text-property beg end 'org-category-position beg)
8691 (goto-char pos)))))))
8694 ;;;; Link Stuff
8696 ;;; Link abbreviations
8698 (defun org-link-expand-abbrev (link)
8699 "Apply replacements as defined in `org-link-abbrev-alist'."
8700 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8701 (let* ((key (match-string 1 link))
8702 (as (or (assoc key org-link-abbrev-alist-local)
8703 (assoc key org-link-abbrev-alist)))
8704 (tag (and (match-end 2) (match-string 3 link)))
8705 rpl)
8706 (if (not as)
8707 link
8708 (setq rpl (cdr as))
8709 (cond
8710 ((symbolp rpl) (funcall rpl tag))
8711 ((string-match "%(\\([^)]+\\))" rpl)
8712 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8713 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8714 ((string-match "%h" rpl)
8715 (replace-match (url-hexify-string (or tag "")) t t rpl))
8716 (t (concat rpl tag)))))
8717 link))
8719 ;;; Storing and inserting links
8721 (defvar org-insert-link-history nil
8722 "Minibuffer history for links inserted with `org-insert-link'.")
8724 (defvar org-stored-links nil
8725 "Contains the links stored with `org-store-link'.")
8727 (defvar org-store-link-plist nil
8728 "Plist with info about the most recently link created with `org-store-link'.")
8730 (defvar org-link-protocols nil
8731 "Link protocols added to Org-mode using `org-add-link-type'.")
8733 (defvar org-store-link-functions nil
8734 "List of functions that are called to create and store a link.
8735 Each function will be called in turn until one returns a non-nil
8736 value. Each function should check if it is responsible for creating
8737 this link (for example by looking at the major mode).
8738 If not, it must exit and return nil.
8739 If yes, it should return a non-nil value after a calling
8740 `org-store-link-props' with a list of properties and values.
8741 Special properties are:
8743 :type The link prefix, like \"http\". This must be given.
8744 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8745 This is obligatory as well.
8746 :description Optional default description for the second pair
8747 of brackets in an Org-mode link. The user can still change
8748 this when inserting this link into an Org-mode buffer.
8750 In addition to these, any additional properties can be specified
8751 and then used in remember templates.")
8753 (defun org-add-link-type (type &optional follow export)
8754 "Add TYPE to the list of `org-link-types'.
8755 Re-compute all regular expressions depending on `org-link-types'
8757 FOLLOW and EXPORT are two functions.
8759 FOLLOW should take the link path as the single argument and do whatever
8760 is necessary to follow the link, for example find a file or display
8761 a mail message.
8763 EXPORT should format the link path for export to one of the export formats.
8764 It should be a function accepting three arguments:
8766 path the path of the link, the text after the prefix (like \"http:\")
8767 desc the description of the link, if any, or a description added by
8768 org-export-normalize-links if there is none
8769 format the export format, a symbol like `html' or `latex' or `ascii'..
8771 The function may use the FORMAT information to return different values
8772 depending on the format. The return value will be put literally into
8773 the exported file. If the return value is nil, this means Org should
8774 do what it normally does with links which do not have EXPORT defined.
8776 Org-mode has a built-in default for exporting links. If you are happy with
8777 this default, there is no need to define an export function for the link
8778 type. For a simple example of an export function, see `org-bbdb.el'."
8779 (add-to-list 'org-link-types type t)
8780 (org-make-link-regexps)
8781 (if (assoc type org-link-protocols)
8782 (setcdr (assoc type org-link-protocols) (list follow export))
8783 (push (list type follow export) org-link-protocols)))
8785 (defvar org-agenda-buffer-name)
8787 ;;;###autoload
8788 (defun org-store-link (arg)
8789 "\\<org-mode-map>Store an org-link to the current location.
8790 This link is added to `org-stored-links' and can later be inserted
8791 into an org-buffer with \\[org-insert-link].
8793 For some link types, a prefix arg is interpreted:
8794 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8795 For file links, arg negates `org-context-in-file-links'."
8796 (interactive "P")
8797 (org-load-modules-maybe)
8798 (setq org-store-link-plist nil) ; reset
8799 (org-with-limited-levels
8800 (let (link cpltxt desc description search txt custom-id agenda-link)
8801 (cond
8803 ((run-hook-with-args-until-success 'org-store-link-functions)
8804 (setq link (plist-get org-store-link-plist :link)
8805 desc (or (plist-get org-store-link-plist :description) link)))
8807 ((org-src-edit-buffer-p)
8808 (let (label gc)
8809 (while (or (not label)
8810 (save-excursion
8811 (save-restriction
8812 (widen)
8813 (goto-char (point-min))
8814 (re-search-forward
8815 (regexp-quote (format org-coderef-label-format label))
8816 nil t))))
8817 (when label (message "Label exists already") (sit-for 2))
8818 (setq label (read-string "Code line label: " label)))
8819 (end-of-line 1)
8820 (setq link (format org-coderef-label-format label))
8821 (setq gc (- 79 (length link)))
8822 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8823 (insert link)
8824 (setq link (concat "(" label ")") desc nil)))
8826 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8827 ;; We are in the agenda, link to referenced location
8828 (let ((m (or (get-text-property (point) 'org-hd-marker)
8829 (get-text-property (point) 'org-marker))))
8830 (when m
8831 (org-with-point-at m
8832 (setq agenda-link
8833 (if (org-called-interactively-p 'any)
8834 (call-interactively 'org-store-link)
8835 (org-store-link nil)))))))
8837 ((eq major-mode 'calendar-mode)
8838 (let ((cd (calendar-cursor-to-date)))
8839 (setq link
8840 (format-time-string
8841 (car org-time-stamp-formats)
8842 (apply 'encode-time
8843 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8844 nil nil nil))))
8845 (org-store-link-props :type "calendar" :date cd)))
8847 ((eq major-mode 'w3-mode)
8848 (setq cpltxt (if (and (buffer-name)
8849 (not (string-match "Untitled" (buffer-name))))
8850 (buffer-name)
8851 (url-view-url t))
8852 link (url-view-url t))
8853 (org-store-link-props :type "w3" :url (url-view-url t)))
8855 ((eq major-mode 'w3m-mode)
8856 (setq cpltxt (or w3m-current-title w3m-current-url)
8857 link w3m-current-url)
8858 (org-store-link-props :type "w3m" :url (url-view-url t)))
8860 ((setq search (run-hook-with-args-until-success
8861 'org-create-file-search-functions))
8862 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8863 "::" search))
8864 (setq cpltxt (or description link)))
8866 ((eq major-mode 'image-mode)
8867 (setq cpltxt (concat "file:"
8868 (abbreviate-file-name buffer-file-name))
8869 link cpltxt)
8870 (org-store-link-props :type "image" :file buffer-file-name))
8872 ((eq major-mode 'dired-mode)
8873 ;; link to the file in the current line
8874 (let ((file (dired-get-filename nil t)))
8875 (setq file (if file
8876 (abbreviate-file-name
8877 (expand-file-name (dired-get-filename nil t)))
8878 ;; otherwise, no file so use current directory.
8879 default-directory))
8880 (setq cpltxt (concat "file:" file)
8881 link cpltxt)))
8883 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8884 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8885 (cond
8886 ((org-in-regexp "<<\\(.*?\\)>>")
8887 (setq cpltxt
8888 (concat "file:"
8889 (abbreviate-file-name
8890 (buffer-file-name (buffer-base-buffer)))
8891 "::" (match-string 1))
8892 link cpltxt))
8893 ((and (featurep 'org-id)
8894 (or (eq org-link-to-org-use-id t)
8895 (and (org-called-interactively-p 'any)
8896 (or (eq org-link-to-org-use-id 'create-if-interactive)
8897 (and (eq org-link-to-org-use-id
8898 'create-if-interactive-and-no-custom-id)
8899 (not custom-id))))
8900 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8901 ;; We can make a link using the ID.
8902 (setq link (condition-case nil
8903 (prog1 (org-id-store-link)
8904 (setq desc (plist-get org-store-link-plist :description)))
8905 (error
8906 ;; probably before first headline, link to file only
8907 (concat "file:"
8908 (abbreviate-file-name
8909 (buffer-file-name (buffer-base-buffer))))))))
8911 ;; Just link to current headline
8912 (setq cpltxt (concat "file:"
8913 (abbreviate-file-name
8914 (buffer-file-name (buffer-base-buffer)))))
8915 ;; Add a context search string
8916 (when (org-xor org-context-in-file-links arg)
8917 (setq txt (cond
8918 ((org-at-heading-p) nil)
8919 ((org-region-active-p)
8920 (buffer-substring (region-beginning) (region-end)))
8921 (t nil)))
8922 (when (or (null txt) (string-match "\\S-" txt))
8923 (setq cpltxt
8924 (concat cpltxt "::"
8925 (condition-case nil
8926 (org-make-org-heading-search-string txt)
8927 (error "")))
8928 desc (or (nth 4 (ignore-errors
8929 (org-heading-components))) "NONE"))))
8930 (if (string-match "::\\'" cpltxt)
8931 (setq cpltxt (substring cpltxt 0 -2)))
8932 (setq link cpltxt))))
8934 ((buffer-file-name (buffer-base-buffer))
8935 ;; Just link to this file here.
8936 (setq cpltxt (concat "file:"
8937 (abbreviate-file-name
8938 (buffer-file-name (buffer-base-buffer)))))
8939 ;; Add a context string
8940 (when (org-xor org-context-in-file-links arg)
8941 (setq txt (if (org-region-active-p)
8942 (buffer-substring (region-beginning) (region-end))
8943 (buffer-substring (point-at-bol) (point-at-eol))))
8944 ;; Only use search option if there is some text.
8945 (when (string-match "\\S-" txt)
8946 (setq cpltxt
8947 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8948 desc "NONE")))
8949 (setq link cpltxt))
8951 ((org-called-interactively-p 'interactive)
8952 (error "Cannot link to a buffer which is not visiting a file"))
8954 (t (setq link nil)))
8956 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8957 (setq link (or link cpltxt)
8958 desc (or desc cpltxt))
8959 (if (equal desc "NONE") (setq desc nil))
8961 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8962 (progn
8963 (setq org-stored-links
8964 (cons (list link desc) org-stored-links))
8965 (message "Stored: %s" (or desc link))
8966 (when custom-id
8967 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8968 "::#" custom-id))
8969 (setq org-stored-links
8970 (cons (list link desc) org-stored-links))))
8971 (or agenda-link (and link (org-make-link-string link desc)))))))
8973 (defun org-store-link-props (&rest plist)
8974 "Store link properties, extract names and addresses."
8975 (let (x adr)
8976 (when (setq x (plist-get plist :from))
8977 (setq adr (mail-extract-address-components x))
8978 (setq plist (plist-put plist :fromname (car adr)))
8979 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8980 (when (setq x (plist-get plist :to))
8981 (setq adr (mail-extract-address-components x))
8982 (setq plist (plist-put plist :toname (car adr)))
8983 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8984 (let ((from (plist-get plist :from))
8985 (to (plist-get plist :to)))
8986 (when (and from to org-from-is-user-regexp)
8987 (setq plist
8988 (plist-put plist :fromto
8989 (if (string-match org-from-is-user-regexp from)
8990 (concat "to %t")
8991 (concat "from %f"))))))
8992 (setq org-store-link-plist plist))
8994 (defun org-add-link-props (&rest plist)
8995 "Add these properties to the link property list."
8996 (let (key value)
8997 (while plist
8998 (setq key (pop plist) value (pop plist))
8999 (setq org-store-link-plist
9000 (plist-put org-store-link-plist key value)))))
9002 (defun org-email-link-description (&optional fmt)
9003 "Return the description part of an email link.
9004 This takes information from `org-store-link-plist' and formats it
9005 according to FMT (default from `org-email-link-description-format')."
9006 (setq fmt (or fmt org-email-link-description-format))
9007 (let* ((p org-store-link-plist)
9008 (to (plist-get p :toaddress))
9009 (from (plist-get p :fromaddress))
9010 (table
9011 (list
9012 (cons "%c" (plist-get p :fromto))
9013 (cons "%F" (plist-get p :from))
9014 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9015 (cons "%T" (plist-get p :to))
9016 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9017 (cons "%s" (plist-get p :subject))
9018 (cons "%d" (plist-get p :date))
9019 (cons "%m" (plist-get p :message-id)))))
9020 (when (string-match "%c" fmt)
9021 ;; Check if the user wrote this message
9022 (if (and org-from-is-user-regexp from to
9023 (save-match-data (string-match org-from-is-user-regexp from)))
9024 (setq fmt (replace-match "to %t" t t fmt))
9025 (setq fmt (replace-match "from %f" t t fmt))))
9026 (org-replace-escapes fmt table)))
9028 (defun org-make-org-heading-search-string (&optional string heading)
9029 "Make search string for STRING or current headline."
9030 (interactive)
9031 (let ((s (or string (org-get-heading)))
9032 (lines org-context-in-file-links))
9033 (unless (and string (not heading))
9034 ;; We are using a headline, clean up garbage in there.
9035 (if (string-match org-todo-regexp s)
9036 (setq s (replace-match "" t t s)))
9037 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9038 (setq s (replace-match "" t t s)))
9039 (setq s (org-trim s))
9040 (if (string-match (concat "^\\(" org-quote-string "\\|"
9041 org-comment-string "\\)") s)
9042 (setq s (replace-match "" t t s)))
9043 (while (string-match org-ts-regexp s)
9044 (setq s (replace-match "" t t s))))
9045 (or string (setq s (concat "*" s))) ; Add * for headlines
9046 (when (and string (integerp lines) (> lines 0))
9047 (let ((slines (org-split-string s "\n")))
9048 (when (< lines (length slines))
9049 (setq s (mapconcat
9050 'identity
9051 (reverse (nthcdr (- (length slines) lines)
9052 (reverse slines))) "\n")))))
9053 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9055 (defun org-make-link-string (link &optional description)
9056 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9057 (unless (string-match "\\S-" link)
9058 (error "Empty link"))
9059 (when (and description
9060 (stringp description)
9061 (not (string-match "\\S-" description)))
9062 (setq description nil))
9063 (when (stringp description)
9064 ;; Remove brackets from the description, they are fatal.
9065 (while (string-match "\\[" description)
9066 (setq description (replace-match "{" t t description)))
9067 (while (string-match "\\]" description)
9068 (setq description (replace-match "}" t t description))))
9069 (when (equal link description)
9070 ;; No description needed, it is identical
9071 (setq description nil))
9072 (when (and (not description)
9073 (not (string-match (org-image-file-name-regexp) link))
9074 (not (equal link (org-link-escape link))))
9075 (setq description (org-extract-attributes link)))
9076 (setq link
9077 (cond ((string-match (org-image-file-name-regexp) link) link)
9078 ((string-match org-link-types-re link)
9079 (concat (match-string 1 link)
9080 (org-link-escape (substring link (match-end 1)))))
9081 (t (org-link-escape link))))
9082 (concat "[[" link "]"
9083 (if description (concat "[" description "]") "")
9084 "]"))
9086 (defconst org-link-escape-chars
9087 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9088 "List of characters that should be escaped in link.
9089 This is the list that is used for internal purposes.")
9091 (defconst org-link-escape-chars-browser
9092 '(?\ )
9093 "List of escapes for characters that are problematic in links.
9094 This is the list that is used before handing over to the browser.")
9096 (defun org-link-escape (text &optional table merge)
9097 "Return percent escaped representation of TEXT.
9098 TEXT is a string with the text to escape.
9099 Optional argument TABLE is a list with characters that should be
9100 escaped. When nil, `org-link-escape-chars' is used.
9101 If optional argument MERGE is set, merge TABLE into
9102 `org-link-escape-chars'."
9103 (cond
9104 ((and table merge)
9105 (mapc (lambda (defchr)
9106 (unless (member defchr table)
9107 (setq table (cons defchr table)))) org-link-escape-chars))
9108 ((null table)
9109 (setq table org-link-escape-chars)))
9110 (mapconcat
9111 (lambda (char)
9112 (if (or (member char table)
9113 (and (or (< char 32) (= char 37) (> char 126))
9114 org-url-hexify-p))
9115 (mapconcat (lambda (sequence-element)
9116 (format "%%%.2X" sequence-element))
9117 (or (encode-coding-char char 'utf-8)
9118 (error "Unable to percent escape character: %s"
9119 (char-to-string char))) "")
9120 (char-to-string char))) text ""))
9122 (defun org-link-unescape (str)
9123 "Unhex hexified Unicode strings as returned from the JavaScript function
9124 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9125 (unless (and (null str) (string= "" str))
9126 (let ((pos 0) (case-fold-search t) unhexed)
9127 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9128 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9129 (setq str (replace-match unhexed t t str))
9130 (setq pos (+ pos (length unhexed))))))
9131 str)
9133 (defun org-link-unescape-compound (hex)
9134 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9135 Note: this function also decodes single byte encodings like
9136 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9137 (save-match-data
9138 (let* ((bytes (cdr (split-string hex "%")))
9139 (ret "")
9140 (eat 0)
9141 (sum 0))
9142 (while bytes
9143 (let* ((val (string-to-number (pop bytes) 16))
9144 (shift-xor
9145 (if (= 0 eat)
9146 (cond
9147 ((>= val 252) (cons 6 252))
9148 ((>= val 248) (cons 5 248))
9149 ((>= val 240) (cons 4 240))
9150 ((>= val 224) (cons 3 224))
9151 ((>= val 192) (cons 2 192))
9152 (t (cons 0 0)))
9153 (cons 6 128))))
9154 (if (>= val 192) (setq eat (car shift-xor)))
9155 (setq val (logxor val (cdr shift-xor)))
9156 (setq sum (+ (lsh sum (car shift-xor)) val))
9157 (if (> eat 0) (setq eat (- eat 1)))
9158 (cond
9159 ((= 0 eat) ;multi byte
9160 (setq ret (concat ret (org-char-to-string sum)))
9161 (setq sum 0))
9162 ((not bytes) ; single byte(s)
9163 (setq ret (org-link-unescape-single-byte-sequence hex))))
9164 )) ;; end (while bytes
9165 ret )))
9167 (defun org-link-unescape-single-byte-sequence (hex)
9168 "Unhexify hex-encoded single byte character sequences."
9169 (mapconcat (lambda (byte)
9170 (char-to-string (string-to-number byte 16)))
9171 (cdr (split-string hex "%")) ""))
9173 (defun org-xor (a b)
9174 "Exclusive or."
9175 (if a (not b) b))
9177 (defun org-fixup-message-id-for-http (s)
9178 "Replace special characters in a message id, so it can be used in an http query."
9179 (when (string-match "%" s)
9180 (setq s (mapconcat (lambda (c)
9181 (if (eq c ?%)
9182 "%25"
9183 (char-to-string c)))
9184 s "")))
9185 (while (string-match "<" s)
9186 (setq s (replace-match "%3C" t t s)))
9187 (while (string-match ">" s)
9188 (setq s (replace-match "%3E" t t s)))
9189 (while (string-match "@" s)
9190 (setq s (replace-match "%40" t t s)))
9193 (defun org-link-prettify (link)
9194 "Return a human-readable representation of LINK.
9195 The car of LINK must be a raw link the cdr of LINK must be either
9196 a link description or nil."
9197 (let ((desc (or (cadr link) "<no description>")))
9198 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9199 "<" (car link) ">")))
9201 ;;;###autoload
9202 (defun org-insert-link-global ()
9203 "Insert a link like Org-mode does.
9204 This command can be called in any mode to insert a link in Org-mode syntax."
9205 (interactive)
9206 (org-load-modules-maybe)
9207 (org-run-like-in-org-mode 'org-insert-link))
9209 (defun org-insert-all-links (&optional keep)
9210 "Insert all links in `org-stored-links'."
9211 (interactive "P")
9212 (let ((links (copy-sequence org-stored-links)) l)
9213 (while (setq l (if keep (pop links) (pop org-stored-links)))
9214 (insert "- ")
9215 (org-insert-link nil (car l) (cadr l))
9216 (insert "\n"))))
9218 (defun org-link-fontify-links-to-this-file ()
9219 "Fontify links to the current file in `org-stored-links'."
9220 (let ((f (buffer-file-name)) a b)
9221 (setq a (mapcar (lambda(l)
9222 (let ((ll (car l)))
9223 (when (and (string-match "^file:\\(.+\\)::" ll)
9224 (equal f (expand-file-name (match-string 1 ll))))
9225 ll)))
9226 org-stored-links))
9227 (when (featurep 'org-id)
9228 (setq b (mapcar (lambda(l)
9229 (let ((ll (car l)))
9230 (when (and (string-match "^id:\\(.+\\)$" ll)
9231 (equal f (expand-file-name
9232 (or (org-id-find-id-file
9233 (match-string 1 ll)) ""))))
9234 ll)))
9235 org-stored-links)))
9236 (mapcar (lambda(l)
9237 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9238 (delq nil (append a b)))))
9240 (defvar org-link-links-in-this-file nil)
9241 (defun org-insert-link (&optional complete-file link-location default-description)
9242 "Insert a link. At the prompt, enter the link.
9244 Completion can be used to insert any of the link protocol prefixes like
9245 http or ftp in use.
9247 The history can be used to select a link previously stored with
9248 `org-store-link'. When the empty string is entered (i.e. if you just
9249 press RET at the prompt), the link defaults to the most recently
9250 stored link. As SPC triggers completion in the minibuffer, you need to
9251 use M-SPC or C-q SPC to force the insertion of a space character.
9253 You will also be prompted for a description, and if one is given, it will
9254 be displayed in the buffer instead of the link.
9256 If there is already a link at point, this command will allow you to edit link
9257 and description parts.
9259 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9260 be selected using completion. The path to the file will be relative to the
9261 current directory if the file is in the current directory or a subdirectory.
9262 Otherwise, the link will be the absolute path as completed in the minibuffer
9263 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9264 option `org-link-file-path-type'.
9266 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9267 the current directory or below.
9269 With three \\[universal-argument] prefixes, negate the meaning of
9270 `org-keep-stored-link-after-insertion'.
9272 If `org-make-link-description-function' is non-nil, this function will be
9273 called with the link target, and the result will be the default
9274 link description.
9276 If the LINK-LOCATION parameter is non-nil, this value will be
9277 used as the link location instead of reading one interactively.
9279 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9280 be used as the default description."
9281 (interactive "P")
9282 (let* ((wcf (current-window-configuration))
9283 (region (if (org-region-active-p)
9284 (buffer-substring (region-beginning) (region-end))))
9285 (remove (and region (list (region-beginning) (region-end))))
9286 (desc region)
9287 tmphist ; byte-compile incorrectly complains about this
9288 (link link-location)
9289 entry file all-prefixes auto-desc)
9290 (cond
9291 (link-location) ; specified by arg, just use it.
9292 ((org-in-regexp org-bracket-link-regexp 1)
9293 ;; We do have a link at point, and we are going to edit it.
9294 (setq remove (list (match-beginning 0) (match-end 0)))
9295 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9296 (setq link (read-string "Link: "
9297 (org-link-unescape
9298 (org-match-string-no-properties 1)))))
9299 ((or (org-in-regexp org-angle-link-re)
9300 (org-in-regexp org-plain-link-re))
9301 ;; Convert to bracket link
9302 (setq remove (list (match-beginning 0) (match-end 0))
9303 link (read-string "Link: "
9304 (org-remove-angle-brackets (match-string 0)))))
9305 ((member complete-file '((4) (16)))
9306 ;; Completing read for file names.
9307 (setq link (org-file-complete-link complete-file)))
9309 ;; Read link, with completion for stored links.
9310 (org-link-fontify-links-to-this-file)
9311 (org-switch-to-buffer-other-window "*Org Links*")
9312 (with-current-buffer "*Org Links*"
9313 (erase-buffer)
9314 (insert "Insert a link.
9315 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9316 (when org-stored-links
9317 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9318 (insert (mapconcat 'org-link-prettify
9319 (reverse org-stored-links) "\n")))
9320 (goto-char (point-min)))
9321 (let ((cw (selected-window)))
9322 (select-window (get-buffer-window "*Org Links*" 'visible))
9323 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9324 (unless (pos-visible-in-window-p (point-max))
9325 (org-fit-window-to-buffer))
9326 (and (window-live-p cw) (select-window cw)))
9327 ;; Fake a link history, containing the stored links.
9328 (setq tmphist (append (mapcar 'car org-stored-links)
9329 org-insert-link-history))
9330 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9331 (mapcar 'car org-link-abbrev-alist)
9332 org-link-types))
9333 (unwind-protect
9334 (progn
9335 (setq link
9336 (let ((org-completion-use-ido nil)
9337 (org-completion-use-iswitchb nil))
9338 (org-completing-read
9339 "Link: "
9340 (append
9341 (mapcar (lambda (x) (list (concat x ":")))
9342 all-prefixes)
9343 (mapcar 'car org-stored-links)
9344 (mapcar 'cadr org-stored-links))
9345 nil nil nil
9346 'tmphist
9347 (caar org-stored-links))))
9348 (if (not (string-match "\\S-" link))
9349 (error "No link selected"))
9350 (mapc (lambda(l)
9351 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9352 org-stored-links)
9353 (if (or (member link all-prefixes)
9354 (and (equal ":" (substring link -1))
9355 (member (substring link 0 -1) all-prefixes)
9356 (setq link (substring link 0 -1))))
9357 (setq link (org-link-try-special-completion link))))
9358 (set-window-configuration wcf)
9359 (kill-buffer "*Org Links*"))
9360 (setq entry (assoc link org-stored-links))
9361 (or entry (push link org-insert-link-history))
9362 (setq desc (or desc (nth 1 entry)))))
9364 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9365 (not org-keep-stored-link-after-insertion))
9366 (setq org-stored-links (delq (assoc link org-stored-links)
9367 org-stored-links)))
9369 (if (string-match org-plain-link-re link)
9370 ;; URL-like link, normalize the use of angular brackets.
9371 (setq link (org-remove-angle-brackets link)))
9373 ;; Check if we are linking to the current file with a search option
9374 ;; If yes, simplify the link by using only the search option.
9375 (when (and buffer-file-name
9376 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9377 (let* ((path (match-string 1 link))
9378 (case-fold-search nil)
9379 (search (match-string 2 link)))
9380 (save-match-data
9381 (if (equal (file-truename buffer-file-name) (file-truename path))
9382 ;; We are linking to this same file, with a search option
9383 (setq link search)))))
9385 ;; Check if we can/should use a relative path. If yes, simplify the link
9386 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9387 (let* ((type (match-string 1 link))
9388 (path (match-string 2 link))
9389 (origpath path)
9390 (case-fold-search nil))
9391 (cond
9392 ((or (eq org-link-file-path-type 'absolute)
9393 (equal complete-file '(16)))
9394 (setq path (abbreviate-file-name (expand-file-name path))))
9395 ((eq org-link-file-path-type 'noabbrev)
9396 (setq path (expand-file-name path)))
9397 ((eq org-link-file-path-type 'relative)
9398 (setq path (file-relative-name path)))
9400 (save-match-data
9401 (if (string-match (concat "^" (regexp-quote
9402 (expand-file-name
9403 (file-name-as-directory
9404 default-directory))))
9405 (expand-file-name path))
9406 ;; We are linking a file with relative path name.
9407 (setq path (substring (expand-file-name path)
9408 (match-end 0)))
9409 (setq path (abbreviate-file-name (expand-file-name path)))))))
9410 (setq link (concat type path))
9411 (if (equal desc origpath)
9412 (setq desc path))))
9414 (if org-make-link-description-function
9415 (setq desc (funcall org-make-link-description-function link desc))
9416 (if default-description (setq desc default-description)
9417 (setq desc (or (and auto-desc desc)
9418 (read-string "Description: " desc)))))
9420 (unless (string-match "\\S-" desc) (setq desc nil))
9421 (if remove (apply 'delete-region remove))
9422 (insert (org-make-link-string link desc))))
9424 (defun org-link-try-special-completion (type)
9425 "If there is completion support for link type TYPE, offer it."
9426 (let ((fun (intern (concat "org-" type "-complete-link"))))
9427 (if (functionp fun)
9428 (funcall fun)
9429 (read-string "Link (no completion support): " (concat type ":")))))
9431 (defun org-file-complete-link (&optional arg)
9432 "Create a file link using completion."
9433 (let (file link)
9434 (setq file (read-file-name "File: "))
9435 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9436 (pwd1 (file-name-as-directory (abbreviate-file-name
9437 (expand-file-name ".")))))
9438 (cond
9439 ((equal arg '(16))
9440 (setq link (concat
9441 "file:"
9442 (abbreviate-file-name (expand-file-name file)))))
9443 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9444 (setq link (concat "file:" (match-string 1 file))))
9445 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9446 (expand-file-name file))
9447 (setq link (concat
9448 "file:" (match-string 1 (expand-file-name file)))))
9449 (t (setq link (concat "file:" file)))))
9450 link))
9452 (defun org-completing-read (&rest args)
9453 "Completing-read with SPACE being a normal character."
9454 (let ((enable-recursive-minibuffers t)
9455 (minibuffer-local-completion-map
9456 (copy-keymap minibuffer-local-completion-map)))
9457 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9458 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9459 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9460 (apply 'org-icompleting-read args)))
9462 (defun org-completing-read-no-i (&rest args)
9463 (let (org-completion-use-ido org-completion-use-iswitchb)
9464 (apply 'org-completing-read args)))
9466 (defun org-iswitchb-completing-read (prompt choices &rest args)
9467 "Use iswitch as a completing-read replacement to choose from choices.
9468 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9469 from."
9470 (let* ((iswitchb-use-virtual-buffers nil)
9471 (iswitchb-make-buflist-hook
9472 (lambda ()
9473 (setq iswitchb-temp-buflist choices))))
9474 (iswitchb-read-buffer prompt)))
9476 (defun org-icompleting-read (&rest args)
9477 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9478 (org-without-partial-completion
9479 (if (and org-completion-use-ido
9480 (fboundp 'ido-completing-read)
9481 (boundp 'ido-mode) ido-mode
9482 (listp (second args)))
9483 (let ((ido-enter-matching-directory nil))
9484 (apply 'ido-completing-read (concat (car args))
9485 (if (consp (car (nth 1 args)))
9486 (mapcar 'car (nth 1 args))
9487 (nth 1 args))
9488 (cddr args)))
9489 (if (and org-completion-use-iswitchb
9490 (boundp 'iswitchb-mode) iswitchb-mode
9491 (listp (second args)))
9492 (apply 'org-iswitchb-completing-read (concat (car args))
9493 (if (consp (car (nth 1 args)))
9494 (mapcar 'car (nth 1 args))
9495 (nth 1 args))
9496 (cddr args))
9497 (apply 'completing-read args)))))
9499 (defun org-extract-attributes (s)
9500 "Extract the attributes cookie from a string and set as text property."
9501 (let (a attr (start 0) key value)
9502 (save-match-data
9503 (when (string-match "{{\\([^}]+\\)}}$" s)
9504 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9505 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9506 (setq key (match-string 1 a) value (match-string 2 a)
9507 start (match-end 0)
9508 attr (plist-put attr (intern key) value))))
9509 (org-add-props s nil 'org-attr attr))
9512 (defun org-extract-attributes-from-string (tag)
9513 (let (key value attr)
9514 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9515 (setq key (match-string 1 tag) value (match-string 2 tag)
9516 tag (replace-match "" t t tag)
9517 attr (plist-put attr (intern key) value)))
9518 (cons tag attr)))
9520 (defun org-attributes-to-string (plist)
9521 "Format a property list into an HTML attribute list."
9522 (let ((s "") key value)
9523 (while plist
9524 (setq key (pop plist) value (pop plist))
9525 (and value
9526 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9529 ;;; Opening/following a link
9531 (defvar org-link-search-failed nil)
9533 (defvar org-open-link-functions nil
9534 "Hook for functions finding a plain text link.
9535 These functions must take a single argument, the link content.
9536 They will be called for links that look like [[link text][description]]
9537 when LINK TEXT does not have a protocol like \"http:\" and does not look
9538 like a filename (e.g. \"./blue.png\").
9540 These functions will be called *before* Org attempts to resolve the
9541 link by doing text searches in the current buffer - so if you want a
9542 link \"[[target]]\" to still find \"<<target>>\", your function should
9543 handle this as a special case.
9545 When the function does handle the link, it must return a non-nil value.
9546 If it decides that it is not responsible for this link, it must return
9547 nil to indicate that that Org-mode can continue with other options
9548 like exact and fuzzy text search.")
9550 (defun org-next-link ()
9551 "Move forward to the next link.
9552 If the link is in hidden text, expose it."
9553 (interactive)
9554 (when (and org-link-search-failed (eq this-command last-command))
9555 (goto-char (point-min))
9556 (message "Link search wrapped back to beginning of buffer"))
9557 (setq org-link-search-failed nil)
9558 (let* ((pos (point))
9559 (ct (org-context))
9560 (a (assoc :link ct)))
9561 (if a (goto-char (nth 2 a)))
9562 (if (re-search-forward org-any-link-re nil t)
9563 (progn
9564 (goto-char (match-beginning 0))
9565 (if (outline-invisible-p) (org-show-context)))
9566 (goto-char pos)
9567 (setq org-link-search-failed t)
9568 (error "No further link found"))))
9570 (defun org-previous-link ()
9571 "Move backward to the previous link.
9572 If the link is in hidden text, expose it."
9573 (interactive)
9574 (when (and org-link-search-failed (eq this-command last-command))
9575 (goto-char (point-max))
9576 (message "Link search wrapped back to end of buffer"))
9577 (setq org-link-search-failed nil)
9578 (let* ((pos (point))
9579 (ct (org-context))
9580 (a (assoc :link ct)))
9581 (if a (goto-char (nth 1 a)))
9582 (if (re-search-backward org-any-link-re nil t)
9583 (progn
9584 (goto-char (match-beginning 0))
9585 (if (outline-invisible-p) (org-show-context)))
9586 (goto-char pos)
9587 (setq org-link-search-failed t)
9588 (error "No further link found"))))
9590 (defun org-translate-link (s)
9591 "Translate a link string if a translation function has been defined."
9592 (if (and org-link-translation-function
9593 (fboundp org-link-translation-function)
9594 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9595 (progn
9596 (setq s (funcall org-link-translation-function
9597 (match-string 1 s) (match-string 2 s)))
9598 (concat (car s) ":" (cdr s)))
9601 (defun org-translate-link-from-planner (type path)
9602 "Translate a link from Emacs Planner syntax so that Org can follow it.
9603 This is still an experimental function, your mileage may vary."
9604 (cond
9605 ((member type '("http" "https" "news" "ftp"))
9606 ;; standard Internet links are the same.
9607 nil)
9608 ((and (equal type "irc") (string-match "^//" path))
9609 ;; Planner has two / at the beginning of an irc link, we have 1.
9610 ;; We should have zero, actually....
9611 (setq path (substring path 1)))
9612 ((and (equal type "lisp") (string-match "^/" path))
9613 ;; Planner has a slash, we do not.
9614 (setq type "elisp" path (substring path 1)))
9615 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9616 ;; A typical message link. Planner has the id after the final slash,
9617 ;; we separate it with a hash mark
9618 (setq path (concat (match-string 1 path) "#"
9619 (org-remove-angle-brackets (match-string 2 path)))))
9621 (cons type path))
9623 (defun org-find-file-at-mouse (ev)
9624 "Open file link or URL at mouse."
9625 (interactive "e")
9626 (mouse-set-point ev)
9627 (org-open-at-point 'in-emacs))
9629 (defun org-open-at-mouse (ev)
9630 "Open file link or URL at mouse.
9631 See the docstring of `org-open-file' for details."
9632 (interactive "e")
9633 (mouse-set-point ev)
9634 (if (eq major-mode 'org-agenda-mode)
9635 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9636 (org-open-at-point))
9638 (defvar org-window-config-before-follow-link nil
9639 "The window configuration before following a link.
9640 This is saved in case the need arises to restore it.")
9642 (defvar org-open-link-marker (make-marker)
9643 "Marker pointing to the location where `org-open-at-point; was called.")
9645 ;;;###autoload
9646 (defun org-open-at-point-global ()
9647 "Follow a link like Org-mode does.
9648 This command can be called in any mode to follow a link that has
9649 Org-mode syntax."
9650 (interactive)
9651 (org-run-like-in-org-mode 'org-open-at-point))
9653 ;;;###autoload
9654 (defun org-open-link-from-string (s &optional arg reference-buffer)
9655 "Open a link in the string S, as if it was in Org-mode."
9656 (interactive "sLink: \nP")
9657 (let ((reference-buffer (or reference-buffer (current-buffer))))
9658 (with-temp-buffer
9659 (let ((org-inhibit-startup (not reference-buffer)))
9660 (org-mode)
9661 (insert s)
9662 (goto-char (point-min))
9663 (when reference-buffer
9664 (setq org-link-abbrev-alist-local
9665 (with-current-buffer reference-buffer
9666 org-link-abbrev-alist-local)))
9667 (org-open-at-point arg reference-buffer)))))
9669 (defvar org-open-at-point-functions nil
9670 "Hook that is run when following a link at point.
9672 Functions in this hook must return t if they identify and follow
9673 a link at point. If they don't find anything interesting at point,
9674 they must return nil.")
9676 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9677 (defun org-open-at-point (&optional arg reference-buffer)
9678 "Open link at or after point.
9679 If there is no link at point, this function will search forward up to
9680 the end of the current line.
9681 Normally, files will be opened by an appropriate application. If the
9682 optional prefix argument ARG is non-nil, Emacs will visit the file.
9683 With a double prefix argument, try to open outside of Emacs, in the
9684 application the system uses for this file type."
9685 (interactive "P")
9686 ;; if in a code block, then open the block's results
9687 (unless (call-interactively #'org-babel-open-src-block-result)
9688 (org-load-modules-maybe)
9689 (move-marker org-open-link-marker (point))
9690 (setq org-window-config-before-follow-link (current-window-configuration))
9691 (org-remove-occur-highlights nil nil t)
9692 (cond
9693 ((and (org-at-heading-p)
9694 (not (org-at-timestamp-p t))
9695 (not (org-in-regexp
9696 (concat org-plain-link-re "\\|"
9697 org-bracket-link-regexp "\\|"
9698 org-angle-link-re "\\|"
9699 "[ \t]:[^ \t\n]+:[ \t]*$")))
9700 (not (get-text-property (point) 'org-linked-text)))
9701 (or (org-offer-links-in-entry arg)
9702 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9703 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9704 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9705 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9706 (not (org-in-regexp org-bracket-link-regexp)))
9707 (org-footnote-action))
9709 (let (type path link line search (pos (point)))
9710 (catch 'match
9711 (save-excursion
9712 (skip-chars-forward "^]\n\r")
9713 (when (org-in-regexp org-bracket-link-regexp 1)
9714 (setq link (org-extract-attributes
9715 (org-link-unescape (org-match-string-no-properties 1))))
9716 (while (string-match " *\n *" link)
9717 (setq link (replace-match " " t t link)))
9718 (setq link (org-link-expand-abbrev link))
9719 (cond
9720 ((or (file-name-absolute-p link)
9721 (string-match "^\\.\\.?/" link))
9722 (setq type "file" path link))
9723 ((string-match org-link-re-with-space3 link)
9724 (setq type (match-string 1 link) path (match-string 2 link)))
9725 (t (setq type "thisfile" path link)))
9726 (throw 'match t)))
9728 (when (get-text-property (point) 'org-linked-text)
9729 (setq type "thisfile"
9730 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9731 (1+ (point)) (point))
9732 path (buffer-substring
9733 (or (previous-single-property-change pos 'org-linked-text)
9734 (point-min))
9735 (or (next-single-property-change pos 'org-linked-text)
9736 (point-max))))
9737 (throw 'match t))
9739 (save-excursion
9740 (when (or (org-in-regexp org-angle-link-re)
9741 (org-in-regexp org-plain-link-re))
9742 (setq type (match-string 1)
9743 path (org-link-unescape (match-string 2)))
9744 (throw 'match t)))
9745 (save-excursion
9746 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9747 (setq type "tags"
9748 path (match-string 1))
9749 (while (string-match ":" path)
9750 (setq path (replace-match "+" t t path)))
9751 (throw 'match t)))
9752 (when (org-in-regexp "<\\([^><\n]+\\)>")
9753 (setq type "tree-match"
9754 path (match-string 1))
9755 (throw 'match t)))
9756 (unless path
9757 (error "No link found"))
9759 ;; switch back to reference buffer
9760 ;; needed when if called in a temporary buffer through
9761 ;; org-open-link-from-string
9762 (with-current-buffer (or reference-buffer (current-buffer))
9764 ;; Remove any trailing spaces in path
9765 (if (string-match " +\\'" path)
9766 (setq path (replace-match "" t t path)))
9767 (if (and org-link-translation-function
9768 (fboundp org-link-translation-function))
9769 ;; Check if we need to translate the link
9770 (let ((tmp (funcall org-link-translation-function type path)))
9771 (setq type (car tmp) path (cdr tmp))))
9773 (cond
9775 ((assoc type org-link-protocols)
9776 (funcall (nth 1 (assoc type org-link-protocols)) path))
9778 ((equal type "mailto")
9779 (let ((cmd (car org-link-mailto-program))
9780 (args (cdr org-link-mailto-program)) args1
9781 (address path) (subject "") a)
9782 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9783 (setq address (match-string 1 path)
9784 subject (org-link-escape (match-string 2 path))))
9785 (while args
9786 (cond
9787 ((not (stringp (car args))) (push (pop args) args1))
9788 (t (setq a (pop args))
9789 (if (string-match "%a" a)
9790 (setq a (replace-match address t t a)))
9791 (if (string-match "%s" a)
9792 (setq a (replace-match subject t t a)))
9793 (push a args1))))
9794 (apply cmd (nreverse args1))))
9796 ((member type '("http" "https" "ftp" "news"))
9797 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9798 (org-link-escape
9799 path org-link-escape-chars-browser)
9800 path))))
9802 ((string= type "doi")
9803 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9804 (org-link-escape
9805 path org-link-escape-chars-browser)
9806 path))))
9808 ((member type '("message"))
9809 (browse-url (concat type ":" path)))
9811 ((string= type "tags")
9812 (org-tags-view arg path))
9814 ((string= type "tree-match")
9815 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9817 ((string= type "file")
9818 (if (string-match "::\\([0-9]+\\)\\'" path)
9819 (setq line (string-to-number (match-string 1 path))
9820 path (substring path 0 (match-beginning 0)))
9821 (if (string-match "::\\(.+\\)\\'" path)
9822 (setq search (match-string 1 path)
9823 path (substring path 0 (match-beginning 0)))))
9824 (if (string-match "[*?{]" (file-name-nondirectory path))
9825 (dired path)
9826 (org-open-file path arg line search)))
9828 ((string= type "shell")
9829 (let ((buf (generate-new-buffer "*Org Shell Output"))
9830 (cmd path))
9831 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9832 (string-match org-confirm-shell-link-not-regexp cmd))
9833 (not org-confirm-shell-link-function)
9834 (funcall org-confirm-shell-link-function
9835 (format "Execute \"%s\" in shell? "
9836 (org-add-props cmd nil
9837 'face 'org-warning))))
9838 (progn
9839 (message "Executing %s" cmd)
9840 (shell-command cmd buf)
9841 (if (featurep 'midnight)
9842 (setq clean-buffer-list-kill-buffer-names
9843 (cons buf clean-buffer-list-kill-buffer-names))))
9844 (error "Abort"))))
9846 ((string= type "elisp")
9847 (let ((cmd path))
9848 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9849 (string-match org-confirm-elisp-link-not-regexp cmd))
9850 (not org-confirm-elisp-link-function)
9851 (funcall org-confirm-elisp-link-function
9852 (format "Execute \"%s\" as elisp? "
9853 (org-add-props cmd nil
9854 'face 'org-warning))))
9855 (message "%s => %s" cmd
9856 (if (equal (string-to-char cmd) ?\()
9857 (eval (read cmd))
9858 (call-interactively (read cmd))))
9859 (error "Abort"))))
9861 ((and (string= type "thisfile")
9862 (run-hook-with-args-until-success
9863 'org-open-link-functions path)))
9865 ((string= type "thisfile")
9866 (if arg
9867 (switch-to-buffer-other-window
9868 (org-get-buffer-for-internal-link (current-buffer)))
9869 (org-mark-ring-push))
9870 (let ((cmd `(org-link-search
9871 ,path
9872 ,(cond ((equal arg '(4)) ''occur)
9873 ((equal arg '(16)) ''org-occur)
9874 (t nil))
9875 ,pos)))
9876 (condition-case nil (let ((org-link-search-inhibit-query t))
9877 (eval cmd))
9878 (error (progn (widen) (eval cmd))))))
9881 (browse-url-at-point)))))))
9882 (move-marker org-open-link-marker nil)
9883 (run-hook-with-args 'org-follow-link-hook)))
9885 (defun org-offer-links-in-entry (&optional nth zero)
9886 "Offer links in the current entry and follow the selected link.
9887 If there is only one link, follow it immediately as well.
9888 If NTH is an integer, immediately pick the NTH link found.
9889 If ZERO is a string, check also this string for a link, and if
9890 there is one, offer it as link number zero."
9891 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9892 "\\(" org-angle-link-re "\\)\\|"
9893 "\\(" org-plain-link-re "\\)"))
9894 (cnt ?0)
9895 (in-emacs (if (integerp nth) nil nth))
9896 have-zero end links link c)
9897 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9898 (push (match-string 0 zero) links)
9899 (setq cnt (1- cnt) have-zero t))
9900 (save-excursion
9901 (org-back-to-heading t)
9902 (setq end (save-excursion (outline-next-heading) (point)))
9903 (while (re-search-forward re end t)
9904 (push (match-string 0) links))
9905 (setq links (org-uniquify (reverse links))))
9907 (cond
9908 ((null links)
9909 (message "No links"))
9910 ((equal (length links) 1)
9911 (setq link (list (car links))))
9912 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9913 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9914 (t ; we have to select a link
9915 (save-excursion
9916 (save-window-excursion
9917 (delete-other-windows)
9918 (with-output-to-temp-buffer "*Select Link*"
9919 (mapc (lambda (l)
9920 (if (not (string-match org-bracket-link-regexp l))
9921 (princ (format "[%c] %s\n" (incf cnt)
9922 (org-remove-angle-brackets l)))
9923 (if (match-end 3)
9924 (princ (format "[%c] %s (%s)\n" (incf cnt)
9925 (match-string 3 l) (match-string 1 l)))
9926 (princ (format "[%c] %s\n" (incf cnt)
9927 (match-string 1 l))))))
9928 links))
9929 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9930 (message "Select link to open, RET to open all:")
9931 (setq c (read-char-exclusive))
9932 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9933 (when (equal c ?q) (error "Abort"))
9934 (if (equal c ?\C-m)
9935 (setq link links)
9936 (setq nth (- c ?0))
9937 (if have-zero (setq nth (1+ nth)))
9938 (unless (and (integerp nth) (>= (length links) nth))
9939 (error "Invalid link selection"))
9940 (setq link (list (nth (1- nth) links))))))
9941 (if link
9942 (let ((buf (current-buffer)))
9943 (dolist (l link)
9944 (org-open-link-from-string l in-emacs buf))
9946 nil)))
9948 ;; Add special file links that specify the way of opening
9950 (org-add-link-type "file+sys" 'org-open-file-with-system)
9951 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9952 (defun org-open-file-with-system (path)
9953 "Open file at PATH using the system way of opening it."
9954 (org-open-file path 'system))
9955 (defun org-open-file-with-emacs (path)
9956 "Open file at PATH in Emacs."
9957 (org-open-file path 'emacs))
9958 (defun org-remove-file-link-modifiers ()
9959 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9960 (goto-char (point-min))
9961 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9962 (org-if-unprotected
9963 (replace-match "file:" t t))))
9964 (eval-after-load "org-exp"
9965 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9966 'org-remove-file-link-modifiers))
9968 ;;;; Time estimates
9970 (defun org-get-effort (&optional pom)
9971 "Get the effort estimate for the current entry."
9972 (org-entry-get pom org-effort-property))
9974 ;;; File search
9976 (defvar org-create-file-search-functions nil
9977 "List of functions to construct the right search string for a file link.
9978 These functions are called in turn with point at the location to
9979 which the link should point.
9981 A function in the hook should first test if it would like to
9982 handle this file type, for example by checking the `major-mode'
9983 or the file extension. If it decides not to handle this file, it
9984 should just return nil to give other functions a chance. If it
9985 does handle the file, it must return the search string to be used
9986 when following the link. The search string will be part of the
9987 file link, given after a double colon, and `org-open-at-point'
9988 will automatically search for it. If special measures must be
9989 taken to make the search successful, another function should be
9990 added to the companion hook `org-execute-file-search-functions',
9991 which see.
9993 A function in this hook may also use `setq' to set the variable
9994 `description' to provide a suggestion for the descriptive text to
9995 be used for this link when it gets inserted into an Org-mode
9996 buffer with \\[org-insert-link].")
9998 (defvar org-execute-file-search-functions nil
9999 "List of functions to execute a file search triggered by a link.
10001 Functions added to this hook must accept a single argument, the
10002 search string that was part of the file link, the part after the
10003 double colon. The function must first check if it would like to
10004 handle this search, for example by checking the `major-mode' or
10005 the file extension. If it decides not to handle this search, it
10006 should just return nil to give other functions a chance. If it
10007 does handle the search, it must return a non-nil value to keep
10008 other functions from trying.
10010 Each function can access the current prefix argument through the
10011 variable `current-prefix-argument'. Note that a single prefix is
10012 used to force opening a link in Emacs, so it may be good to only
10013 use a numeric or double prefix to guide the search function.
10015 In case this is needed, a function in this hook can also restore
10016 the window configuration before `org-open-at-point' was called using:
10018 (set-window-configuration org-window-config-before-follow-link)")
10020 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10021 (defun org-link-search (s &optional type avoid-pos stealth)
10022 "Search for a link search option.
10023 If S is surrounded by forward slashes, it is interpreted as a
10024 regular expression. In org-mode files, this will create an `org-occur'
10025 sparse tree. In ordinary files, `occur' will be used to list matches.
10026 If the current buffer is in `dired-mode', grep will be used to search
10027 in all files. If AVOID-POS is given, ignore matches near that position.
10029 When optional argument STEALTH is non-nil, do not modify
10030 visibility around point, thus ignoring
10031 `org-show-hierarchy-above', `org-show-following-heading' and
10032 `org-show-siblings' variables."
10033 (let ((case-fold-search t)
10034 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10035 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10036 (append '(("") (" ") ("\t") ("\n"))
10037 org-emphasis-alist)
10038 "\\|") "\\)"))
10039 (pos (point))
10040 (pre nil) (post nil)
10041 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10042 (cond
10043 ;; First check if there are any special search functions
10044 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10045 ;; Now try the builtin stuff
10046 ((and (equal (string-to-char s0) ?#)
10047 (> (length s0) 1)
10048 (save-excursion
10049 (goto-char (point-min))
10050 (and
10051 (re-search-forward
10052 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10053 (setq type 'dedicated
10054 pos (match-beginning 0))))
10055 ;; There is an exact target for this
10056 (goto-char pos)
10057 (org-back-to-heading t)))
10058 ((save-excursion
10059 (goto-char (point-min))
10060 (and
10061 (re-search-forward
10062 (concat "<<" (regexp-quote s0) ">>") nil t)
10063 (setq type 'dedicated
10064 pos (match-beginning 0))))
10065 ;; There is an exact target for this
10066 (goto-char pos))
10067 ((save-excursion
10068 (goto-char (point-min))
10069 (and
10070 (re-search-forward
10071 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10072 (setq type 'dedicated pos (match-beginning 0))))
10073 ;; Found an invisible target.
10074 (goto-char pos))
10075 ((save-excursion
10076 (goto-char (point-min))
10077 (and
10078 (re-search-forward
10079 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10080 (setq type 'dedicated pos (match-beginning 0))))
10081 ;; Found an element with a matching #+name affiliated keyword.
10082 (goto-char pos))
10083 ((and (string-match "^(\\(.*\\))$" s0)
10084 (save-excursion
10085 (goto-char (point-min))
10086 (and
10087 (re-search-forward
10088 (concat "[^[]" (regexp-quote
10089 (format org-coderef-label-format
10090 (match-string 1 s0))))
10091 nil t)
10092 (setq type 'dedicated
10093 pos (1+ (match-beginning 0))))))
10094 ;; There is a coderef target for this
10095 (goto-char pos))
10096 ((string-match "^/\\(.*\\)/$" s)
10097 ;; A regular expression
10098 (cond
10099 ((derived-mode-p 'org-mode)
10100 (org-occur (match-string 1 s)))
10101 ;;((eq major-mode 'dired-mode)
10102 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10103 (t (org-do-occur (match-string 1 s)))))
10104 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10105 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10106 (goto-char (point-min))
10107 (cond
10108 ((let (case-fold-search)
10109 (re-search-forward (format org-complex-heading-regexp-format
10110 (regexp-quote s))
10111 nil t))
10112 ;; OK, found a match
10113 (setq type 'dedicated)
10114 (goto-char (match-beginning 0)))
10115 ((and (not org-link-search-inhibit-query)
10116 (eq org-link-search-must-match-exact-headline 'query-to-create)
10117 (y-or-n-p "No match - create this as a new heading? "))
10118 (goto-char (point-max))
10119 (or (bolp) (newline))
10120 (insert "* " s "\n")
10121 (beginning-of-line 0))
10123 (goto-char pos)
10124 (error "No match"))))
10126 ;; A normal search string
10127 (when (equal (string-to-char s) ?*)
10128 ;; Anchor on headlines, post may include tags.
10129 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10130 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10131 s (substring s 1)))
10132 (remove-text-properties
10133 0 (length s)
10134 '(face nil mouse-face nil keymap nil fontified nil) s)
10135 ;; Make a series of regular expressions to find a match
10136 (setq words (org-split-string s "[ \n\r\t]+")
10138 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10139 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10140 "\\)" markers)
10141 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10142 re2a (concat "[ \t\r\n]" re2a_)
10143 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10144 re4 (concat "[^a-zA-Z_]" re4_)
10146 re1 (concat pre re2 post)
10147 re3 (concat pre (if pre re4_ re4) post)
10148 re5 (concat pre ".*" re4)
10149 re2 (concat pre re2)
10150 re2a (concat pre (if pre re2a_ re2a))
10151 re4 (concat pre (if pre re4_ re4))
10152 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10153 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10154 re5 "\\)"
10156 (cond
10157 ((eq type 'org-occur) (org-occur reall))
10158 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10159 (t (goto-char (point-min))
10160 (setq type 'fuzzy)
10161 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10162 (org-search-not-self 1 re1 nil t)
10163 (org-search-not-self 1 re2 nil t)
10164 (org-search-not-self 1 re2a nil t)
10165 (org-search-not-self 1 re3 nil t)
10166 (org-search-not-self 1 re4 nil t)
10167 (org-search-not-self 1 re5 nil t)
10169 (goto-char (match-beginning 1))
10170 (goto-char pos)
10171 (error "No match"))))))
10172 (and (derived-mode-p 'org-mode)
10173 (not stealth)
10174 (org-show-context 'link-search))
10175 type))
10177 (defun org-search-not-self (group &rest args)
10178 "Execute `re-search-forward', but only accept matches that do not
10179 enclose the position of `org-open-link-marker'."
10180 (let ((m org-open-link-marker))
10181 (catch 'exit
10182 (while (apply 're-search-forward args)
10183 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10184 (goto-char (match-end group))
10185 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10186 (> (match-beginning 0) (marker-position m))
10187 (< (match-end 0) (marker-position m)))
10188 (save-match-data
10189 (or (not (org-in-regexp
10190 org-bracket-link-analytic-regexp 1))
10191 (not (match-end 4)) ; no description
10192 (and (<= (match-beginning 4) (point))
10193 (>= (match-end 4) (point))))))
10194 (throw 'exit (point))))))))
10196 (defun org-get-buffer-for-internal-link (buffer)
10197 "Return a buffer to be used for displaying the link target of internal links."
10198 (cond
10199 ((not org-display-internal-link-with-indirect-buffer)
10200 buffer)
10201 ((string-match "(Clone)$" (buffer-name buffer))
10202 (message "Buffer is already a clone, not making another one")
10203 ;; we also do not modify visibility in this case
10204 buffer)
10205 (t ; make a new indirect buffer for displaying the link
10206 (let* ((bn (buffer-name buffer))
10207 (ibn (concat bn "(Clone)"))
10208 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10209 (with-current-buffer ib (org-overview))
10210 ib))))
10212 (defun org-do-occur (regexp &optional cleanup)
10213 "Call the Emacs command `occur'.
10214 If CLEANUP is non-nil, remove the printout of the regular expression
10215 in the *Occur* buffer. This is useful if the regex is long and not useful
10216 to read."
10217 (occur regexp)
10218 (when cleanup
10219 (let ((cwin (selected-window)) win beg end)
10220 (when (setq win (get-buffer-window "*Occur*"))
10221 (select-window win))
10222 (goto-char (point-min))
10223 (when (re-search-forward "match[a-z]+" nil t)
10224 (setq beg (match-end 0))
10225 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10226 (setq end (1- (match-beginning 0)))))
10227 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10228 (goto-char (point-min))
10229 (select-window cwin))))
10231 ;;; The mark ring for links jumps
10233 (defvar org-mark-ring nil
10234 "Mark ring for positions before jumps in Org-mode.")
10235 (defvar org-mark-ring-last-goto nil
10236 "Last position in the mark ring used to go back.")
10237 ;; Fill and close the ring
10238 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10239 (loop for i from 1 to org-mark-ring-length do
10240 (push (make-marker) org-mark-ring))
10241 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10242 org-mark-ring)
10244 (defun org-mark-ring-push (&optional pos buffer)
10245 "Put the current position or POS into the mark ring and rotate it."
10246 (interactive)
10247 (setq pos (or pos (point)))
10248 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10249 (move-marker (car org-mark-ring)
10250 (or pos (point))
10251 (or buffer (current-buffer)))
10252 (message "%s"
10253 (substitute-command-keys
10254 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10256 (defun org-mark-ring-goto (&optional n)
10257 "Jump to the previous position in the mark ring.
10258 With prefix arg N, jump back that many stored positions. When
10259 called several times in succession, walk through the entire ring.
10260 Org-mode commands jumping to a different position in the current file,
10261 or to another Org-mode file, automatically push the old position
10262 onto the ring."
10263 (interactive "p")
10264 (let (p m)
10265 (if (eq last-command this-command)
10266 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10267 (setq p org-mark-ring))
10268 (setq org-mark-ring-last-goto p)
10269 (setq m (car p))
10270 (org-pop-to-buffer-same-window (marker-buffer m))
10271 (goto-char m)
10272 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10274 (defun org-remove-angle-brackets (s)
10275 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10276 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10278 (defun org-add-angle-brackets (s)
10279 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10280 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10282 (defun org-remove-double-quotes (s)
10283 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10284 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10287 ;;; Following specific links
10289 (defun org-follow-timestamp-link ()
10290 (cond
10291 ((org-at-date-range-p t)
10292 (let ((org-agenda-start-on-weekday)
10293 (t1 (match-string 1))
10294 (t2 (match-string 2)))
10295 (setq t1 (time-to-days (org-time-string-to-time t1))
10296 t2 (time-to-days (org-time-string-to-time t2)))
10297 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10298 ((org-at-timestamp-p t)
10299 (org-agenda-list nil (time-to-days (org-time-string-to-time
10300 (substring (match-string 1) 0 10)))
10302 (t (error "This should not happen"))))
10305 ;;; Following file links
10306 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10307 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10308 (declare-function mailcap-mime-info
10309 "mailcap" (string &optional request no-decode))
10310 (defvar org-wait nil)
10311 (defun org-open-file (path &optional in-emacs line search)
10312 "Open the file at PATH.
10313 First, this expands any special file name abbreviations. Then the
10314 configuration variable `org-file-apps' is checked if it contains an
10315 entry for this file type, and if yes, the corresponding command is launched.
10317 If no application is found, Emacs simply visits the file.
10319 With optional prefix argument IN-EMACS, Emacs will visit the file.
10320 With a double \\[universal-argument] \\[universal-argument] \
10321 prefix arg, Org tries to avoid opening in Emacs
10322 and to use an external application to visit the file.
10324 Optional LINE specifies a line to go to, optional SEARCH a string
10325 to search for. If LINE or SEARCH is given, the file will be
10326 opened in Emacs, unless an entry from org-file-apps that makes
10327 use of groups in a regexp matches.
10329 If you want to change the way frames are used when following a
10330 link, please customize `org-link-frame-setup'.
10332 If the file does not exist, an error is thrown."
10333 (let* ((file (if (equal path "")
10334 buffer-file-name
10335 (substitute-in-file-name (expand-file-name path))))
10336 (file-apps (append org-file-apps (org-default-apps)))
10337 (apps (org-remove-if
10338 'org-file-apps-entry-match-against-dlink-p file-apps))
10339 (apps-dlink (org-remove-if-not
10340 'org-file-apps-entry-match-against-dlink-p file-apps))
10341 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10342 (dirp (if remp nil (file-directory-p file)))
10343 (file (if (and dirp org-open-directory-means-index-dot-org)
10344 (concat (file-name-as-directory file) "index.org")
10345 file))
10346 (a-m-a-p (assq 'auto-mode apps))
10347 (dfile (downcase file))
10348 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10349 (link (cond ((and (eq line nil)
10350 (eq search nil))
10351 file)
10352 (line
10353 (concat file "::" (number-to-string line)))
10354 (search
10355 (concat file "::" search))))
10356 (dlink (downcase link))
10357 (old-buffer (current-buffer))
10358 (old-pos (point))
10359 (old-mode major-mode)
10360 ext cmd link-match-data)
10361 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10362 (setq ext (match-string 1 dfile))
10363 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10364 (setq ext (match-string 1 dfile))))
10365 (cond
10366 ((member in-emacs '((16) system))
10367 (setq cmd (cdr (assoc 'system apps))))
10368 (in-emacs (setq cmd 'emacs))
10370 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10371 (and dirp (cdr (assoc 'directory apps)))
10372 ; first, try matching against apps-dlink
10373 ; if we get a match here, store the match data for later
10374 (let ((match (assoc-default dlink apps-dlink
10375 'string-match)))
10376 (if match
10377 (progn (setq link-match-data (match-data))
10378 match)
10379 (progn (setq in-emacs (or in-emacs line search))
10380 nil))) ; if we have no match in apps-dlink,
10381 ; always open the file in emacs if line or search
10382 ; is given (for backwards compatibility)
10383 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10384 'string-match)
10385 (cdr (assoc ext apps))
10386 (cdr (assoc t apps))))))
10387 (when (eq cmd 'system)
10388 (setq cmd (cdr (assoc 'system apps))))
10389 (when (eq cmd 'default)
10390 (setq cmd (cdr (assoc t apps))))
10391 (when (eq cmd 'mailcap)
10392 (require 'mailcap)
10393 (mailcap-parse-mailcaps)
10394 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10395 (command (mailcap-mime-info mime-type)))
10396 (if (stringp command)
10397 (setq cmd command)
10398 (setq cmd 'emacs))))
10399 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10400 (not (file-exists-p file))
10401 (not org-open-non-existing-files))
10402 (error "No such file: %s" file))
10403 (cond
10404 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10405 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10406 (while (string-match "['\"]%s['\"]" cmd)
10407 (setq cmd (replace-match "%s" t t cmd)))
10408 (while (string-match "%s" cmd)
10409 (setq cmd (replace-match
10410 (save-match-data
10411 (shell-quote-argument
10412 (convert-standard-filename file)))
10413 t t cmd)))
10415 ;; Replace "%1", "%2" etc. in command with group matches from regex
10416 (save-match-data
10417 (let ((match-index 1)
10418 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10419 (set-match-data link-match-data)
10420 (while (<= match-index number-of-groups)
10421 (let ((regex (concat "%" (number-to-string match-index)))
10422 (replace-with (match-string match-index dlink)))
10423 (while (string-match regex cmd)
10424 (setq cmd (replace-match replace-with t t cmd))))
10425 (setq match-index (+ match-index 1)))))
10427 (save-window-excursion
10428 (start-process-shell-command cmd nil cmd)
10429 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10431 ((or (stringp cmd)
10432 (eq cmd 'emacs))
10433 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10434 (widen)
10435 (if line (org-goto-line line)
10436 (if search (org-link-search search))))
10437 ((consp cmd)
10438 (let ((file (convert-standard-filename file)))
10439 (save-match-data
10440 (set-match-data link-match-data)
10441 (eval cmd))))
10442 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10443 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10444 (or (not (equal old-buffer (current-buffer)))
10445 (not (equal old-pos (point))))
10446 (org-mark-ring-push old-pos old-buffer))))
10448 (defun org-file-apps-entry-match-against-dlink-p (entry)
10449 "This function returns non-nil if `entry' uses a regular
10450 expression which should be matched against the whole link by
10451 org-open-file.
10453 It assumes that is the case when the entry uses a regular
10454 expression which has at least one grouping construct and the
10455 action is either a lisp form or a command string containing
10456 '%1', i.e. using at least one subexpression match as a
10457 parameter."
10458 (let ((selector (car entry))
10459 (action (cdr entry)))
10460 (if (stringp selector)
10461 (and (> (regexp-opt-depth selector) 0)
10462 (or (and (stringp action)
10463 (string-match "%[0-9]" action))
10464 (consp action)))
10465 nil)))
10467 (defun org-default-apps ()
10468 "Return the default applications for this operating system."
10469 (cond
10470 ((eq system-type 'darwin)
10471 org-file-apps-defaults-macosx)
10472 ((eq system-type 'windows-nt)
10473 org-file-apps-defaults-windowsnt)
10474 (t org-file-apps-defaults-gnu)))
10476 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10477 "Convert extensions to regular expressions in the cars of LIST.
10478 Also, weed out any non-string entries, because the return value is used
10479 only for regexp matching.
10480 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10481 point to the symbol `emacs', indicating that the file should
10482 be opened in Emacs."
10483 (append
10484 (delq nil
10485 (mapcar (lambda (x)
10486 (if (not (stringp (car x)))
10488 (if (string-match "\\W" (car x))
10490 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10491 list))
10492 (if add-auto-mode
10493 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10495 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10496 (defun org-file-remote-p (file)
10497 "Test whether FILE specifies a location on a remote system.
10498 Return non-nil if the location is indeed remote.
10500 For example, the filename \"/user@host:/foo\" specifies a location
10501 on the system \"/user@host:\"."
10502 (cond ((fboundp 'file-remote-p)
10503 (file-remote-p file))
10504 ((fboundp 'tramp-handle-file-remote-p)
10505 (tramp-handle-file-remote-p file))
10506 ((and (boundp 'ange-ftp-name-format)
10507 (string-match (car ange-ftp-name-format) file))
10509 (t nil)))
10512 ;;;; Refiling
10514 (defun org-get-org-file ()
10515 "Read a filename, with default directory `org-directory'."
10516 (let ((default (or org-default-notes-file remember-data-file)))
10517 (read-file-name (format "File name [%s]: " default)
10518 (file-name-as-directory org-directory)
10519 default)))
10521 (defun org-notes-order-reversed-p ()
10522 "Check if the current file should receive notes in reversed order."
10523 (cond
10524 ((not org-reverse-note-order) nil)
10525 ((eq t org-reverse-note-order) t)
10526 ((not (listp org-reverse-note-order)) nil)
10527 (t (catch 'exit
10528 (let ((all org-reverse-note-order)
10529 entry)
10530 (while (setq entry (pop all))
10531 (if (string-match (car entry) buffer-file-name)
10532 (throw 'exit (cdr entry))))
10533 nil)))))
10535 (defvar org-refile-target-table nil
10536 "The list of refile targets, created by `org-refile'.")
10538 (defvar org-agenda-new-buffers nil
10539 "Buffers created to visit agenda files.")
10541 (defvar org-refile-cache nil
10542 "Cache for refile targets.")
10544 (defvar org-refile-markers nil
10545 "All the markers used for caching refile locations.")
10547 (defun org-refile-marker (pos)
10548 "Get a new refile marker, but only if caching is in use."
10549 (if (not org-refile-use-cache)
10551 (let ((m (make-marker)))
10552 (move-marker m pos)
10553 (push m org-refile-markers)
10554 m)))
10556 (defun org-refile-cache-clear ()
10557 "Clear the refile cache and disable all the markers."
10558 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10559 (setq org-refile-markers nil)
10560 (setq org-refile-cache nil)
10561 (message "Refile cache has been cleared"))
10563 (defun org-refile-cache-check-set (set)
10564 "Check if all the markers in the cache still have live buffers."
10565 (let (marker)
10566 (catch 'exit
10567 (while (and set (setq marker (nth 3 (pop set))))
10568 ;; if org-refile-use-outline-path is 'file, marker may be nil
10569 (when (and marker (null (marker-buffer marker)))
10570 (message "not found") (sit-for 3)
10571 (throw 'exit nil)))
10572 t)))
10574 (defun org-refile-cache-put (set &rest identifiers)
10575 "Push the refile targets SET into the cache, under IDENTIFIERS."
10576 (let* ((key (sha1 (prin1-to-string identifiers)))
10577 (entry (assoc key org-refile-cache)))
10578 (if entry
10579 (setcdr entry set)
10580 (push (cons key set) org-refile-cache))))
10582 (defun org-refile-cache-get (&rest identifiers)
10583 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10584 (cond
10585 ((not org-refile-cache) nil)
10586 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10588 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10589 org-refile-cache))))
10590 (and set (org-refile-cache-check-set set) set)))))
10592 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10593 "Produce a table with refile targets."
10594 (let ((case-fold-search nil)
10595 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10596 (entries (or org-refile-targets '((nil . (:level . 1)))))
10597 targets tgs txt re files f desc descre fast-path-p level pos0)
10598 (message "Getting targets...")
10599 (with-current-buffer (or default-buffer (current-buffer))
10600 (while (setq entry (pop entries))
10601 (setq files (car entry) desc (cdr entry))
10602 (setq fast-path-p nil)
10603 (cond
10604 ((null files) (setq files (list (current-buffer))))
10605 ((eq files 'org-agenda-files)
10606 (setq files (org-agenda-files 'unrestricted)))
10607 ((and (symbolp files) (fboundp files))
10608 (setq files (funcall files)))
10609 ((and (symbolp files) (boundp files))
10610 (setq files (symbol-value files))))
10611 (if (stringp files) (setq files (list files)))
10612 (cond
10613 ((eq (car desc) :tag)
10614 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10615 ((eq (car desc) :todo)
10616 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10617 ((eq (car desc) :regexp)
10618 (setq descre (cdr desc)))
10619 ((eq (car desc) :level)
10620 (setq descre (concat "^\\*\\{" (number-to-string
10621 (if org-odd-levels-only
10622 (1- (* 2 (cdr desc)))
10623 (cdr desc)))
10624 "\\}[ \t]")))
10625 ((eq (car desc) :maxlevel)
10626 (setq fast-path-p t)
10627 (setq descre (concat "^\\*\\{1," (number-to-string
10628 (if org-odd-levels-only
10629 (1- (* 2 (cdr desc)))
10630 (cdr desc)))
10631 "\\}[ \t]")))
10632 (t (error "Bad refiling target description %s" desc)))
10633 (while (setq f (pop files))
10634 (with-current-buffer
10635 (if (bufferp f) f (org-get-agenda-file-buffer f))
10637 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10638 (progn
10639 (if (bufferp f) (setq f (buffer-file-name
10640 (buffer-base-buffer f))))
10641 (setq f (and f (expand-file-name f)))
10642 (if (eq org-refile-use-outline-path 'file)
10643 (push (list (file-name-nondirectory f) f nil nil) tgs))
10644 (save-excursion
10645 (save-restriction
10646 (widen)
10647 (goto-char (point-min))
10648 (while (re-search-forward descre nil t)
10649 (goto-char (setq pos0 (point-at-bol)))
10650 (catch 'next
10651 (when org-refile-target-verify-function
10652 (save-match-data
10653 (or (funcall org-refile-target-verify-function)
10654 (throw 'next t))))
10655 (when (and (looking-at org-complex-heading-regexp)
10656 (not (member (match-string 4) excluded-entries))
10657 (match-string 4))
10658 (setq level (org-reduced-level
10659 (- (match-end 1) (match-beginning 1)))
10660 txt (org-link-display-format (match-string 4))
10661 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10662 re (format org-complex-heading-regexp-format
10663 (regexp-quote (match-string 4))))
10664 (when org-refile-use-outline-path
10665 (setq txt (mapconcat
10666 'org-protect-slash
10667 (append
10668 (if (eq org-refile-use-outline-path
10669 'file)
10670 (list (file-name-nondirectory
10671 (buffer-file-name
10672 (buffer-base-buffer))))
10673 (if (eq org-refile-use-outline-path
10674 'full-file-path)
10675 (list (buffer-file-name
10676 (buffer-base-buffer)))))
10677 (org-get-outline-path fast-path-p
10678 level txt)
10679 (list txt))
10680 "/")))
10681 (push (list txt f re (org-refile-marker (point)))
10682 tgs)))
10683 (when (= (point) pos0)
10684 ;; verification function has not moved point
10685 (goto-char (point-at-eol))))))))
10686 (when org-refile-use-cache
10687 (org-refile-cache-put tgs (buffer-file-name) descre))
10688 (setq targets (append tgs targets))
10689 ))))
10690 (message "Getting targets...done")
10691 (nreverse targets)))
10693 (defun org-protect-slash (s)
10694 (while (string-match "/" s)
10695 (setq s (replace-match "\\" t t s)))
10698 (defvar org-olpa (make-vector 20 nil))
10700 (defun org-get-outline-path (&optional fastp level heading)
10701 "Return the outline path to the current entry, as a list.
10703 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10704 routine which makes outline path derivations for an entire file,
10705 avoiding backtracing. Refile target collection makes use of that."
10706 (if fastp
10707 (progn
10708 (if (> level 19)
10709 (error "Outline path failure, more than 19 levels"))
10710 (loop for i from level upto 19 do
10711 (aset org-olpa i nil))
10712 (prog1
10713 (delq nil (append org-olpa nil))
10714 (aset org-olpa level heading)))
10715 (let (rtn case-fold-search)
10716 (save-excursion
10717 (save-restriction
10718 (widen)
10719 (while (org-up-heading-safe)
10720 (when (looking-at org-complex-heading-regexp)
10721 (push (org-match-string-no-properties 4) rtn)))
10722 rtn)))))
10724 (defun org-format-outline-path (path &optional width prefix)
10725 "Format the outline path PATH for display.
10726 Width is the maximum number of characters that is available.
10727 Prefix is a prefix to be included in the returned string,
10728 such as the file name."
10729 (setq width (or width 79))
10730 (if prefix (setq width (- width (length prefix))))
10731 (if (not path)
10732 (or prefix "")
10733 (let* ((nsteps (length path))
10734 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10735 (maxwidth (if (<= total-width width)
10736 10000 ;; everything fits
10737 ;; we need to shorten the level headings
10738 (/ (- width nsteps) nsteps)))
10739 (org-odd-levels-only nil)
10740 (n 0)
10741 (total (1+ (length prefix))))
10742 (setq maxwidth (max maxwidth 10))
10743 (concat prefix
10744 (mapconcat
10745 (lambda (h)
10746 (setq n (1+ n))
10747 (if (and (= n nsteps) (< maxwidth 10000))
10748 (setq maxwidth (- total-width total)))
10749 (if (< (length h) maxwidth)
10750 (progn (setq total (+ total (length h) 1)) h)
10751 (setq h (substring h 0 (- maxwidth 2))
10752 total (+ total maxwidth 1))
10753 (if (string-match "[ \t]+\\'" h)
10754 (setq h (substring h 0 (match-beginning 0))))
10755 (setq h (concat h "..")))
10756 (org-add-props h nil 'face
10757 (nth (% (1- n) org-n-level-faces)
10758 org-level-faces))
10760 path "/")))))
10762 (defun org-display-outline-path (&optional file current)
10763 "Display the current outline path in the echo area."
10764 (interactive "P")
10765 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10766 (case-fold-search nil)
10767 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10768 (if current (setq path (append path
10769 (save-excursion
10770 (org-back-to-heading t)
10771 (if (looking-at org-complex-heading-regexp)
10772 (list (match-string 4)))))))
10773 (message "%s"
10774 (org-format-outline-path
10775 path
10776 (1- (frame-width))
10777 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10779 (defvar org-refile-history nil
10780 "History for refiling operations.")
10782 (defvar org-after-refile-insert-hook nil
10783 "Hook run after `org-refile' has inserted its stuff at the new location.
10784 Note that this is still *before* the stuff will be removed from
10785 the *old* location.")
10787 (defvar org-capture-last-stored-marker)
10788 (defun org-refile (&optional goto default-buffer rfloc)
10789 "Move the entry or entries at point to another heading.
10790 The list of target headings is compiled using the information in
10791 `org-refile-targets', which see.
10793 At the target location, the entry is filed as a subitem of the target
10794 heading. Depending on `org-reverse-note-order', the new subitem will
10795 either be the first or the last subitem.
10797 If there is an active region, all entries in that region will be moved.
10798 However, the region must fulfill the requirement that the first heading
10799 is the first one sets the top-level of the moved text - at most siblings
10800 below it are allowed.
10802 With prefix arg GOTO, the command will only visit the target location
10803 and not actually move anything.
10805 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10806 go to the location where the last refiling operation has put the subtree.
10807 With a prefix argument of `2', refile to the running clock.
10809 RFLOC can be a refile location obtained in a different way.
10811 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10813 If you are using target caching (see `org-refile-use-cache'),
10814 you have to clear the target cache in order to find new targets.
10815 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10816 prefix argument (`C-u C-u C-u C-c C-w')."
10818 (interactive "P")
10819 (if (member goto '(0 (64)))
10820 (org-refile-cache-clear)
10821 (let* ((cbuf (current-buffer))
10822 (regionp (org-region-active-p))
10823 (region-start (and regionp (region-beginning)))
10824 (region-end (and regionp (region-end)))
10825 (region-length (and regionp (- region-end region-start)))
10826 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10827 pos it nbuf file re level reversed)
10828 (setq last-command nil)
10829 (when regionp
10830 (goto-char region-start)
10831 (or (bolp) (goto-char (point-at-bol)))
10832 (setq region-start (point))
10833 (unless (or (org-kill-is-subtree-p
10834 (buffer-substring region-start region-end))
10835 (prog1 org-refile-active-region-within-subtree
10836 (org-toggle-heading)))
10837 (error "The region is not a (sequence of) subtree(s)")))
10838 (if (equal goto '(16))
10839 (org-refile-goto-last-stored)
10840 (when (or
10841 (and (equal goto 2)
10842 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10843 (prog1
10844 (setq it (list (or org-clock-heading "running clock")
10845 (buffer-file-name
10846 (marker-buffer org-clock-hd-marker))
10848 (marker-position org-clock-hd-marker)))
10849 (setq goto nil)))
10850 (setq it (or rfloc
10851 (let (heading-text)
10852 (save-excursion
10853 (unless goto
10854 (org-back-to-heading t)
10855 (setq heading-text
10856 (nth 4 (org-heading-components))))
10857 (org-refile-get-location
10858 (cond (goto "Goto")
10859 (regionp "Refile region to")
10860 (t (concat "Refile subtree \""
10861 heading-text "\" to")))
10862 default-buffer
10863 (and (not (equal '(4) goto))
10864 org-refile-allow-creating-parent-nodes)
10865 goto))))))
10866 (setq file (nth 1 it)
10867 re (nth 2 it)
10868 pos (nth 3 it))
10869 (if (and (not goto)
10871 (equal (buffer-file-name) file)
10872 (if regionp
10873 (and (>= pos region-start)
10874 (<= pos region-end))
10875 (and (>= pos (point))
10876 (< pos (save-excursion
10877 (org-end-of-subtree t t))))))
10878 (error "Cannot refile to position inside the tree or region"))
10880 (setq nbuf (or (find-buffer-visiting file)
10881 (find-file-noselect file)))
10882 (if goto
10883 (progn
10884 (org-pop-to-buffer-same-window nbuf)
10885 (goto-char pos)
10886 (org-show-context 'org-goto))
10887 (if regionp
10888 (progn
10889 (org-kill-new (buffer-substring region-start region-end))
10890 (org-save-markers-in-region region-start region-end))
10891 (org-copy-subtree 1 nil t))
10892 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10893 (find-file-noselect file)))
10894 (setq reversed (org-notes-order-reversed-p))
10895 (save-excursion
10896 (save-restriction
10897 (widen)
10898 (if pos
10899 (progn
10900 (goto-char pos)
10901 (looking-at org-outline-regexp)
10902 (setq level (org-get-valid-level (funcall outline-level) 1))
10903 (goto-char
10904 (if reversed
10905 (or (outline-next-heading) (point-max))
10906 (or (save-excursion (org-get-next-sibling))
10907 (org-end-of-subtree t t)
10908 (point-max)))))
10909 (setq level 1)
10910 (if (not reversed)
10911 (goto-char (point-max))
10912 (goto-char (point-min))
10913 (or (outline-next-heading) (goto-char (point-max)))))
10914 (if (not (bolp)) (newline))
10915 (org-paste-subtree level)
10916 (when org-log-refile
10917 (org-add-log-setup 'refile nil nil 'findpos
10918 org-log-refile)
10919 (unless (eq org-log-refile 'note)
10920 (save-excursion (org-add-log-note))))
10921 (and org-auto-align-tags
10922 (let ((org-loop-over-headlines-in-active-region nil))
10923 (org-set-tags nil t)))
10924 (bookmark-set "org-refile-last-stored")
10925 ;; If we are refiling for capture, make sure that the
10926 ;; last-capture pointers point here
10927 (when (org-bound-and-true-p org-refile-for-capture)
10928 (bookmark-set "org-capture-last-stored-marker")
10929 (move-marker org-capture-last-stored-marker (point)))
10930 (if (fboundp 'deactivate-mark) (deactivate-mark))
10931 (run-hooks 'org-after-refile-insert-hook))))
10932 (if regionp
10933 (delete-region (point) (+ (point) region-length))
10934 (org-cut-subtree))
10935 (when (featurep 'org-inlinetask)
10936 (org-inlinetask-remove-END-maybe))
10937 (setq org-markers-to-move nil)
10938 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10940 (defun org-refile-goto-last-stored ()
10941 "Go to the location where the last refile was stored."
10942 (interactive)
10943 (bookmark-jump "org-refile-last-stored")
10944 (message "This is the location of the last refile"))
10946 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10947 no-exclude)
10948 "Prompt the user for a refile location, using PROMPT.
10949 PROMPT should not be suffixed with a colon and a space, because
10950 this function appends the default value from
10951 `org-refile-history' automatically, if that is not empty.
10952 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10953 this is used for the GOTO interface."
10954 (let ((org-refile-targets org-refile-targets)
10955 (org-refile-use-outline-path org-refile-use-outline-path)
10956 excluded-entries)
10957 (when (and (derived-mode-p 'org-mode)
10958 (not org-refile-use-cache)
10959 (not no-exclude))
10960 (org-map-tree
10961 (lambda()
10962 (setq excluded-entries
10963 (append excluded-entries (list (org-get-heading t t)))))))
10964 (setq org-refile-target-table
10965 (org-refile-get-targets default-buffer excluded-entries)))
10966 (unless org-refile-target-table
10967 (error "No refile targets"))
10968 (let* ((prompt (concat prompt
10969 (and (car org-refile-history)
10970 (concat " (default " (car org-refile-history) ")"))
10971 ": "))
10972 (cbuf (current-buffer))
10973 (partial-completion-mode nil)
10974 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10975 (cfunc (if (and org-refile-use-outline-path
10976 org-outline-path-complete-in-steps)
10977 'org-olpath-completing-read
10978 'org-icompleting-read))
10979 (extra (if org-refile-use-outline-path "/" ""))
10980 (filename (and cfn (expand-file-name cfn)))
10981 (tbl (mapcar
10982 (lambda (x)
10983 (if (and (not (member org-refile-use-outline-path
10984 '(file full-file-path)))
10985 (not (equal filename (nth 1 x))))
10986 (cons (concat (car x) extra " ("
10987 (file-name-nondirectory (nth 1 x)) ")")
10988 (cdr x))
10989 (cons (concat (car x) extra) (cdr x))))
10990 org-refile-target-table))
10991 (completion-ignore-case t)
10992 pa answ parent-target child parent old-hist)
10993 (setq old-hist org-refile-history)
10994 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10995 nil 'org-refile-history (car org-refile-history)))
10996 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10997 (org-refile-check-position pa)
10998 (if pa
10999 (progn
11000 (when (or (not org-refile-history)
11001 (not (eq old-hist org-refile-history))
11002 (not (equal (car pa) (car org-refile-history))))
11003 (setq org-refile-history
11004 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11005 org-refile-history
11006 (cdr org-refile-history))))
11007 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11008 (pop org-refile-history)))
11010 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11011 (progn
11012 (setq parent (match-string 1 answ)
11013 child (match-string 2 answ))
11014 (setq parent-target (or (assoc parent tbl)
11015 (assoc (concat parent "/") tbl)))
11016 (when (and parent-target
11017 (or (eq new-nodes t)
11018 (and (eq new-nodes 'confirm)
11019 (y-or-n-p (format "Create new node \"%s\"? "
11020 child)))))
11021 (org-refile-new-child parent-target child)))
11022 (error "Invalid target location")))))
11024 (declare-function org-string-nw-p "org-macs.el" (s))
11025 (defun org-refile-check-position (refile-pointer)
11026 "Check if the refile pointer matches the readline to which it points."
11027 (let* ((file (nth 1 refile-pointer))
11028 (re (nth 2 refile-pointer))
11029 (pos (nth 3 refile-pointer))
11030 buffer)
11031 (when (org-string-nw-p re)
11032 (setq buffer (if (markerp pos)
11033 (marker-buffer pos)
11034 (or (find-buffer-visiting file)
11035 (find-file-noselect file))))
11036 (with-current-buffer buffer
11037 (save-excursion
11038 (save-restriction
11039 (widen)
11040 (goto-char pos)
11041 (beginning-of-line 1)
11042 (unless (org-looking-at-p re)
11043 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11045 (defun org-refile-new-child (parent-target child)
11046 "Use refile target PARENT-TARGET to add new CHILD below it."
11047 (unless parent-target
11048 (error "Cannot find parent for new node"))
11049 (let ((file (nth 1 parent-target))
11050 (pos (nth 3 parent-target))
11051 level)
11052 (with-current-buffer (or (find-buffer-visiting file)
11053 (find-file-noselect file))
11054 (save-excursion
11055 (save-restriction
11056 (widen)
11057 (if pos
11058 (goto-char pos)
11059 (goto-char (point-max))
11060 (if (not (bolp)) (newline)))
11061 (when (looking-at org-outline-regexp)
11062 (setq level (funcall outline-level))
11063 (org-end-of-subtree t t))
11064 (org-back-over-empty-lines)
11065 (insert "\n" (make-string
11066 (if pos (org-get-valid-level level 1) 1) ?*)
11067 " " child "\n")
11068 (beginning-of-line 0)
11069 (list (concat (car parent-target) "/" child) file "" (point)))))))
11071 (defun org-olpath-completing-read (prompt collection &rest args)
11072 "Read an outline path like a file name."
11073 (let ((thetable collection)
11074 (org-completion-use-ido nil) ; does not work with ido.
11075 (org-completion-use-iswitchb nil)) ; or iswitchb
11076 (apply
11077 'org-icompleting-read prompt
11078 (lambda (string predicate &optional flag)
11079 (let (rtn r f (l (length string)))
11080 (cond
11081 ((eq flag nil)
11082 ;; try completion
11083 (try-completion string thetable))
11084 ((eq flag t)
11085 ;; all-completions
11086 (setq rtn (all-completions string thetable predicate))
11087 (mapcar
11088 (lambda (x)
11089 (setq r (substring x l))
11090 (if (string-match " ([^)]*)$" x)
11091 (setq f (match-string 0 x))
11092 (setq f ""))
11093 (if (string-match "/" r)
11094 (concat string (substring r 0 (match-end 0)) f)
11096 rtn))
11097 ((eq flag 'lambda)
11098 ;; exact match?
11099 (assoc string thetable)))))
11100 args)))
11102 ;;;; Dynamic blocks
11104 (defun org-find-dblock (name)
11105 "Find the first dynamic block with name NAME in the buffer.
11106 If not found, stay at current position and return nil."
11107 (let (pos)
11108 (save-excursion
11109 (goto-char (point-min))
11110 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11111 nil t)
11112 (match-beginning 0))))
11113 (if pos (goto-char pos))
11114 pos))
11116 (defconst org-dblock-start-re
11117 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11118 "Matches the start line of a dynamic block, with parameters.")
11120 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11121 "Matches the end of a dynamic block.")
11123 (defun org-create-dblock (plist)
11124 "Create a dynamic block section, with parameters taken from PLIST.
11125 PLIST must contain a :name entry which is used as name of the block."
11126 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11127 (end-of-line 1)
11128 (newline))
11129 (let ((col (current-column))
11130 (name (plist-get plist :name)))
11131 (insert "#+BEGIN: " name)
11132 (while plist
11133 (if (eq (car plist) :name)
11134 (setq plist (cddr plist))
11135 (insert " " (prin1-to-string (pop plist)))))
11136 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11137 (beginning-of-line -2)))
11139 (defun org-prepare-dblock ()
11140 "Prepare dynamic block for refresh.
11141 This empties the block, puts the cursor at the insert position and returns
11142 the property list including an extra property :name with the block name."
11143 (unless (looking-at org-dblock-start-re)
11144 (error "Not at a dynamic block"))
11145 (let* ((begdel (1+ (match-end 0)))
11146 (name (org-no-properties (match-string 1)))
11147 (params (append (list :name name)
11148 (read (concat "(" (match-string 3) ")")))))
11149 (save-excursion
11150 (beginning-of-line 1)
11151 (skip-chars-forward " \t")
11152 (setq params (plist-put params :indentation-column (current-column))))
11153 (unless (re-search-forward org-dblock-end-re nil t)
11154 (error "Dynamic block not terminated"))
11155 (setq params
11156 (append params
11157 (list :content (buffer-substring
11158 begdel (match-beginning 0)))))
11159 (delete-region begdel (match-beginning 0))
11160 (goto-char begdel)
11161 (open-line 1)
11162 params))
11164 (defun org-map-dblocks (&optional command)
11165 "Apply COMMAND to all dynamic blocks in the current buffer.
11166 If COMMAND is not given, use `org-update-dblock'."
11167 (let ((cmd (or command 'org-update-dblock)))
11168 (save-excursion
11169 (goto-char (point-min))
11170 (while (re-search-forward org-dblock-start-re nil t)
11171 (goto-char (match-beginning 0))
11172 (save-excursion
11173 (condition-case nil
11174 (funcall cmd)
11175 (error (message "Error during update of dynamic block"))))
11176 (unless (re-search-forward org-dblock-end-re nil t)
11177 (error "Dynamic block not terminated"))))))
11179 (defun org-dblock-update (&optional arg)
11180 "User command for updating dynamic blocks.
11181 Update the dynamic block at point. With prefix ARG, update all dynamic
11182 blocks in the buffer."
11183 (interactive "P")
11184 (if arg
11185 (org-update-all-dblocks)
11186 (or (looking-at org-dblock-start-re)
11187 (org-beginning-of-dblock))
11188 (org-update-dblock)))
11190 (defun org-update-dblock ()
11191 "Update the dynamic block at point.
11192 This means to empty the block, parse for parameters and then call
11193 the correct writing function."
11194 (interactive)
11195 (save-window-excursion
11196 (let* ((pos (point))
11197 (line (org-current-line))
11198 (params (org-prepare-dblock))
11199 (name (plist-get params :name))
11200 (indent (plist-get params :indentation-column))
11201 (cmd (intern (concat "org-dblock-write:" name))))
11202 (message "Updating dynamic block `%s' at line %d..." name line)
11203 (funcall cmd params)
11204 (message "Updating dynamic block `%s' at line %d...done" name line)
11205 (goto-char pos)
11206 (when (and indent (> indent 0))
11207 (setq indent (make-string indent ?\ ))
11208 (save-excursion
11209 (org-beginning-of-dblock)
11210 (forward-line 1)
11211 (while (not (looking-at org-dblock-end-re))
11212 (insert indent)
11213 (beginning-of-line 2))
11214 (when (looking-at org-dblock-end-re)
11215 (and (looking-at "[ \t]+")
11216 (replace-match ""))
11217 (insert indent)))))))
11219 (defun org-beginning-of-dblock ()
11220 "Find the beginning of the dynamic block at point.
11221 Error if there is no such block at point."
11222 (let ((pos (point))
11223 beg)
11224 (end-of-line 1)
11225 (if (and (re-search-backward org-dblock-start-re nil t)
11226 (setq beg (match-beginning 0))
11227 (re-search-forward org-dblock-end-re nil t)
11228 (> (match-end 0) pos))
11229 (goto-char beg)
11230 (goto-char pos)
11231 (error "Not in a dynamic block"))))
11233 ;;;###autoload
11234 (defun org-update-all-dblocks ()
11235 "Update all dynamic blocks in the buffer.
11236 This function can be used in a hook."
11237 (interactive)
11238 (when (derived-mode-p 'org-mode)
11239 (org-map-dblocks 'org-update-dblock)))
11242 ;;;; Completion
11244 (defconst org-additional-option-like-keywords
11245 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11246 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11247 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11248 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11249 "BEGIN:" "END:"
11250 "ORGTBL" "TBLFM:" "TBLNAME:"
11251 "BEGIN_EXAMPLE" "END_EXAMPLE"
11252 "BEGIN_VERBATIM" "END_VERBATIM"
11253 "BEGIN_QUOTE" "END_QUOTE"
11254 "BEGIN_VERSE" "END_VERSE"
11255 "BEGIN_CENTER" "END_CENTER"
11256 "BEGIN_SRC" "END_SRC"
11257 "BEGIN_RESULT" "END_RESULT"
11258 "BEGIN_lstlisting" "END_lstlisting"
11259 "NAME:" "RESULTS:"
11260 "HEADER:" "HEADERS:"
11261 "COLUMNS:" "PROPERTY:"
11262 "CAPTION:" "LABEL:"
11263 "SETUPFILE:"
11264 "INCLUDE:"
11265 "BIND:"
11266 "MACRO:"))
11268 (defconst org-options-keywords
11269 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11270 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11271 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11272 "LINK_UP:" "LINK_HOME:" "LINK:"
11273 "XSLT:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11274 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11275 "FILETAGS:" "ARCHIVE:"))
11277 (defconst org-additional-option-like-keywords-for-flyspell
11278 (delete-dups
11279 (split-string
11280 (mapconcat (lambda(k)
11281 (replace-regexp-in-string
11282 "_\\|:" " "
11283 (concat k " " (downcase k) " " (upcase k))))
11284 (append org-options-keywords org-additional-option-like-keywords)
11285 " ")
11286 " +" t)))
11288 (defcustom org-structure-template-alist
11290 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11291 "<src lang=\"?\">\n\n</src>")
11292 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11293 "<example>\n?\n</example>")
11294 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11295 "<quote>\n?\n</quote>")
11296 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11297 "<verse>\n?\n</verse>")
11298 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11299 "<center>\n?\n</center>")
11300 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11301 "<literal style=\"latex\">\n?\n</literal>")
11302 ("L" "#+LaTeX: "
11303 "<literal style=\"latex\">?</literal>")
11304 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11305 "<literal style=\"html\">\n?\n</literal>")
11306 ("H" "#+HTML: "
11307 "<literal style=\"html\">?</literal>")
11308 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11309 ("A" "#+ASCII: ")
11310 ("i" "#+INDEX: ?"
11311 "#+INDEX: ?")
11312 ("I" "#+INCLUDE %file ?"
11313 "<include file=%file markup=\"?\">")
11315 "Structure completion elements.
11316 This is a list of abbreviation keys and values. The value gets inserted
11317 if you type `<' followed by the key and then press the completion key,
11318 usually `M-TAB'. %file will be replaced by a file name after prompting
11319 for the file using completion. The cursor will be placed at the position
11320 of the `?` in the template.
11321 There are two templates for each key, the first uses the original Org syntax,
11322 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11323 the default when the /org-mtags.el/ module has been loaded. See also the
11324 variable `org-mtags-prefer-muse-templates'."
11325 :group 'org-completion
11326 :type '(repeat
11327 (string :tag "Key")
11328 (string :tag "Template")
11329 (string :tag "Muse Template")))
11331 (defun org-try-structure-completion ()
11332 "Try to complete a structure template before point.
11333 This looks for strings like \"<e\" on an otherwise empty line and
11334 expands them."
11335 (let ((l (buffer-substring (point-at-bol) (point)))
11337 (when (and (looking-at "[ \t]*$")
11338 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11339 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11340 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11341 (match-beginning 1)) a)
11342 t)))
11344 (defun org-complete-expand-structure-template (start cell)
11345 "Expand a structure template."
11346 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11347 (rpl (nth (if musep 2 1) cell))
11348 (ind ""))
11349 (delete-region start (point))
11350 (when (string-match "\\`#\\+" rpl)
11351 (cond
11352 ((bolp))
11353 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11354 (setq ind (buffer-substring (point-at-bol) (point))))
11355 (t (newline))))
11356 (setq start (point))
11357 (if (string-match "%file" rpl)
11358 (setq rpl (replace-match
11359 (concat
11360 "\""
11361 (save-match-data
11362 (abbreviate-file-name (read-file-name "Include file: ")))
11363 "\"")
11364 t t rpl)))
11365 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11366 (concat "\n" ind)))
11367 (insert rpl)
11368 (if (re-search-backward "\\?" start t) (delete-char 1))))
11370 ;;;; TODO, DEADLINE, Comments
11372 (defun org-toggle-comment ()
11373 "Change the COMMENT state of an entry."
11374 (interactive)
11375 (save-excursion
11376 (org-back-to-heading)
11377 (let (case-fold-search)
11378 (cond
11379 ((looking-at (format org-heading-keyword-regexp-format
11380 org-comment-string))
11381 (goto-char (match-end 1))
11382 (looking-at (concat " +" org-comment-string))
11383 (replace-match "" t t)
11384 (when (eolp) (insert " ")))
11385 ((looking-at org-outline-regexp)
11386 (goto-char (match-end 0))
11387 (insert org-comment-string " "))))))
11389 (defvar org-last-todo-state-is-todo nil
11390 "This is non-nil when the last TODO state change led to a TODO state.
11391 If the last change removed the TODO tag or switched to DONE, then
11392 this is nil.")
11394 (defvar org-setting-tags nil) ; dynamically skipped
11396 (defvar org-todo-setup-filter-hook nil
11397 "Hook for functions that pre-filter todo specs.
11398 Each function takes a todo spec and returns either nil or the spec
11399 transformed into canonical form." )
11401 (defvar org-todo-get-default-hook nil
11402 "Hook for functions that get a default item for todo.
11403 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11404 nil or a string to be used for the todo mark." )
11406 (defvar org-agenda-headline-snapshot-before-repeat)
11408 (defun org-current-effective-time ()
11409 "Return current time adjusted for `org-extend-today-until' variable."
11410 (let* ((ct (org-current-time))
11411 (dct (decode-time ct))
11412 (ct1
11413 (if (and org-use-effective-time
11414 (< (nth 2 dct) org-extend-today-until))
11415 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11416 ct)))
11417 ct1))
11419 (defun org-todo-yesterday (&optional arg)
11420 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11421 (interactive "P")
11422 (if (eq major-mode 'org-agenda-mode)
11423 (apply 'org-agenda-todo-yesterday arg)
11424 (let* ((hour (third (decode-time
11425 (org-current-time))))
11426 (org-extend-today-until (1+ hour)))
11427 (org-todo arg))))
11429 (defun org-todo (&optional arg)
11430 "Change the TODO state of an item.
11431 The state of an item is given by a keyword at the start of the heading,
11432 like
11433 *** TODO Write paper
11434 *** DONE Call mom
11436 The different keywords are specified in the variable `org-todo-keywords'.
11437 By default the available states are \"TODO\" and \"DONE\".
11438 So for this example: when the item starts with TODO, it is changed to DONE.
11439 When it starts with DONE, the DONE is removed. And when neither TODO nor
11440 DONE are present, add TODO at the beginning of the heading.
11442 With \\[universal-argument] prefix arg, use completion to determine the new \
11443 state.
11444 With numeric prefix arg, switch to that state.
11445 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11446 keywords (nextset).
11447 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11448 With a numeric prefix arg of 0, inhibit note taking for the change.
11450 For calling through lisp, arg is also interpreted in the following way:
11451 'none -> empty state
11452 \"\"(empty string) -> switch to empty state
11453 'done -> switch to DONE
11454 'nextset -> switch to the next set of keywords
11455 'previousset -> switch to the previous set of keywords
11456 \"WAITING\" -> switch to the specified keyword, but only if it
11457 really is a member of `org-todo-keywords'."
11458 (interactive "P")
11459 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11460 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11461 'region-start-level 'region))
11462 org-loop-over-headlines-in-active-region)
11463 (org-map-entries
11464 `(org-todo ,arg)
11465 org-loop-over-headlines-in-active-region
11466 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11467 (if (equal arg '(16)) (setq arg 'nextset))
11468 (let ((org-blocker-hook org-blocker-hook)
11469 (case-fold-search nil))
11470 (when (equal arg '(64))
11471 (setq arg nil org-blocker-hook nil))
11472 (when (and org-blocker-hook
11473 (or org-inhibit-blocking
11474 (org-entry-get nil "NOBLOCKING")))
11475 (setq org-blocker-hook nil))
11476 (save-excursion
11477 (catch 'exit
11478 (org-back-to-heading t)
11479 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11480 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11481 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11482 (let* ((match-data (match-data))
11483 (startpos (point-at-bol))
11484 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11485 (org-log-done org-log-done)
11486 (org-log-repeat org-log-repeat)
11487 (org-todo-log-states org-todo-log-states)
11488 (org-inhibit-logging
11489 (if (equal arg 0)
11490 (progn (setq arg nil) 'note) org-inhibit-logging))
11491 (this (match-string 1))
11492 (hl-pos (match-beginning 0))
11493 (head (org-get-todo-sequence-head this))
11494 (ass (assoc head org-todo-kwd-alist))
11495 (interpret (nth 1 ass))
11496 (done-word (nth 3 ass))
11497 (final-done-word (nth 4 ass))
11498 (org-last-state (or this ""))
11499 (completion-ignore-case t)
11500 (member (member this org-todo-keywords-1))
11501 (tail (cdr member))
11502 (org-state (cond
11503 ((and org-todo-key-trigger
11504 (or (and (equal arg '(4))
11505 (eq org-use-fast-todo-selection 'prefix))
11506 (and (not arg) org-use-fast-todo-selection
11507 (not (eq org-use-fast-todo-selection
11508 'prefix)))))
11509 ;; Use fast selection
11510 (org-fast-todo-selection))
11511 ((and (equal arg '(4))
11512 (or (not org-use-fast-todo-selection)
11513 (not org-todo-key-trigger)))
11514 ;; Read a state with completion
11515 (org-icompleting-read
11516 "State: " (mapcar (lambda(x) (list x))
11517 org-todo-keywords-1)
11518 nil t))
11519 ((eq arg 'right)
11520 (if this
11521 (if tail (car tail) nil)
11522 (car org-todo-keywords-1)))
11523 ((eq arg 'left)
11524 (if (equal member org-todo-keywords-1)
11526 (if this
11527 (nth (- (length org-todo-keywords-1)
11528 (length tail) 2)
11529 org-todo-keywords-1)
11530 (org-last org-todo-keywords-1))))
11531 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11532 (setq arg nil))) ; hack to fall back to cycling
11533 (arg
11534 ;; user or caller requests a specific state
11535 (cond
11536 ((equal arg "") nil)
11537 ((eq arg 'none) nil)
11538 ((eq arg 'done) (or done-word (car org-done-keywords)))
11539 ((eq arg 'nextset)
11540 (or (car (cdr (member head org-todo-heads)))
11541 (car org-todo-heads)))
11542 ((eq arg 'previousset)
11543 (let ((org-todo-heads (reverse org-todo-heads)))
11544 (or (car (cdr (member head org-todo-heads)))
11545 (car org-todo-heads))))
11546 ((car (member arg org-todo-keywords-1)))
11547 ((stringp arg)
11548 (error "State `%s' not valid in this file" arg))
11549 ((nth (1- (prefix-numeric-value arg))
11550 org-todo-keywords-1))))
11551 ((null member) (or head (car org-todo-keywords-1)))
11552 ((equal this final-done-word) nil) ;; -> make empty
11553 ((null tail) nil) ;; -> first entry
11554 ((memq interpret '(type priority))
11555 (if (eq this-command last-command)
11556 (car tail)
11557 (if (> (length tail) 0)
11558 (or done-word (car org-done-keywords))
11559 nil)))
11561 (car tail))))
11562 (org-state (or
11563 (run-hook-with-args-until-success
11564 'org-todo-get-default-hook org-state org-last-state)
11565 org-state))
11566 (next (if org-state (concat " " org-state " ") " "))
11567 (change-plist (list :type 'todo-state-change :from this :to org-state
11568 :position startpos))
11569 dolog now-done-p)
11570 (when org-blocker-hook
11571 (setq org-last-todo-state-is-todo
11572 (not (member this org-done-keywords)))
11573 (unless (save-excursion
11574 (save-match-data
11575 (org-with-wide-buffer
11576 (run-hook-with-args-until-failure
11577 'org-blocker-hook change-plist))))
11578 (if (org-called-interactively-p 'interactive)
11579 (error "TODO state change from %s to %s blocked" this org-state)
11580 ;; fail silently
11581 (message "TODO state change from %s to %s blocked" this org-state)
11582 (throw 'exit nil))))
11583 (store-match-data match-data)
11584 (replace-match next t t)
11585 (unless (pos-visible-in-window-p hl-pos)
11586 (message "TODO state changed to %s" (org-trim next)))
11587 (unless head
11588 (setq head (org-get-todo-sequence-head org-state)
11589 ass (assoc head org-todo-kwd-alist)
11590 interpret (nth 1 ass)
11591 done-word (nth 3 ass)
11592 final-done-word (nth 4 ass)))
11593 (when (memq arg '(nextset previousset))
11594 (message "Keyword-Set %d/%d: %s"
11595 (- (length org-todo-sets) -1
11596 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11597 (length org-todo-sets)
11598 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11599 (setq org-last-todo-state-is-todo
11600 (not (member org-state org-done-keywords)))
11601 (setq now-done-p (and (member org-state org-done-keywords)
11602 (not (member this org-done-keywords))))
11603 (and logging (org-local-logging logging))
11604 (when (and (or org-todo-log-states org-log-done)
11605 (not (eq org-inhibit-logging t))
11606 (not (memq arg '(nextset previousset))))
11607 ;; we need to look at recording a time and note
11608 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11609 (nth 2 (assoc this org-todo-log-states))))
11610 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11611 (setq dolog 'time))
11612 (when (and org-state
11613 (member org-state org-not-done-keywords)
11614 (not (member this org-not-done-keywords)))
11615 ;; This is now a todo state and was not one before
11616 ;; If there was a CLOSED time stamp, get rid of it.
11617 (org-add-planning-info nil nil 'closed))
11618 (when (and now-done-p org-log-done)
11619 ;; It is now done, and it was not done before
11620 (org-add-planning-info 'closed (org-current-effective-time))
11621 (if (and (not dolog) (eq 'note org-log-done))
11622 (org-add-log-setup 'done org-state this 'findpos 'note)))
11623 (when (and org-state dolog)
11624 ;; This is a non-nil state, and we need to log it
11625 (org-add-log-setup 'state org-state this 'findpos dolog)))
11626 ;; Fixup tag positioning
11627 (org-todo-trigger-tag-changes org-state)
11628 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11629 (when org-provide-todo-statistics
11630 (org-update-parent-todo-statistics))
11631 (run-hooks 'org-after-todo-state-change-hook)
11632 (if (and arg (not (member org-state org-done-keywords)))
11633 (setq head (org-get-todo-sequence-head org-state)))
11634 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11635 ;; Do we need to trigger a repeat?
11636 (when now-done-p
11637 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11638 ;; This is for the agenda, take a snapshot of the headline.
11639 (save-match-data
11640 (setq org-agenda-headline-snapshot-before-repeat
11641 (org-get-heading))))
11642 (org-auto-repeat-maybe org-state))
11643 ;; Fixup cursor location if close to the keyword
11644 (if (and (outline-on-heading-p)
11645 (not (bolp))
11646 (save-excursion (beginning-of-line 1)
11647 (looking-at org-todo-line-regexp))
11648 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11649 (progn
11650 (goto-char (or (match-end 2) (match-end 1)))
11651 (and (looking-at " ") (just-one-space))))
11652 (when org-trigger-hook
11653 (save-excursion
11654 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11656 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11657 "Block turning an entry into a TODO, using the hierarchy.
11658 This checks whether the current task should be blocked from state
11659 changes. Such blocking occurs when:
11661 1. The task has children which are not all in a completed state.
11663 2. A task has a parent with the property :ORDERED:, and there
11664 are siblings prior to the current task with incomplete
11665 status.
11667 3. The parent of the task is blocked because it has siblings that should
11668 be done first, or is child of a block grandparent TODO entry."
11670 (if (not org-enforce-todo-dependencies)
11671 t ; if locally turned off don't block
11672 (catch 'dont-block
11673 ;; If this is not a todo state change, or if this entry is already DONE,
11674 ;; do not block
11675 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11676 (member (plist-get change-plist :from)
11677 (cons 'done org-done-keywords))
11678 (member (plist-get change-plist :to)
11679 (cons 'todo org-not-done-keywords))
11680 (not (plist-get change-plist :to)))
11681 (throw 'dont-block t))
11682 ;; If this task has children, and any are undone, it's blocked
11683 (save-excursion
11684 (org-back-to-heading t)
11685 (let ((this-level (funcall outline-level)))
11686 (outline-next-heading)
11687 (let ((child-level (funcall outline-level)))
11688 (while (and (not (eobp))
11689 (> child-level this-level))
11690 ;; this todo has children, check whether they are all
11691 ;; completed
11692 (if (and (not (org-entry-is-done-p))
11693 (org-entry-is-todo-p))
11694 (throw 'dont-block nil))
11695 (outline-next-heading)
11696 (setq child-level (funcall outline-level))))))
11697 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11698 ;; any previous siblings are undone, it's blocked
11699 (save-excursion
11700 (org-back-to-heading t)
11701 (let* ((pos (point))
11702 (parent-pos (and (org-up-heading-safe) (point))))
11703 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11704 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11705 (forward-line 1)
11706 (re-search-forward org-not-done-heading-regexp pos t))
11707 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11708 ;; Search further up the hierarchy, to see if an ancestor is blocked
11709 (while t
11710 (goto-char parent-pos)
11711 (if (not (looking-at org-not-done-heading-regexp))
11712 (throw 'dont-block t)) ; do not block, parent is not a TODO
11713 (setq pos (point))
11714 (setq parent-pos (and (org-up-heading-safe) (point)))
11715 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11716 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11717 (forward-line 1)
11718 (re-search-forward org-not-done-heading-regexp pos t))
11719 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11721 (defcustom org-track-ordered-property-with-tag nil
11722 "Should the ORDERED property also be shown as a tag?
11723 The ORDERED property decides if an entry should require subtasks to be
11724 completed in sequence. Since a property is not very visible, setting
11725 this option means that toggling the ORDERED property with the command
11726 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11727 not relevant for the behavior, but it makes things more visible.
11729 Note that toggling the tag with tags commands will not change the property
11730 and therefore not influence behavior!
11732 This can be t, meaning the tag ORDERED should be used, It can also be a
11733 string to select a different tag for this task."
11734 :group 'org-todo
11735 :type '(choice
11736 (const :tag "No tracking" nil)
11737 (const :tag "Track with ORDERED tag" t)
11738 (string :tag "Use other tag")))
11740 (defun org-toggle-ordered-property ()
11741 "Toggle the ORDERED property of the current entry.
11742 For better visibility, you can track the value of this property with a tag.
11743 See variable `org-track-ordered-property-with-tag'."
11744 (interactive)
11745 (let* ((t1 org-track-ordered-property-with-tag)
11746 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11747 (save-excursion
11748 (org-back-to-heading)
11749 (if (org-entry-get nil "ORDERED")
11750 (progn
11751 (org-delete-property "ORDERED")
11752 (and tag (org-toggle-tag tag 'off))
11753 (message "Subtasks can be completed in arbitrary order"))
11754 (org-entry-put nil "ORDERED" "t")
11755 (and tag (org-toggle-tag tag 'on))
11756 (message "Subtasks must be completed in sequence")))))
11758 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11759 (defun org-block-todo-from-checkboxes (change-plist)
11760 "Block turning an entry into a TODO, using checkboxes.
11761 This checks whether the current task should be blocked from state
11762 changes because there are unchecked boxes in this entry."
11763 (if (not org-enforce-todo-checkbox-dependencies)
11764 t ; if locally turned off don't block
11765 (catch 'dont-block
11766 ;; If this is not a todo state change, or if this entry is already DONE,
11767 ;; do not block
11768 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11769 (member (plist-get change-plist :from)
11770 (cons 'done org-done-keywords))
11771 (member (plist-get change-plist :to)
11772 (cons 'todo org-not-done-keywords))
11773 (not (plist-get change-plist :to)))
11774 (throw 'dont-block t))
11775 ;; If this task has checkboxes that are not checked, it's blocked
11776 (save-excursion
11777 (org-back-to-heading t)
11778 (let ((beg (point)) end)
11779 (outline-next-heading)
11780 (setq end (point))
11781 (goto-char beg)
11782 (if (org-list-search-forward
11783 (concat (org-item-beginning-re)
11784 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11785 "\\[[- ]\\]")
11786 end t)
11787 (progn
11788 (if (boundp 'org-blocked-by-checkboxes)
11789 (setq org-blocked-by-checkboxes t))
11790 (throw 'dont-block nil)))))
11791 t))) ; do not block
11793 (defun org-entry-blocked-p ()
11794 "Is the current entry blocked?"
11795 (if (org-entry-get nil "NOBLOCKING")
11796 nil ;; Never block this entry
11797 (not
11798 (run-hook-with-args-until-failure
11799 'org-blocker-hook
11800 (list :type 'todo-state-change
11801 :position (point)
11802 :from 'todo
11803 :to 'done)))))
11805 (defun org-update-statistics-cookies (all)
11806 "Update the statistics cookie, either from TODO or from checkboxes.
11807 This should be called with the cursor in a line with a statistics cookie."
11808 (interactive "P")
11809 (if all
11810 (progn
11811 (org-update-checkbox-count 'all)
11812 (org-map-entries 'org-update-parent-todo-statistics))
11813 (if (not (org-at-heading-p))
11814 (org-update-checkbox-count)
11815 (let ((pos (move-marker (make-marker) (point)))
11816 end l1 l2)
11817 (ignore-errors (org-back-to-heading t))
11818 (if (not (org-at-heading-p))
11819 (org-update-checkbox-count)
11820 (setq l1 (org-outline-level))
11821 (setq end (save-excursion
11822 (outline-next-heading)
11823 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11824 (point)))
11825 (if (and (save-excursion
11826 (re-search-forward
11827 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11828 (not (save-excursion (re-search-forward
11829 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11830 (org-update-checkbox-count)
11831 (if (and l2 (> l2 l1))
11832 (progn
11833 (goto-char end)
11834 (org-update-parent-todo-statistics))
11835 (goto-char pos)
11836 (beginning-of-line 1)
11837 (while (re-search-forward
11838 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11839 (point-at-eol) t)
11840 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11841 (goto-char pos)
11842 (move-marker pos nil)))))
11844 (defvar org-entry-property-inherited-from) ;; defined below
11845 (defun org-update-parent-todo-statistics ()
11846 "Update any statistics cookie in the parent of the current headline.
11847 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11848 the entire subtree and this will travel up the hierarchy and update
11849 statistics everywhere."
11850 (let* ((prop (save-excursion (org-up-heading-safe)
11851 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11852 (recursive (or (not org-hierarchical-todo-statistics)
11853 (and prop (string-match "\\<recursive\\>" prop))))
11854 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11856 (first t)
11857 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11858 level ltoggle l1 new ndel
11859 (cnt-all 0) (cnt-done 0) is-percent kwd
11860 checkbox-beg ov ovs ove cookie-present)
11861 (catch 'exit
11862 (save-excursion
11863 (beginning-of-line 1)
11864 (setq ltoggle (funcall outline-level))
11865 ;; Three situations are to consider:
11867 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11868 ;; to the top-level ancestor on the headline;
11870 ;; 2. If parent has "recursive" property, repeat up to the
11871 ;; headline setting that property, taking inheritance into
11872 ;; account;
11874 ;; 3. Else, move up to direct parent and proceed only once.
11875 (while (and (setq level (org-up-heading-safe))
11876 (or recursive first)
11877 (>= (point) lim))
11878 (setq first nil cookie-present nil)
11879 (unless (and level
11880 (not (string-match
11881 "\\<checkbox\\>"
11882 (downcase (or (org-entry-get nil "COOKIE_DATA")
11883 "")))))
11884 (throw 'exit nil))
11885 (while (re-search-forward box-re (point-at-eol) t)
11886 (setq cnt-all 0 cnt-done 0 cookie-present t)
11887 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11888 (save-match-data
11889 (unless (outline-next-heading) (throw 'exit nil))
11890 (while (and (looking-at org-complex-heading-regexp)
11891 (> (setq l1 (length (match-string 1))) level))
11892 (setq kwd (and (or recursive (= l1 ltoggle))
11893 (match-string 2)))
11894 (if (or (eq org-provide-todo-statistics 'all-headlines)
11895 (and (listp org-provide-todo-statistics)
11896 (or (member kwd org-provide-todo-statistics)
11897 (member kwd org-done-keywords))))
11898 (setq cnt-all (1+ cnt-all))
11899 (if (eq org-provide-todo-statistics t)
11900 (and kwd (setq cnt-all (1+ cnt-all)))))
11901 (and (member kwd org-done-keywords)
11902 (setq cnt-done (1+ cnt-done)))
11903 (outline-next-heading)))
11904 (setq new
11905 (if is-percent
11906 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11907 (format "[%d/%d]" cnt-done cnt-all))
11908 ndel (- (match-end 0) checkbox-beg))
11909 ;; handle overlays when updating cookie from column view
11910 (when (setq ov (car (overlays-at checkbox-beg)))
11911 (setq ovs (overlay-start ov) ove (overlay-end ov))
11912 (delete-overlay ov))
11913 (goto-char checkbox-beg)
11914 (insert new)
11915 (delete-region (point) (+ (point) ndel))
11916 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11917 (when ov (move-overlay ov ovs ove)))
11918 (when cookie-present
11919 (run-hook-with-args 'org-after-todo-statistics-hook
11920 cnt-done (- cnt-all cnt-done))))))
11921 (run-hooks 'org-todo-statistics-hook)))
11923 (defvar org-after-todo-statistics-hook nil
11924 "Hook that is called after a TODO statistics cookie has been updated.
11925 Each function is called with two arguments: the number of not-done entries
11926 and the number of done entries.
11928 For example, the following function, when added to this hook, will switch
11929 an entry to DONE when all children are done, and back to TODO when new
11930 entries are set to a TODO status. Note that this hook is only called
11931 when there is a statistics cookie in the headline!
11933 (defun org-summary-todo (n-done n-not-done)
11934 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11935 (let (org-log-done org-log-states) ; turn off logging
11936 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11939 (defvar org-todo-statistics-hook nil
11940 "Hook that is run whenever Org thinks TODO statistics should be updated.
11941 This hook runs even if there is no statistics cookie present, in which case
11942 `org-after-todo-statistics-hook' would not run.")
11944 (defun org-todo-trigger-tag-changes (state)
11945 "Apply the changes defined in `org-todo-state-tags-triggers'."
11946 (let ((l org-todo-state-tags-triggers)
11947 changes)
11948 (when (or (not state) (equal state ""))
11949 (setq changes (append changes (cdr (assoc "" l)))))
11950 (when (and (stringp state) (> (length state) 0))
11951 (setq changes (append changes (cdr (assoc state l)))))
11952 (when (member state org-not-done-keywords)
11953 (setq changes (append changes (cdr (assoc 'todo l)))))
11954 (when (member state org-done-keywords)
11955 (setq changes (append changes (cdr (assoc 'done l)))))
11956 (dolist (c changes)
11957 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11959 (defun org-local-logging (value)
11960 "Get logging settings from a property VALUE."
11961 (let* (words w a)
11962 ;; directly set the variables, they are already local.
11963 (setq org-log-done nil
11964 org-log-repeat nil
11965 org-todo-log-states nil)
11966 (setq words (org-split-string value))
11967 (while (setq w (pop words))
11968 (cond
11969 ((setq a (assoc w org-startup-options))
11970 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11971 (set (nth 1 a) (nth 2 a))))
11972 ((setq a (org-extract-log-state-settings w))
11973 (and (member (car a) org-todo-keywords-1)
11974 (push a org-todo-log-states)))))))
11976 (defun org-get-todo-sequence-head (kwd)
11977 "Return the head of the TODO sequence to which KWD belongs.
11978 If KWD is not set, check if there is a text property remembering the
11979 right sequence."
11980 (let (p)
11981 (cond
11982 ((not kwd)
11983 (or (get-text-property (point-at-bol) 'org-todo-head)
11984 (progn
11985 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11986 nil (point-at-eol)))
11987 (get-text-property p 'org-todo-head))))
11988 ((not (member kwd org-todo-keywords-1))
11989 (car org-todo-keywords-1))
11990 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11992 (defun org-fast-todo-selection ()
11993 "Fast TODO keyword selection with single keys.
11994 Returns the new TODO keyword, or nil if no state change should occur."
11995 (let* ((fulltable org-todo-key-alist)
11996 (done-keywords org-done-keywords) ;; needed for the faces.
11997 (maxlen (apply 'max (mapcar
11998 (lambda (x)
11999 (if (stringp (car x)) (string-width (car x)) 0))
12000 fulltable)))
12001 (expert nil)
12002 (fwidth (+ maxlen 3 1 3))
12003 (ncol (/ (- (window-width) 4) fwidth))
12004 tg cnt e c tbl
12005 groups ingroup)
12006 (save-excursion
12007 (save-window-excursion
12008 (if expert
12009 (set-buffer (get-buffer-create " *Org todo*"))
12010 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12011 (erase-buffer)
12012 (org-set-local 'org-done-keywords done-keywords)
12013 (setq tbl fulltable cnt 0)
12014 (while (setq e (pop tbl))
12015 (cond
12016 ((equal e '(:startgroup))
12017 (push '() groups) (setq ingroup t)
12018 (when (not (= cnt 0))
12019 (setq cnt 0)
12020 (insert "\n"))
12021 (insert "{ "))
12022 ((equal e '(:endgroup))
12023 (setq ingroup nil cnt 0)
12024 (insert "}\n"))
12025 ((equal e '(:newline))
12026 (when (not (= cnt 0))
12027 (setq cnt 0)
12028 (insert "\n")
12029 (setq e (car tbl))
12030 (while (equal (car tbl) '(:newline))
12031 (insert "\n")
12032 (setq tbl (cdr tbl)))))
12034 (setq tg (car e) c (cdr e))
12035 (if ingroup (push tg (car groups)))
12036 (setq tg (org-add-props tg nil 'face
12037 (org-get-todo-face tg)))
12038 (if (and (= cnt 0) (not ingroup)) (insert " "))
12039 (insert "[" c "] " tg (make-string
12040 (- fwidth 4 (length tg)) ?\ ))
12041 (when (= (setq cnt (1+ cnt)) ncol)
12042 (insert "\n")
12043 (if ingroup (insert " "))
12044 (setq cnt 0)))))
12045 (insert "\n")
12046 (goto-char (point-min))
12047 (if (not expert) (org-fit-window-to-buffer))
12048 (message "[a-z..]:Set [SPC]:clear")
12049 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12050 (cond
12051 ((or (= c ?\C-g)
12052 (and (= c ?q) (not (rassoc c fulltable))))
12053 (setq quit-flag t))
12054 ((= c ?\ ) nil)
12055 ((setq e (rassoc c fulltable) tg (car e))
12057 (t (setq quit-flag t)))))))
12059 (defun org-entry-is-todo-p ()
12060 (member (org-get-todo-state) org-not-done-keywords))
12062 (defun org-entry-is-done-p ()
12063 (member (org-get-todo-state) org-done-keywords))
12065 (defun org-get-todo-state ()
12066 (save-excursion
12067 (org-back-to-heading t)
12068 (and (looking-at org-todo-line-regexp)
12069 (match-end 2)
12070 (match-string 2))))
12072 (defun org-at-date-range-p (&optional inactive-ok)
12073 "Is the cursor inside a date range?"
12074 (interactive)
12075 (save-excursion
12076 (catch 'exit
12077 (let ((pos (point)))
12078 (skip-chars-backward "^[<\r\n")
12079 (skip-chars-backward "<[")
12080 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12081 (>= (match-end 0) pos)
12082 (throw 'exit t))
12083 (skip-chars-backward "^<[\r\n")
12084 (skip-chars-backward "<[")
12085 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12086 (>= (match-end 0) pos)
12087 (throw 'exit t)))
12088 nil)))
12090 (defun org-get-repeat (&optional tagline)
12091 "Check if there is a deadline/schedule with repeater in this entry."
12092 (save-match-data
12093 (save-excursion
12094 (org-back-to-heading t)
12095 (and (re-search-forward (if tagline
12096 (concat tagline "\\s-*" org-repeat-re)
12097 org-repeat-re)
12098 (org-entry-end-position) t)
12099 (match-string-no-properties 1)))))
12101 (defvar org-last-changed-timestamp)
12102 (defvar org-last-inserted-timestamp)
12103 (defvar org-log-post-message)
12104 (defvar org-log-note-purpose)
12105 (defvar org-log-note-how)
12106 (defvar org-log-note-extra)
12107 (defun org-auto-repeat-maybe (done-word)
12108 "Check if the current headline contains a repeated deadline/schedule.
12109 If yes, set TODO state back to what it was and change the base date
12110 of repeating deadline/scheduled time stamps to new date.
12111 This function is run automatically after each state change to a DONE state."
12112 ;; last-state is dynamically scoped into this function
12113 (let* ((repeat (org-get-repeat))
12114 (aa (assoc org-last-state org-todo-kwd-alist))
12115 (interpret (nth 1 aa))
12116 (head (nth 2 aa))
12117 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12118 (msg "Entry repeats: ")
12119 (org-log-done nil)
12120 (org-todo-log-states nil)
12121 re type n what ts time to-state)
12122 (when repeat
12123 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12124 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12125 org-todo-repeat-to-state))
12126 (unless (and to-state (member to-state org-todo-keywords-1))
12127 (setq to-state (if (eq interpret 'type) org-last-state head)))
12128 (org-todo to-state)
12129 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12130 (org-entry-put nil "LAST_REPEAT" (format-time-string
12131 (org-time-stamp-format t t))))
12132 (when org-log-repeat
12133 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12134 (memq 'org-add-log-note post-command-hook))
12135 ;; OK, we are already setup for some record
12136 (if (eq org-log-repeat 'note)
12137 ;; make sure we take a note, not only a time stamp
12138 (setq org-log-note-how 'note))
12139 ;; Set up for taking a record
12140 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12141 org-last-state
12142 'findpos org-log-repeat)))
12143 (org-back-to-heading t)
12144 (org-add-planning-info nil nil 'closed)
12145 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12146 org-deadline-time-regexp "\\)\\|\\("
12147 org-ts-regexp "\\)"))
12148 (while (re-search-forward
12149 re (save-excursion (outline-next-heading) (point)) t)
12150 (setq type (if (match-end 1) org-scheduled-string
12151 (if (match-end 3) org-deadline-string "Plain:"))
12152 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12153 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12154 (setq n (string-to-number (match-string 2 ts))
12155 what (match-string 3 ts))
12156 (if (equal what "w") (setq n (* n 7) what "d"))
12157 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12158 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12159 ;; Preparation, see if we need to modify the start date for the change
12160 (when (match-end 1)
12161 (setq time (save-match-data (org-time-string-to-time ts)))
12162 (cond
12163 ((equal (match-string 1 ts) ".")
12164 ;; Shift starting date to today
12165 (org-timestamp-change
12166 (- (org-today) (time-to-days time))
12167 'day))
12168 ((equal (match-string 1 ts) "+")
12169 (let ((nshiftmax 10) (nshift 0))
12170 (while (or (= nshift 0)
12171 (<= (time-to-days time)
12172 (time-to-days (current-time))))
12173 (when (= (incf nshift) nshiftmax)
12174 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12175 (error "Abort")))
12176 (org-timestamp-change n (cdr (assoc what whata)))
12177 (org-at-timestamp-p t)
12178 (setq ts (match-string 1))
12179 (setq time (save-match-data (org-time-string-to-time ts)))))
12180 (org-timestamp-change (- n) (cdr (assoc what whata)))
12181 ;; rematch, so that we have everything in place for the real shift
12182 (org-at-timestamp-p t)
12183 (setq ts (match-string 1))
12184 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12185 (org-timestamp-change n (cdr (assoc what whata)))
12186 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12187 (setq org-log-post-message msg)
12188 (message "%s" msg))))
12190 (defun org-show-todo-tree (arg)
12191 "Make a compact tree which shows all headlines marked with TODO.
12192 The tree will show the lines where the regexp matches, and all higher
12193 headlines above the match.
12194 With a \\[universal-argument] prefix, prompt for a regexp to match.
12195 With a numeric prefix N, construct a sparse tree for the Nth element
12196 of `org-todo-keywords-1'."
12197 (interactive "P")
12198 (let ((case-fold-search nil)
12199 (kwd-re
12200 (cond ((null arg) org-not-done-regexp)
12201 ((equal arg '(4))
12202 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12203 (mapcar 'list org-todo-keywords-1))))
12204 (concat "\\("
12205 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12206 "\\)\\>")))
12207 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12208 (regexp-quote (nth (1- (prefix-numeric-value arg))
12209 org-todo-keywords-1)))
12210 (t (error "Invalid prefix argument: %s" arg)))))
12211 (message "%d TODO entries found"
12212 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12214 (defun org-deadline (&optional remove time)
12215 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12216 With argument REMOVE, remove any deadline from the item.
12217 With argument TIME, set the deadline at the corresponding date. TIME
12218 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12219 (interactive "P")
12220 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12221 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12222 'region-start-level 'region))
12223 org-loop-over-headlines-in-active-region)
12224 (org-map-entries
12225 `(org-deadline ',remove ,time)
12226 org-loop-over-headlines-in-active-region
12227 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12228 (let* ((old-date (org-entry-get nil "DEADLINE"))
12229 (repeater (and old-date
12230 (string-match
12231 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12232 old-date)
12233 (match-string 1 old-date))))
12234 (if remove
12235 (progn
12236 (when (and old-date org-log-redeadline)
12237 (org-add-log-setup 'deldeadline nil old-date 'findpos
12238 org-log-redeadline))
12239 (org-remove-timestamp-with-keyword org-deadline-string)
12240 (message "Item no longer has a deadline."))
12241 (org-add-planning-info 'deadline time 'closed)
12242 (when (and old-date org-log-redeadline
12243 (not (equal old-date
12244 (substring org-last-inserted-timestamp 1 -1))))
12245 (org-add-log-setup 'redeadline nil old-date 'findpos
12246 org-log-redeadline))
12247 (when repeater
12248 (save-excursion
12249 (org-back-to-heading t)
12250 (when (re-search-forward (concat org-deadline-string " "
12251 org-last-inserted-timestamp)
12252 (save-excursion
12253 (outline-next-heading) (point)) t)
12254 (goto-char (1- (match-end 0)))
12255 (insert " " repeater)
12256 (setq org-last-inserted-timestamp
12257 (concat (substring org-last-inserted-timestamp 0 -1)
12258 " " repeater
12259 (substring org-last-inserted-timestamp -1))))))
12260 (message "Deadline on %s" org-last-inserted-timestamp)))))
12262 (defun org-schedule (&optional remove time)
12263 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12264 With argument REMOVE, remove any scheduling date from the item.
12265 With argument TIME, scheduled at the corresponding date. TIME can
12266 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12267 (interactive "P")
12268 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12269 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12270 'region-start-level 'region))
12271 org-loop-over-headlines-in-active-region)
12272 (org-map-entries
12273 `(org-schedule ',remove ,time)
12274 org-loop-over-headlines-in-active-region
12275 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12276 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12277 (repeater (and old-date
12278 (string-match
12279 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12280 old-date)
12281 (match-string 1 old-date))))
12282 (if remove
12283 (progn
12284 (when (and old-date org-log-reschedule)
12285 (org-add-log-setup 'delschedule nil old-date 'findpos
12286 org-log-reschedule))
12287 (org-remove-timestamp-with-keyword org-scheduled-string)
12288 (message "Item is no longer scheduled."))
12289 (org-add-planning-info 'scheduled time 'closed)
12290 (when (and old-date org-log-reschedule
12291 (not (equal old-date
12292 (substring org-last-inserted-timestamp 1 -1))))
12293 (org-add-log-setup 'reschedule nil old-date 'findpos
12294 org-log-reschedule))
12295 (when repeater
12296 (save-excursion
12297 (org-back-to-heading t)
12298 (when (re-search-forward (concat org-scheduled-string " "
12299 org-last-inserted-timestamp)
12300 (save-excursion
12301 (outline-next-heading) (point)) t)
12302 (goto-char (1- (match-end 0)))
12303 (insert " " repeater)
12304 (setq org-last-inserted-timestamp
12305 (concat (substring org-last-inserted-timestamp 0 -1)
12306 " " repeater
12307 (substring org-last-inserted-timestamp -1))))))
12308 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12310 (defun org-get-scheduled-time (pom &optional inherit)
12311 "Get the scheduled time as a time tuple, of a format suitable
12312 for calling org-schedule with, or if there is no scheduling,
12313 returns nil."
12314 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12315 (when time
12316 (apply 'encode-time (org-parse-time-string time)))))
12318 (defun org-get-deadline-time (pom &optional inherit)
12319 "Get the deadline as a time tuple, of a format suitable for
12320 calling org-deadline with, or if there is no scheduling, returns
12321 nil."
12322 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12323 (when time
12324 (apply 'encode-time (org-parse-time-string time)))))
12326 (defun org-remove-timestamp-with-keyword (keyword)
12327 "Remove all time stamps with KEYWORD in the current entry."
12328 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12329 beg)
12330 (save-excursion
12331 (org-back-to-heading t)
12332 (setq beg (point))
12333 (outline-next-heading)
12334 (while (re-search-backward re beg t)
12335 (replace-match "")
12336 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12337 (equal (char-before) ?\ ))
12338 (backward-delete-char 1)
12339 (if (string-match "^[ \t]*$" (buffer-substring
12340 (point-at-bol) (point-at-eol)))
12341 (delete-region (point-at-bol)
12342 (min (point-max) (1+ (point-at-eol))))))))))
12344 (defun org-add-planning-info (what &optional time &rest remove)
12345 "Insert new timestamp with keyword in the line directly after the headline.
12346 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12347 If non is given, the user is prompted for a date.
12348 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12349 be removed."
12350 (interactive)
12351 (let (org-time-was-given org-end-time-was-given ts
12352 end default-time default-input)
12354 (catch 'exit
12355 (when (and (memq what '(scheduled deadline))
12356 (or (not time)
12357 (and (stringp time)
12358 (string-match "^[-+]+[0-9]" time))))
12359 ;; Try to get a default date/time from existing timestamp
12360 (save-excursion
12361 (org-back-to-heading t)
12362 (setq end (save-excursion (outline-next-heading) (point)))
12363 (when (re-search-forward (if (eq what 'scheduled)
12364 org-scheduled-time-regexp
12365 org-deadline-time-regexp)
12366 end t)
12367 (setq ts (match-string 1)
12368 default-time
12369 (apply 'encode-time (org-parse-time-string ts))
12370 default-input (and ts (org-get-compact-tod ts))))))
12371 (when what
12372 (setq time
12373 (if (stringp time)
12374 ;; This is a string (relative or absolute), set proper date
12375 (apply 'encode-time
12376 (org-read-date-analyze
12377 time default-time (decode-time default-time)))
12378 ;; If necessary, get the time from the user
12379 (or time (org-read-date nil 'to-time nil nil
12380 default-time default-input)))))
12382 (when (and org-insert-labeled-timestamps-at-point
12383 (member what '(scheduled deadline)))
12384 (insert
12385 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12386 (org-insert-time-stamp time org-time-was-given
12387 nil nil nil (list org-end-time-was-given))
12388 (setq what nil))
12389 (save-excursion
12390 (save-restriction
12391 (let (col list elt ts buffer-invisibility-spec)
12392 (org-back-to-heading t)
12393 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12394 (goto-char (match-end 1))
12395 (setq col (current-column))
12396 (goto-char (match-end 0))
12397 (if (eobp) (insert "\n") (forward-char 1))
12398 (when (and (not what)
12399 (not (looking-at
12400 (concat "[ \t]*"
12401 org-keyword-time-not-clock-regexp))))
12402 ;; Nothing to add, nothing to remove...... :-)
12403 (throw 'exit nil))
12404 (if (and (not (looking-at org-outline-regexp))
12405 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12406 "[^\r\n]*"))
12407 (not (equal (match-string 1) org-clock-string)))
12408 (narrow-to-region (match-beginning 0) (match-end 0))
12409 (insert-before-markers "\n")
12410 (backward-char 1)
12411 (narrow-to-region (point) (point))
12412 (and org-adapt-indentation (org-indent-to-column col)))
12413 ;; Check if we have to remove something.
12414 (setq list (cons what remove))
12415 (while list
12416 (setq elt (pop list))
12417 (when (or (and (eq elt 'scheduled)
12418 (re-search-forward org-scheduled-time-regexp nil t))
12419 (and (eq elt 'deadline)
12420 (re-search-forward org-deadline-time-regexp nil t))
12421 (and (eq elt 'closed)
12422 (re-search-forward org-closed-time-regexp nil t)))
12423 (replace-match "")
12424 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12425 (and (looking-at "[ \t]+") (replace-match ""))
12426 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12427 (when what
12428 (insert
12429 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12430 (cond ((eq what 'scheduled) org-scheduled-string)
12431 ((eq what 'deadline) org-deadline-string)
12432 ((eq what 'closed) org-closed-string))
12433 " ")
12434 (setq ts (org-insert-time-stamp
12435 time
12436 (or org-time-was-given
12437 (and (eq what 'closed) org-log-done-with-time))
12438 (eq what 'closed)
12439 nil nil (list org-end-time-was-given)))
12440 (insert
12441 (if (not (or (bolp) (eq (char-before) ?\ )
12442 (memq (char-after) '(32 10))
12443 (eobp))) " " ""))
12444 (end-of-line 1))
12445 (goto-char (point-min))
12446 (widen)
12447 (if (and (looking-at "[ \t]*\n")
12448 (equal (char-before) ?\n))
12449 (delete-region (1- (point)) (point-at-eol)))
12450 ts))))))
12452 (defvar org-log-note-marker (make-marker))
12453 (defvar org-log-note-purpose nil)
12454 (defvar org-log-note-state nil)
12455 (defvar org-log-note-previous-state nil)
12456 (defvar org-log-note-how nil)
12457 (defvar org-log-note-extra nil)
12458 (defvar org-log-note-window-configuration nil)
12459 (defvar org-log-note-return-to (make-marker))
12460 (defvar org-log-note-effective-time nil
12461 "Remembered current time so that dynamically scoped
12462 `org-extend-today-until' affects tha timestamps in state change
12463 log")
12465 (defvar org-log-post-message nil
12466 "Message to be displayed after a log note has been stored.
12467 The auto-repeater uses this.")
12469 (defun org-add-note ()
12470 "Add a note to the current entry.
12471 This is done in the same way as adding a state change note."
12472 (interactive)
12473 (org-add-log-setup 'note nil nil 'findpos nil))
12475 (defvar org-property-end-re)
12476 (defun org-add-log-setup (&optional purpose state prev-state
12477 findpos how extra)
12478 "Set up the post command hook to take a note.
12479 If this is about to TODO state change, the new state is expected in STATE.
12480 When FINDPOS is non-nil, find the correct position for the note in
12481 the current entry. If not, assume that it can be inserted at point.
12482 HOW is an indicator what kind of note should be created.
12483 EXTRA is additional text that will be inserted into the notes buffer."
12484 (let* ((org-log-into-drawer (org-log-into-drawer))
12485 (drawer (cond ((stringp org-log-into-drawer)
12486 org-log-into-drawer)
12487 (org-log-into-drawer "LOGBOOK")
12488 (t nil))))
12489 (save-restriction
12490 (save-excursion
12491 (when findpos
12492 (org-back-to-heading t)
12493 (narrow-to-region (point) (save-excursion
12494 (outline-next-heading) (point)))
12495 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12496 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12497 "[^\r\n]*\\)?"))
12498 (goto-char (match-end 0))
12499 (cond
12500 (drawer
12501 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12502 nil t)
12503 (progn
12504 (goto-char (match-end 0))
12505 (or org-log-states-order-reversed
12506 (and (re-search-forward org-property-end-re nil t)
12507 (goto-char (1- (match-beginning 0))))))
12508 (insert "\n:" drawer ":\n:END:")
12509 (beginning-of-line 0)
12510 (org-indent-line)
12511 (beginning-of-line 2)
12512 (org-indent-line)
12513 (end-of-line 0)))
12514 ((and org-log-state-notes-insert-after-drawers
12515 (save-excursion
12516 (forward-line) (looking-at org-drawer-regexp)))
12517 (forward-line)
12518 (while (looking-at org-drawer-regexp)
12519 (goto-char (match-end 0))
12520 (re-search-forward org-property-end-re (point-max) t)
12521 (forward-line))
12522 (forward-line -1)))
12523 (unless org-log-states-order-reversed
12524 (and (= (char-after) ?\n) (forward-char 1))
12525 (org-skip-over-state-notes)
12526 (skip-chars-backward " \t\n\r")))
12527 (move-marker org-log-note-marker (point))
12528 (setq org-log-note-purpose purpose
12529 org-log-note-state state
12530 org-log-note-previous-state prev-state
12531 org-log-note-how how
12532 org-log-note-extra extra
12533 org-log-note-effective-time (org-current-effective-time))
12534 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12536 (defun org-skip-over-state-notes ()
12537 "Skip past the list of State notes in an entry."
12538 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12539 (when (ignore-errors (goto-char (org-in-item-p)))
12540 (let* ((struct (org-list-struct))
12541 (prevs (org-list-prevs-alist struct)))
12542 (while (looking-at "[ \t]*- State")
12543 (goto-char (or (org-list-get-next-item (point) struct prevs)
12544 (org-list-get-item-end (point) struct)))))))
12546 (defun org-add-log-note (&optional purpose)
12547 "Pop up a window for taking a note, and add this note later at point."
12548 (remove-hook 'post-command-hook 'org-add-log-note)
12549 (setq org-log-note-window-configuration (current-window-configuration))
12550 (delete-other-windows)
12551 (move-marker org-log-note-return-to (point))
12552 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12553 (goto-char org-log-note-marker)
12554 (org-switch-to-buffer-other-window "*Org Note*")
12555 (erase-buffer)
12556 (if (memq org-log-note-how '(time state))
12557 (let (current-prefix-arg) (org-store-log-note))
12558 (let ((org-inhibit-startup t)) (org-mode))
12559 (insert (format "# Insert note for %s.
12560 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12561 (cond
12562 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12563 ((eq org-log-note-purpose 'done) "closed todo item")
12564 ((eq org-log-note-purpose 'state)
12565 (format "state change from \"%s\" to \"%s\""
12566 (or org-log-note-previous-state "")
12567 (or org-log-note-state "")))
12568 ((eq org-log-note-purpose 'reschedule)
12569 "rescheduling")
12570 ((eq org-log-note-purpose 'delschedule)
12571 "no longer scheduled")
12572 ((eq org-log-note-purpose 'redeadline)
12573 "changing deadline")
12574 ((eq org-log-note-purpose 'deldeadline)
12575 "removing deadline")
12576 ((eq org-log-note-purpose 'refile)
12577 "refiling")
12578 ((eq org-log-note-purpose 'note)
12579 "this entry")
12580 (t (error "This should not happen")))))
12581 (if org-log-note-extra (insert org-log-note-extra))
12582 (org-set-local 'org-finish-function 'org-store-log-note)
12583 (run-hooks 'org-log-buffer-setup-hook)))
12585 (defvar org-note-abort nil) ; dynamically scoped
12586 (defun org-store-log-note ()
12587 "Finish taking a log note, and insert it to where it belongs."
12588 (let ((txt (buffer-string))
12589 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12590 lines ind bul)
12591 (kill-buffer (current-buffer))
12592 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12593 (setq txt (replace-match "" t t txt)))
12594 (if (string-match "\\s-+\\'" txt)
12595 (setq txt (replace-match "" t t txt)))
12596 (setq lines (org-split-string txt "\n"))
12597 (when (and note (string-match "\\S-" note))
12598 (setq note
12599 (org-replace-escapes
12600 note
12601 (list (cons "%u" (user-login-name))
12602 (cons "%U" user-full-name)
12603 (cons "%t" (format-time-string
12604 (org-time-stamp-format 'long 'inactive)
12605 org-log-note-effective-time))
12606 (cons "%T" (format-time-string
12607 (org-time-stamp-format 'long nil)
12608 org-log-note-effective-time))
12609 (cons "%d" (format-time-string
12610 (org-time-stamp-format nil 'inactive)
12611 org-log-note-effective-time))
12612 (cons "%D" (format-time-string
12613 (org-time-stamp-format nil nil)
12614 org-log-note-effective-time))
12615 (cons "%s" (if org-log-note-state
12616 (concat "\"" org-log-note-state "\"")
12617 ""))
12618 (cons "%S" (if org-log-note-previous-state
12619 (concat "\"" org-log-note-previous-state "\"")
12620 "\"\"")))))
12621 (if lines (setq note (concat note " \\\\")))
12622 (push note lines))
12623 (when (or current-prefix-arg org-note-abort)
12624 (when org-log-into-drawer
12625 (org-remove-empty-drawer-at
12626 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12627 org-log-note-marker))
12628 (setq lines nil))
12629 (when lines
12630 (with-current-buffer (marker-buffer org-log-note-marker)
12631 (save-excursion
12632 (goto-char org-log-note-marker)
12633 (move-marker org-log-note-marker nil)
12634 (end-of-line 1)
12635 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12636 (setq ind (save-excursion
12637 (if (ignore-errors (goto-char (org-in-item-p)))
12638 (let ((struct (org-list-struct)))
12639 (org-list-get-ind
12640 (org-list-get-top-point struct) struct))
12641 (skip-chars-backward " \r\t\n")
12642 (cond
12643 ((and (org-at-heading-p)
12644 org-adapt-indentation)
12645 (1+ (org-current-level)))
12646 ((org-at-heading-p) 0)
12647 (t (org-get-indentation))))))
12648 (setq bul (org-list-bullet-string "-"))
12649 (org-indent-line-to ind)
12650 (insert bul (pop lines))
12651 (let ((ind-body (+ (length bul) ind)))
12652 (while lines
12653 (insert "\n")
12654 (org-indent-line-to ind-body)
12655 (insert (pop lines))))
12656 (message "Note stored")
12657 (org-back-to-heading t)
12658 (org-cycle-hide-drawers 'children)))))
12659 (set-window-configuration org-log-note-window-configuration)
12660 (with-current-buffer (marker-buffer org-log-note-return-to)
12661 (goto-char org-log-note-return-to))
12662 (move-marker org-log-note-return-to nil)
12663 (and org-log-post-message (message "%s" org-log-post-message)))
12665 (defun org-remove-empty-drawer-at (drawer pos)
12666 "Remove an empty drawer DRAWER at position POS.
12667 POS may also be a marker."
12668 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12669 (save-excursion
12670 (save-restriction
12671 (widen)
12672 (goto-char pos)
12673 (if (org-in-regexp
12674 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12675 (replace-match ""))))))
12677 (defvar org-ts-type nil)
12678 (defun org-sparse-tree (&optional arg type)
12679 "Create a sparse tree, prompt for the details.
12680 This command can create sparse trees. You first need to select the type
12681 of match used to create the tree:
12683 t Show all TODO entries.
12684 T Show entries with a specific TODO keyword.
12685 m Show entries selected by a tags/property match.
12686 p Enter a property name and its value (both with completion on existing
12687 names/values) and show entries with that property.
12688 r Show entries matching a regular expression (`/' can be used as well).
12689 b Show deadlines and scheduled items before a date.
12690 a Show deadlines and scheduled items after a date.
12691 d Show deadlines due within `org-deadline-warning-days'.
12692 D Show deadlines and scheduled items between a date range."
12693 (interactive "P")
12694 (let (ans kwd value ts-type)
12695 (setq type (or type org-sparse-tree-default-date-type))
12696 (setq org-ts-type type)
12697 (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"
12698 (cond ((eq type 'all) "all timestamps")
12699 ((eq type 'scheduled) "only scheduled")
12700 ((eq type 'deadline) "only deadline")
12701 ((eq type 'active) "only active timestamps")
12702 ((eq type 'inactive) "only inactive timestamps")
12703 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12704 (t "scheduled/deadline")))
12705 (setq ans (read-char-exclusive))
12706 (cond
12707 ((equal ans ?c)
12708 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12709 ((equal ans ?d)
12710 (call-interactively 'org-check-deadlines))
12711 ((equal ans ?b)
12712 (call-interactively 'org-check-before-date))
12713 ((equal ans ?a)
12714 (call-interactively 'org-check-after-date))
12715 ((equal ans ?D)
12716 (call-interactively 'org-check-dates-range))
12717 ((equal ans ?t)
12718 (org-show-todo-tree nil))
12719 ((equal ans ?T)
12720 (org-show-todo-tree '(4)))
12721 ((member ans '(?T ?m))
12722 (call-interactively 'org-match-sparse-tree))
12723 ((member ans '(?p ?P))
12724 (setq kwd (org-icompleting-read "Property: "
12725 (mapcar 'list (org-buffer-property-keys))))
12726 (setq value (org-icompleting-read "Value: "
12727 (mapcar 'list (org-property-values kwd))))
12728 (unless (string-match "\\`{.*}\\'" value)
12729 (setq value (concat "\"" value "\"")))
12730 (org-match-sparse-tree arg (concat kwd "=" value)))
12731 ((member ans '(?r ?R ?/))
12732 (call-interactively 'org-occur))
12733 (t (error "No such sparse tree command \"%c\"" ans)))))
12735 (defvar org-occur-highlights nil
12736 "List of overlays used for occur matches.")
12737 (make-variable-buffer-local 'org-occur-highlights)
12738 (defvar org-occur-parameters nil
12739 "Parameters of the active org-occur calls.
12740 This is a list, each call to org-occur pushes as cons cell,
12741 containing the regular expression and the callback, onto the list.
12742 The list can contain several entries if `org-occur' has been called
12743 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12744 will only contain one set of parameters. When the highlights are
12745 removed (for example with `C-c C-c', or with the next edit (depending
12746 on `org-remove-highlights-with-change'), this variable is emptied
12747 as well.")
12748 (make-variable-buffer-local 'org-occur-parameters)
12750 (defun org-occur (regexp &optional keep-previous callback)
12751 "Make a compact tree which shows all matches of REGEXP.
12752 The tree will show the lines where the regexp matches, and all higher
12753 headlines above the match. It will also show the heading after the match,
12754 to make sure editing the matching entry is easy.
12755 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12756 call to `org-occur' will be kept, to allow stacking of calls to this
12757 command.
12758 If CALLBACK is non-nil, it is a function which is called to confirm
12759 that the match should indeed be shown."
12760 (interactive "sRegexp: \nP")
12761 (when (equal regexp "")
12762 (error "Regexp cannot be empty"))
12763 (unless keep-previous
12764 (org-remove-occur-highlights nil nil t))
12765 (push (cons regexp callback) org-occur-parameters)
12766 (let ((cnt 0))
12767 (save-excursion
12768 (goto-char (point-min))
12769 (if (or (not keep-previous) ; do not want to keep
12770 (not org-occur-highlights)) ; no previous matches
12771 ;; hide everything
12772 (org-overview))
12773 (while (re-search-forward regexp nil t)
12774 (when (or (not callback)
12775 (save-match-data (funcall callback)))
12776 (setq cnt (1+ cnt))
12777 (when org-highlight-sparse-tree-matches
12778 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12779 (org-show-context 'occur-tree))))
12780 (when org-remove-highlights-with-change
12781 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12782 nil 'local))
12783 (unless org-sparse-tree-open-archived-trees
12784 (org-hide-archived-subtrees (point-min) (point-max)))
12785 (run-hooks 'org-occur-hook)
12786 (if (org-called-interactively-p 'interactive)
12787 (message "%d match(es) for regexp %s" cnt regexp))
12788 cnt))
12790 (defun org-occur-next-match (&optional n reset)
12791 "Function for `next-error-function' to find sparse tree matches.
12792 N is the number of matches to move, when negative move backwards.
12793 RESET is entirely ignored - this function always goes back to the
12794 starting point when no match is found."
12795 (let* ((limit (if (< n 0) (point-min) (point-max)))
12796 (search-func (if (< n 0)
12797 'previous-single-char-property-change
12798 'next-single-char-property-change))
12799 (n (abs n))
12800 (pos (point))
12802 (catch 'exit
12803 (while (setq p1 (funcall search-func (point) 'org-type))
12804 (when (equal p1 limit)
12805 (goto-char pos)
12806 (error "No more matches"))
12807 (when (equal (get-char-property p1 'org-type) 'org-occur)
12808 (setq n (1- n))
12809 (when (= n 0)
12810 (goto-char p1)
12811 (throw 'exit (point))))
12812 (goto-char p1))
12813 (goto-char p1)
12814 (error "No more matches"))))
12816 (defun org-show-context (&optional key)
12817 "Make sure point and context are visible.
12818 How much context is shown depends upon the variables
12819 `org-show-hierarchy-above', `org-show-following-heading',
12820 `org-show-entry-below' and `org-show-siblings'."
12821 (let ((heading-p (org-at-heading-p t))
12822 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12823 (following-p (org-get-alist-option org-show-following-heading key))
12824 (entry-p (org-get-alist-option org-show-entry-below key))
12825 (siblings-p (org-get-alist-option org-show-siblings key)))
12826 (catch 'exit
12827 ;; Show heading or entry text
12828 (if (and heading-p (not entry-p))
12829 (org-flag-heading nil) ; only show the heading
12830 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12831 (org-show-hidden-entry))) ; show entire entry
12832 (when following-p
12833 ;; Show next sibling, or heading below text
12834 (save-excursion
12835 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12836 (org-flag-heading nil))))
12837 (when siblings-p (org-show-siblings))
12838 (when hierarchy-p
12839 ;; show all higher headings, possibly with siblings
12840 (save-excursion
12841 (while (and (condition-case nil
12842 (progn (org-up-heading-all 1) t)
12843 (error nil))
12844 (not (bobp)))
12845 (org-flag-heading nil)
12846 (when siblings-p (org-show-siblings))))))))
12848 (defvar org-reveal-start-hook nil
12849 "Hook run before revealing a location.")
12851 (defun org-reveal (&optional siblings)
12852 "Show current entry, hierarchy above it, and the following headline.
12853 This can be used to show a consistent set of context around locations
12854 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12855 not t for the search context.
12857 With optional argument SIBLINGS, on each level of the hierarchy all
12858 siblings are shown. This repairs the tree structure to what it would
12859 look like when opened with hierarchical calls to `org-cycle'.
12860 With double optional argument \\[universal-argument] \\[universal-argument], \
12861 go to the parent and show the
12862 entire tree."
12863 (interactive "P")
12864 (run-hooks 'org-reveal-start-hook)
12865 (let ((org-show-hierarchy-above t)
12866 (org-show-following-heading t)
12867 (org-show-siblings (if siblings t org-show-siblings)))
12868 (org-show-context nil))
12869 (when (equal siblings '(16))
12870 (save-excursion
12871 (when (org-up-heading-safe)
12872 (org-show-subtree)
12873 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12875 (defun org-highlight-new-match (beg end)
12876 "Highlight from BEG to END and mark the highlight is an occur headline."
12877 (let ((ov (make-overlay beg end)))
12878 (overlay-put ov 'face 'secondary-selection)
12879 (overlay-put ov 'org-type 'org-occur)
12880 (push ov org-occur-highlights)))
12882 (defun org-remove-occur-highlights (&optional beg end noremove)
12883 "Remove the occur highlights from the buffer.
12884 BEG and END are ignored. If NOREMOVE is nil, remove this function
12885 from the `before-change-functions' in the current buffer."
12886 (interactive)
12887 (unless org-inhibit-highlight-removal
12888 (mapc 'delete-overlay org-occur-highlights)
12889 (setq org-occur-highlights nil)
12890 (setq org-occur-parameters nil)
12891 (unless noremove
12892 (remove-hook 'before-change-functions
12893 'org-remove-occur-highlights 'local))))
12895 ;;;; Priorities
12897 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12898 "Regular expression matching the priority indicator.")
12900 (defvar org-remove-priority-next-time nil)
12902 (defun org-priority-up ()
12903 "Increase the priority of the current item."
12904 (interactive)
12905 (org-priority 'up))
12907 (defun org-priority-down ()
12908 "Decrease the priority of the current item."
12909 (interactive)
12910 (org-priority 'down))
12912 (defun org-priority (&optional action)
12913 "Change the priority of an item by ARG.
12914 ACTION can be `set', `up', `down', or a character."
12915 (interactive)
12916 (unless org-enable-priority-commands
12917 (error "Priority commands are disabled"))
12918 (setq action (or action 'set))
12919 (let (current new news have remove)
12920 (save-excursion
12921 (org-back-to-heading t)
12922 (if (looking-at org-priority-regexp)
12923 (setq current (string-to-char (match-string 2))
12924 have t))
12925 (cond
12926 ((eq action 'remove)
12927 (setq remove t new ?\ ))
12928 ((or (eq action 'set)
12929 (if (featurep 'xemacs) (characterp action) (integerp action)))
12930 (if (not (eq action 'set))
12931 (setq new action)
12932 (message "Priority %c-%c, SPC to remove: "
12933 org-highest-priority org-lowest-priority)
12934 (save-match-data
12935 (setq new (read-char-exclusive))))
12936 (if (and (= (upcase org-highest-priority) org-highest-priority)
12937 (= (upcase org-lowest-priority) org-lowest-priority))
12938 (setq new (upcase new)))
12939 (cond ((equal new ?\ ) (setq remove t))
12940 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12941 (error "Priority must be between `%c' and `%c'"
12942 org-highest-priority org-lowest-priority))))
12943 ((eq action 'up)
12944 (setq new (if have
12945 (1- current) ; normal cycling
12946 ;; last priority was empty
12947 (if (eq last-command this-command)
12948 org-lowest-priority ; wrap around empty to lowest
12949 ;; default
12950 (if org-priority-start-cycle-with-default
12951 org-default-priority
12952 (1- org-default-priority))))))
12953 ((eq action 'down)
12954 (setq new (if have
12955 (1+ current) ; normal cycling
12956 ;; last priority was empty
12957 (if (eq last-command this-command)
12958 org-highest-priority ; wrap around empty to highest
12959 ;; default
12960 (if org-priority-start-cycle-with-default
12961 org-default-priority
12962 (1+ org-default-priority))))))
12963 (t (error "Invalid action")))
12964 (if (or (< (upcase new) org-highest-priority)
12965 (> (upcase new) org-lowest-priority))
12966 (if (and (memq action '(up down))
12967 (not have) (not (eq last-command this-command)))
12968 ;; `new' is from default priority
12969 (error
12970 "The default can not be set, see `org-default-priority' why")
12971 ;; normal cycling: `new' is beyond highest/lowest priority
12972 ;; and is wrapped around to the empty priority
12973 (setq remove t)))
12974 (setq news (format "%c" new))
12975 (if have
12976 (if remove
12977 (replace-match "" t t nil 1)
12978 (replace-match news t t nil 2))
12979 (if remove
12980 (error "No priority cookie found in line")
12981 (let ((case-fold-search nil))
12982 (looking-at org-todo-line-regexp))
12983 (if (match-end 2)
12984 (progn
12985 (goto-char (match-end 2))
12986 (insert " [#" news "]"))
12987 (goto-char (match-beginning 3))
12988 (insert "[#" news "] "))))
12989 (org-preserve-lc (org-set-tags nil 'align)))
12990 (if remove
12991 (message "Priority removed")
12992 (message "Priority of current item set to %s" news))))
12994 (defun org-get-priority (s)
12995 "Find priority cookie and return priority."
12996 (if (functionp org-get-priority-function)
12997 (funcall org-get-priority-function)
12998 (save-match-data
12999 (if (not (string-match org-priority-regexp s))
13000 (* 1000 (- org-lowest-priority org-default-priority))
13001 (* 1000 (- org-lowest-priority
13002 (string-to-char (match-string 2 s))))))))
13004 ;;;; Tags
13006 (defvar org-agenda-archives-mode)
13007 (defvar org-map-continue-from nil
13008 "Position from where mapping should continue.
13009 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13011 (defvar org-scanner-tags nil
13012 "The current tag list while the tags scanner is running.")
13013 (defvar org-trust-scanner-tags nil
13014 "Should `org-get-tags-at' use the tags for the scanner.
13015 This is for internal dynamical scoping only.
13016 When this is non-nil, the function `org-get-tags-at' will return the value
13017 of `org-scanner-tags' instead of building the list by itself. This
13018 can lead to large speed-ups when the tags scanner is used in a file with
13019 many entries, and when the list of tags is retrieved, for example to
13020 obtain a list of properties. Building the tags list for each entry in such
13021 a file becomes an N^2 operation - but with this variable set, it scales
13022 as N.")
13024 (defun org-scan-tags (action matcher todo-only &optional start-level)
13025 "Scan headline tags with inheritance and produce output ACTION.
13027 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13028 or `agenda' to produce an entry list for an agenda view. It can also be
13029 a Lisp form or a function that should be called at each matched headline, in
13030 this case the return value is a list of all return values from these calls.
13032 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13033 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13034 only lines with a not-done TODO keyword are included in the output.
13035 This should be the same variable that was scoped into
13036 and set by `org-make-tags-matcher' when it constructed MATCHER.
13038 START-LEVEL can be a string with asterisks, reducing the scope to
13039 headlines matching this string."
13040 (require 'org-agenda)
13041 (let* ((re (concat "^"
13042 (if start-level
13043 ;; Get the correct level to match
13044 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13045 org-outline-regexp)
13046 " *\\(\\<\\("
13047 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13048 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13049 (props (list 'face 'default
13050 'done-face 'org-agenda-done
13051 'undone-face 'default
13052 'mouse-face 'highlight
13053 'org-not-done-regexp org-not-done-regexp
13054 'org-todo-regexp org-todo-regexp
13055 'org-complex-heading-regexp org-complex-heading-regexp
13056 'help-echo
13057 (format "mouse-2 or RET jump to org file %s"
13058 (abbreviate-file-name
13059 (or (buffer-file-name (buffer-base-buffer))
13060 (buffer-name (buffer-base-buffer)))))))
13061 (case-fold-search nil)
13062 (org-map-continue-from nil)
13063 lspos tags tags-list
13064 (tags-alist (list (cons 0 org-file-tags)))
13065 (llast 0) rtn rtn1 level category i txt
13066 todo marker entry priority)
13067 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13068 (setq action (list 'lambda nil action)))
13069 (save-excursion
13070 (goto-char (point-min))
13071 (when (eq action 'sparse-tree)
13072 (org-overview)
13073 (org-remove-occur-highlights))
13074 (while (re-search-forward re nil t)
13075 (setq org-map-continue-from nil)
13076 (catch :skip
13077 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13078 tags (if (match-end 4) (org-match-string-no-properties 4)))
13079 (goto-char (setq lspos (match-beginning 0)))
13080 (setq level (org-reduced-level (funcall outline-level))
13081 category (org-get-category))
13082 (setq i llast llast level)
13083 ;; remove tag lists from same and sublevels
13084 (while (>= i level)
13085 (when (setq entry (assoc i tags-alist))
13086 (setq tags-alist (delete entry tags-alist)))
13087 (setq i (1- i)))
13088 ;; add the next tags
13089 (when tags
13090 (setq tags (org-split-string tags ":")
13091 tags-alist
13092 (cons (cons level tags) tags-alist)))
13093 ;; compile tags for current headline
13094 (setq tags-list
13095 (if org-use-tag-inheritance
13096 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13097 tags)
13098 org-scanner-tags tags-list)
13099 (when org-use-tag-inheritance
13100 (setcdr (car tags-alist)
13101 (mapcar (lambda (x)
13102 (setq x (copy-sequence x))
13103 (org-add-prop-inherited x))
13104 (cdar tags-alist))))
13105 (when (and tags org-use-tag-inheritance
13106 (or (not (eq t org-use-tag-inheritance))
13107 org-tags-exclude-from-inheritance))
13108 ;; selective inheritance, remove uninherited ones
13109 (setcdr (car tags-alist)
13110 (org-remove-uninherited-tags (cdar tags-alist))))
13111 (when (and
13113 ;; eval matcher only when the todo condition is OK
13114 (and (or (not todo-only) (member todo org-not-done-keywords))
13115 (let ((case-fold-search t) (org-trust-scanner-tags t))
13116 (eval matcher)))
13118 ;; Call the skipper, but return t if it does not skip,
13119 ;; so that the `and' form continues evaluating
13120 (progn
13121 (unless (eq action 'sparse-tree) (org-agenda-skip))
13124 ;; Check if timestamps are deselecting this entry
13125 (or (not todo-only)
13126 (and (member todo org-not-done-keywords)
13127 (or (not org-agenda-tags-todo-honor-ignore-options)
13128 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13130 ;; Extra check for the archive tag
13131 ;; FIXME: Does the skipper already do this????
13133 (not (member org-archive-tag tags-list))
13134 ;; we have an archive tag, should we use this anyway?
13135 (or (not org-agenda-skip-archived-trees)
13136 (and (eq action 'agenda) org-agenda-archives-mode))))
13138 ;; select this headline
13140 (cond
13141 ((eq action 'sparse-tree)
13142 (and org-highlight-sparse-tree-matches
13143 (org-get-heading) (match-end 0)
13144 (org-highlight-new-match
13145 (match-beginning 1) (match-end 1)))
13146 (org-show-context 'tags-tree))
13147 ((eq action 'agenda)
13148 (setq txt (org-agenda-format-item
13150 (concat
13151 (if (eq org-tags-match-list-sublevels 'indented)
13152 (make-string (1- level) ?.) "")
13153 (org-get-heading))
13154 category
13155 tags-list)
13156 priority (org-get-priority txt))
13157 (goto-char lspos)
13158 (setq marker (org-agenda-new-marker))
13159 (org-add-props txt props
13160 'org-marker marker 'org-hd-marker marker 'org-category category
13161 'todo-state todo
13162 'priority priority 'type "tagsmatch")
13163 (push txt rtn))
13164 ((functionp action)
13165 (setq org-map-continue-from nil)
13166 (save-excursion
13167 (setq rtn1 (funcall action))
13168 (push rtn1 rtn)))
13169 (t (error "Invalid action")))
13171 ;; if we are to skip sublevels, jump to end of subtree
13172 (unless org-tags-match-list-sublevels
13173 (org-end-of-subtree t)
13174 (backward-char 1))))
13175 ;; Get the correct position from where to continue
13176 (if org-map-continue-from
13177 (goto-char org-map-continue-from)
13178 (and (= (point) lspos) (end-of-line 1)))))
13179 (when (and (eq action 'sparse-tree)
13180 (not org-sparse-tree-open-archived-trees))
13181 (org-hide-archived-subtrees (point-min) (point-max)))
13182 (nreverse rtn)))
13184 (defun org-remove-uninherited-tags (tags)
13185 "Remove all tags that are not inherited from the list TAGS."
13186 (cond
13187 ((eq org-use-tag-inheritance t)
13188 (if org-tags-exclude-from-inheritance
13189 (org-delete-all org-tags-exclude-from-inheritance tags)
13190 tags))
13191 ((not org-use-tag-inheritance) nil)
13192 ((stringp org-use-tag-inheritance)
13193 (delq nil (mapcar
13194 (lambda (x)
13195 (if (and (string-match org-use-tag-inheritance x)
13196 (not (member x org-tags-exclude-from-inheritance)))
13197 x nil))
13198 tags)))
13199 ((listp org-use-tag-inheritance)
13200 (delq nil (mapcar
13201 (lambda (x)
13202 (if (member x org-use-tag-inheritance) x nil))
13203 tags)))))
13205 (defun org-match-sparse-tree (&optional todo-only match)
13206 "Create a sparse tree according to tags string MATCH.
13207 MATCH can contain positive and negative selection of tags, like
13208 \"+WORK+URGENT-WITHBOSS\".
13209 If optional argument TODO-ONLY is non-nil, only select lines that are
13210 also TODO lines."
13211 (interactive "P")
13212 (org-prepare-agenda-buffers (list (current-buffer)))
13213 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13215 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13217 (defvar org-cached-props nil)
13218 (defun org-cached-entry-get (pom property)
13219 (if (or (eq t org-use-property-inheritance)
13220 (and (stringp org-use-property-inheritance)
13221 (string-match org-use-property-inheritance property))
13222 (and (listp org-use-property-inheritance)
13223 (member property org-use-property-inheritance)))
13224 ;; Caching is not possible, check it directly
13225 (org-entry-get pom property 'inherit)
13226 ;; Get all properties, so that we can do complicated checks easily
13227 (cdr (assoc property (or org-cached-props
13228 (setq org-cached-props
13229 (org-entry-properties pom)))))))
13231 (defun org-global-tags-completion-table (&optional files)
13232 "Return the list of all tags in all agenda buffer/files.
13233 Optional FILES argument is a list of files which can be used
13234 instead of the agenda files."
13235 (save-excursion
13236 (org-uniquify
13237 (delq nil
13238 (apply 'append
13239 (mapcar
13240 (lambda (file)
13241 (set-buffer (find-file-noselect file))
13242 (append (org-get-buffer-tags)
13243 (mapcar (lambda (x) (if (stringp (car-safe x))
13244 (list (car-safe x)) nil))
13245 org-tag-alist)))
13246 (if (and files (car files))
13247 files
13248 (org-agenda-files))))))))
13250 (defun org-make-tags-matcher (match)
13251 "Create the TAGS/TODO matcher form for the selection string MATCH.
13253 The variable `todo-only' is scoped dynamically into this function; it will be
13254 set to t if the matcher restricts matching to TODO entries,
13255 otherwise will not be touched.
13257 Returns a cons of the selection string MATCH and the constructed
13258 lisp form implementing the matcher. The matcher is to be
13259 evaluated at an Org entry, with point on the headline,
13260 and returns t if the entry matches the
13261 selection string MATCH. The returned lisp form references
13262 two variables with information about the entry, which must be
13263 bound around the form's evaluation: todo, the TODO keyword at the
13264 entry (or nil of none); and tags-list, the list of all tags at the
13265 entry including inherited ones. Additionally, the category
13266 of the entry (if any) must be specified as the text property
13267 'org-category on the headline.
13269 See also `org-scan-tags'.
13271 (declare (special todo-only))
13272 (unless (boundp 'todo-only)
13273 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13274 (unless match
13275 ;; Get a new match request, with completion
13276 (let ((org-last-tags-completion-table
13277 (org-global-tags-completion-table)))
13278 (setq match (org-completing-read-no-i
13279 "Match: " 'org-tags-completion-function nil nil nil
13280 'org-tags-history))))
13282 ;; Parse the string and create a lisp form
13283 (let ((match0 match)
13284 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13285 minus tag mm
13286 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13287 orterms term orlist re-p str-p level-p level-op time-p
13288 prop-p pn pv po gv rest)
13289 (if (string-match "/+" match)
13290 ;; match contains also a todo-matching request
13291 (progn
13292 (setq tagsmatch (substring match 0 (match-beginning 0))
13293 todomatch (substring match (match-end 0)))
13294 (if (string-match "^!" todomatch)
13295 (setq todo-only t todomatch (substring todomatch 1)))
13296 (if (string-match "^\\s-*$" todomatch)
13297 (setq todomatch nil)))
13298 ;; only matching tags
13299 (setq tagsmatch match todomatch nil))
13301 ;; Make the tags matcher
13302 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13303 (setq tagsmatcher t)
13304 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13305 (while (setq term (pop orterms))
13306 (while (and (equal (substring term -1) "\\") orterms)
13307 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13308 (while (string-match re term)
13309 (setq rest (substring term (match-end 0))
13310 minus (and (match-end 1)
13311 (equal (match-string 1 term) "-"))
13312 tag (save-match-data (replace-regexp-in-string
13313 "\\\\-" "-"
13314 (match-string 2 term)))
13315 re-p (equal (string-to-char tag) ?{)
13316 level-p (match-end 4)
13317 prop-p (match-end 5)
13318 mm (cond
13319 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13320 (level-p
13321 (setq level-op (org-op-to-function (match-string 3 term)))
13322 `(,level-op level ,(string-to-number
13323 (match-string 4 term))))
13324 (prop-p
13325 (setq pn (match-string 5 term)
13326 po (match-string 6 term)
13327 pv (match-string 7 term)
13328 re-p (equal (string-to-char pv) ?{)
13329 str-p (equal (string-to-char pv) ?\")
13330 time-p (save-match-data
13331 (string-match "^\"[[<].*[]>]\"$" pv))
13332 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13333 (if time-p (setq pv (org-matcher-time pv)))
13334 (setq po (org-op-to-function po (if time-p 'time str-p)))
13335 (cond
13336 ((equal pn "CATEGORY")
13337 (setq gv '(get-text-property (point) 'org-category)))
13338 ((equal pn "TODO")
13339 (setq gv 'todo))
13341 (setq gv `(org-cached-entry-get nil ,pn))))
13342 (if re-p
13343 (if (eq po 'org<>)
13344 `(not (string-match ,pv (or ,gv "")))
13345 `(string-match ,pv (or ,gv "")))
13346 (if str-p
13347 `(,po (or ,gv "") ,pv)
13348 `(,po (string-to-number (or ,gv ""))
13349 ,(string-to-number pv) ))))
13350 (t `(member ,tag tags-list)))
13351 mm (if minus (list 'not mm) mm)
13352 term rest)
13353 (push mm tagsmatcher))
13354 (push (if (> (length tagsmatcher) 1)
13355 (cons 'and tagsmatcher)
13356 (car tagsmatcher))
13357 orlist)
13358 (setq tagsmatcher nil))
13359 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13360 (setq tagsmatcher
13361 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13362 ;; Make the todo matcher
13363 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13364 (setq todomatcher t)
13365 (setq orterms (org-split-string todomatch "|") orlist nil)
13366 (while (setq term (pop orterms))
13367 (while (string-match re term)
13368 (setq minus (and (match-end 1)
13369 (equal (match-string 1 term) "-"))
13370 kwd (match-string 2 term)
13371 re-p (equal (string-to-char kwd) ?{)
13372 term (substring term (match-end 0))
13373 mm (if re-p
13374 `(string-match ,(substring kwd 1 -1) todo)
13375 (list 'equal 'todo kwd))
13376 mm (if minus (list 'not mm) mm))
13377 (push mm todomatcher))
13378 (push (if (> (length todomatcher) 1)
13379 (cons 'and todomatcher)
13380 (car todomatcher))
13381 orlist)
13382 (setq todomatcher nil))
13383 (setq todomatcher (if (> (length orlist) 1)
13384 (cons 'or orlist) (car orlist))))
13386 ;; Return the string and lisp forms of the matcher
13387 (setq matcher (if todomatcher
13388 (list 'and tagsmatcher todomatcher)
13389 tagsmatcher))
13390 (when todo-only
13391 (setq matcher (list 'and '(member todo org-not-done-keywords)
13392 matcher)))
13393 (cons match0 matcher)))
13395 (defun org-op-to-function (op &optional stringp)
13396 "Turn an operator into the appropriate function."
13397 (setq op
13398 (cond
13399 ((equal op "<" ) '(< string< org-time<))
13400 ((equal op ">" ) '(> org-string> org-time>))
13401 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13402 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13403 ((member op '("=" "==")) '(= string= org-time=))
13404 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13405 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13407 (defun org<> (a b) (not (= a b)))
13408 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13409 (defun org-string>= (a b) (not (string< a b)))
13410 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13411 (defun org-string<> (a b) (not (string= a b)))
13412 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13413 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13414 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13415 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13416 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13417 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13418 (defun org-2ft (s)
13419 "Convert S to a floating point time.
13420 If S is already a number, just return it. If it is a string, parse
13421 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13422 (cond
13423 ((numberp s) s)
13424 ((stringp s)
13425 (condition-case nil
13426 (float-time (apply 'encode-time (org-parse-time-string s)))
13427 (error 0.)))
13428 (t 0.)))
13430 (defun org-time-today ()
13431 "Time in seconds today at 0:00.
13432 Returns the float number of seconds since the beginning of the
13433 epoch to the beginning of today (00:00)."
13434 (float-time (apply 'encode-time
13435 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13437 (defun org-matcher-time (s)
13438 "Interpret a time comparison value."
13439 (save-match-data
13440 (cond
13441 ((string= s "<now>") (float-time))
13442 ((string= s "<today>") (org-time-today))
13443 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13444 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13445 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13446 (+ (org-time-today)
13447 (* (string-to-number (match-string 1 s))
13448 (cdr (assoc (match-string 2 s)
13449 '(("d" . 86400.0) ("w" . 604800.0)
13450 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13451 (t (org-2ft s)))))
13453 (defun org-match-any-p (re list)
13454 "Does re match any element of list?"
13455 (setq list (mapcar (lambda (x) (string-match re x)) list))
13456 (delq nil list))
13458 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13459 (defvar org-tags-overlay (make-overlay 1 1))
13460 (org-detach-overlay org-tags-overlay)
13462 (defun org-get-local-tags-at (&optional pos)
13463 "Get a list of tags defined in the current headline."
13464 (org-get-tags-at pos 'local))
13466 (defun org-get-local-tags ()
13467 "Get a list of tags defined in the current headline."
13468 (org-get-tags-at nil 'local))
13470 (defun org-get-tags-at (&optional pos local)
13471 "Get a list of all headline tags applicable at POS.
13472 POS defaults to point. If tags are inherited, the list contains
13473 the targets in the same sequence as the headlines appear, i.e.
13474 the tags of the current headline come last.
13475 When LOCAL is non-nil, only return tags from the current headline,
13476 ignore inherited ones."
13477 (interactive)
13478 (if (and org-trust-scanner-tags
13479 (or (not pos) (equal pos (point)))
13480 (not local))
13481 org-scanner-tags
13482 (let (tags ltags lastpos parent)
13483 (save-excursion
13484 (save-restriction
13485 (widen)
13486 (goto-char (or pos (point)))
13487 (save-match-data
13488 (catch 'done
13489 (condition-case nil
13490 (progn
13491 (org-back-to-heading t)
13492 (while (not (equal lastpos (point)))
13493 (setq lastpos (point))
13494 (when (looking-at
13495 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13496 (setq ltags (org-split-string
13497 (org-match-string-no-properties 1) ":"))
13498 (when parent
13499 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13500 (setq tags (append
13501 (if parent
13502 (org-remove-uninherited-tags ltags)
13503 ltags)
13504 tags)))
13505 (or org-use-tag-inheritance (throw 'done t))
13506 (if local (throw 'done t))
13507 (or (org-up-heading-safe) (error nil))
13508 (setq parent t)))
13509 (error nil)))))
13510 (if local
13511 tags
13512 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13514 (defun org-add-prop-inherited (s)
13515 (add-text-properties 0 (length s) '(inherited t) s)
13518 (defun org-toggle-tag (tag &optional onoff)
13519 "Toggle the tag TAG for the current line.
13520 If ONOFF is `on' or `off', don't toggle but set to this state."
13521 (let (res current)
13522 (save-excursion
13523 (org-back-to-heading t)
13524 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13525 (point-at-eol) t)
13526 (progn
13527 (setq current (match-string 1))
13528 (replace-match ""))
13529 (setq current ""))
13530 (setq current (nreverse (org-split-string current ":")))
13531 (cond
13532 ((eq onoff 'on)
13533 (setq res t)
13534 (or (member tag current) (push tag current)))
13535 ((eq onoff 'off)
13536 (or (not (member tag current)) (setq current (delete tag current))))
13537 (t (if (member tag current)
13538 (setq current (delete tag current))
13539 (setq res t)
13540 (push tag current))))
13541 (end-of-line 1)
13542 (if current
13543 (progn
13544 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13545 (org-set-tags nil t))
13546 (delete-horizontal-space))
13547 (run-hooks 'org-after-tags-change-hook))
13548 res))
13550 (defun org-align-tags-here (to-col)
13551 ;; Assumes that this is a headline
13552 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13553 (beginning-of-line 1)
13554 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13555 (< pos (match-beginning 2)))
13556 (progn
13557 (setq tags-l (- (match-end 2) (match-beginning 2)))
13558 (goto-char (match-beginning 1))
13559 (insert " ")
13560 (delete-region (point) (1+ (match-beginning 2)))
13561 (setq ncol (max (current-column)
13562 (1+ col)
13563 (if (> to-col 0)
13564 to-col
13565 (- (abs to-col) tags-l))))
13566 (setq p (point))
13567 (insert (make-string (- ncol (current-column)) ?\ ))
13568 (setq ncol (current-column))
13569 (when indent-tabs-mode (tabify p (point-at-eol)))
13570 (org-move-to-column (min ncol col) t))
13571 (goto-char pos))))
13573 (defun org-set-tags-command (&optional arg just-align)
13574 "Call the set-tags command for the current entry."
13575 (interactive "P")
13576 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13577 (org-set-tags arg just-align)
13578 (save-excursion
13579 (org-back-to-heading t)
13580 (org-set-tags arg just-align))))
13582 (defun org-set-tags-to (data)
13583 "Set the tags of the current entry to DATA, replacing the current tags.
13584 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13585 If DATA is nil or the empty string, any tags will be removed."
13586 (interactive "sTags: ")
13587 (setq data
13588 (cond
13589 ((eq data nil) "")
13590 ((equal data "") "")
13591 ((stringp data)
13592 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13593 ":"))
13594 ((listp data)
13595 (concat ":" (mapconcat 'identity data ":") ":"))
13596 (t nil)))
13597 (when data
13598 (save-excursion
13599 (org-back-to-heading t)
13600 (when (looking-at org-complex-heading-regexp)
13601 (if (match-end 5)
13602 (progn
13603 (goto-char (match-beginning 5))
13604 (insert data)
13605 (delete-region (point) (point-at-eol))
13606 (org-set-tags nil 'align))
13607 (goto-char (point-at-eol))
13608 (insert " " data)
13609 (org-set-tags nil 'align)))
13610 (beginning-of-line 1)
13611 (if (looking-at ".*?\\([ \t]+\\)$")
13612 (delete-region (match-beginning 1) (match-end 1))))))
13614 (defun org-align-all-tags ()
13615 "Align the tags i all headings."
13616 (interactive)
13617 (save-excursion
13618 (or (ignore-errors (org-back-to-heading t))
13619 (outline-next-heading))
13620 (if (org-at-heading-p)
13621 (org-set-tags t)
13622 (message "No headings"))))
13624 (defvar org-indent-indentation-per-level)
13625 (defun org-set-tags (&optional arg just-align)
13626 "Set the tags for the current headline.
13627 With prefix ARG, realign all tags in headings in the current buffer."
13628 (interactive "P")
13629 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13630 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13631 'region-start-level 'region))
13632 org-loop-over-headlines-in-active-region)
13633 (org-map-entries
13634 ;; We don't use ARG and JUST-ALIGN here these args are not
13635 ;; useful when looping over headlines
13636 `(org-set-tags)
13637 org-loop-over-headlines-in-active-region
13638 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13639 (let* ((re org-outline-regexp-bol)
13640 (current (unless arg (org-get-tags-string)))
13641 (col (current-column))
13642 (org-setting-tags t)
13643 table current-tags inherited-tags ; computed below when needed
13644 tags p0 c0 c1 rpl di tc level)
13645 (if arg
13646 (save-excursion
13647 (goto-char (point-min))
13648 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13649 (while (re-search-forward re nil t)
13650 (org-set-tags nil t)
13651 (end-of-line 1)))
13652 (message "All tags realigned to column %d" org-tags-column))
13653 (if just-align
13654 (setq tags current)
13655 ;; Get a new set of tags from the user
13656 (save-excursion
13657 (setq table (append org-tag-persistent-alist
13658 (or org-tag-alist (org-get-buffer-tags))
13659 (and
13660 org-complete-tags-always-offer-all-agenda-tags
13661 (org-global-tags-completion-table
13662 (org-agenda-files))))
13663 org-last-tags-completion-table table
13664 current-tags (org-split-string current ":")
13665 inherited-tags (nreverse
13666 (nthcdr (length current-tags)
13667 (nreverse (org-get-tags-at))))
13668 tags
13669 (if (or (eq t org-use-fast-tag-selection)
13670 (and org-use-fast-tag-selection
13671 (delq nil (mapcar 'cdr table))))
13672 (org-fast-tag-selection
13673 current-tags inherited-tags table
13674 (if org-fast-tag-selection-include-todo
13675 org-todo-key-alist))
13676 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13677 (org-trim
13678 (org-icompleting-read "Tags: "
13679 'org-tags-completion-function
13680 nil nil current 'org-tags-history))))))
13681 (while (string-match "[-+&]+" tags)
13682 ;; No boolean logic, just a list
13683 (setq tags (replace-match ":" t t tags))))
13685 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13687 (if org-tags-sort-function
13688 (setq tags (mapconcat 'identity
13689 (sort (org-split-string
13690 tags (org-re "[^[:alnum:]_@#%]+"))
13691 org-tags-sort-function) ":")))
13693 (if (string-match "\\`[\t ]*\\'" tags)
13694 (setq tags "")
13695 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13696 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13698 ;; Insert new tags at the correct column
13699 (beginning-of-line 1)
13700 (setq level (or (and (looking-at org-outline-regexp)
13701 (- (match-end 0) (point) 1))
13703 (cond
13704 ((and (equal current "") (equal tags "")))
13705 ((re-search-forward
13706 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13707 (point-at-eol) t)
13708 (if (equal tags "")
13709 (setq rpl "")
13710 (goto-char (match-beginning 0))
13711 (setq c0 (current-column)
13712 ;; compute offset for the case of org-indent-mode active
13713 di (if org-indent-mode
13714 (* (1- org-indent-indentation-per-level) (1- level))
13716 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13717 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13718 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13719 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13720 (replace-match rpl t t)
13721 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13722 tags)
13723 (t (error "Tags alignment failed")))
13724 (org-move-to-column col)
13725 (unless just-align
13726 (run-hooks 'org-after-tags-change-hook))))))
13728 (defun org-change-tag-in-region (beg end tag off)
13729 "Add or remove TAG for each entry in the region.
13730 This works in the agenda, and also in an org-mode buffer."
13731 (interactive
13732 (list (region-beginning) (region-end)
13733 (let ((org-last-tags-completion-table
13734 (if (derived-mode-p 'org-mode)
13735 (org-get-buffer-tags)
13736 (org-global-tags-completion-table))))
13737 (org-icompleting-read
13738 "Tag: " 'org-tags-completion-function nil nil nil
13739 'org-tags-history))
13740 (progn
13741 (message "[s]et or [r]emove? ")
13742 (equal (read-char-exclusive) ?r))))
13743 (if (fboundp 'deactivate-mark) (deactivate-mark))
13744 (let ((agendap (equal major-mode 'org-agenda-mode))
13745 l1 l2 m buf pos newhead (cnt 0))
13746 (goto-char end)
13747 (setq l2 (1- (org-current-line)))
13748 (goto-char beg)
13749 (setq l1 (org-current-line))
13750 (loop for l from l1 to l2 do
13751 (org-goto-line l)
13752 (setq m (get-text-property (point) 'org-hd-marker))
13753 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13754 (and agendap m))
13755 (setq buf (if agendap (marker-buffer m) (current-buffer))
13756 pos (if agendap m (point)))
13757 (with-current-buffer buf
13758 (save-excursion
13759 (save-restriction
13760 (goto-char pos)
13761 (setq cnt (1+ cnt))
13762 (org-toggle-tag tag (if off 'off 'on))
13763 (setq newhead (org-get-heading)))))
13764 (and agendap (org-agenda-change-all-lines newhead m))))
13765 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13767 (defun org-tags-completion-function (string predicate &optional flag)
13768 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13769 (confirm (lambda (x) (stringp (car x)))))
13770 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13771 (setq s1 (match-string 1 string)
13772 s2 (match-string 2 string))
13773 (setq s1 "" s2 string))
13774 (cond
13775 ((eq flag nil)
13776 ;; try completion
13777 (setq rtn (try-completion s2 ctable confirm))
13778 (if (stringp rtn)
13779 (setq rtn
13780 (concat s1 s2 (substring rtn (length s2))
13781 (if (and org-add-colon-after-tag-completion
13782 (assoc rtn ctable))
13783 ":" ""))))
13784 rtn)
13785 ((eq flag t)
13786 ;; all-completions
13787 (all-completions s2 ctable confirm)
13789 ((eq flag 'lambda)
13790 ;; exact match?
13791 (assoc s2 ctable)))
13794 (defun org-fast-tag-insert (kwd tags face &optional end)
13795 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13796 (insert (format "%-12s" (concat kwd ":"))
13797 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13798 (or end "")))
13800 (defun org-fast-tag-show-exit (flag)
13801 (save-excursion
13802 (org-goto-line 3)
13803 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13804 (replace-match ""))
13805 (when flag
13806 (end-of-line 1)
13807 (org-move-to-column (- (window-width) 19) t)
13808 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13810 (defun org-set-current-tags-overlay (current prefix)
13811 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13812 (if (featurep 'xemacs)
13813 (org-overlay-display org-tags-overlay (concat prefix s)
13814 'secondary-selection)
13815 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13816 (org-overlay-display org-tags-overlay (concat prefix s)))))
13818 (defvar org-last-tag-selection-key nil)
13819 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13820 "Fast tag selection with single keys.
13821 CURRENT is the current list of tags in the headline, INHERITED is the
13822 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13823 possibly with grouping information. TODO-TABLE is a similar table with
13824 TODO keywords, should these have keys assigned to them.
13825 If the keys are nil, a-z are automatically assigned.
13826 Returns the new tags string, or nil to not change the current settings."
13827 (let* ((fulltable (append table todo-table))
13828 (maxlen (apply 'max (mapcar
13829 (lambda (x)
13830 (if (stringp (car x)) (string-width (car x)) 0))
13831 fulltable)))
13832 (buf (current-buffer))
13833 (expert (eq org-fast-tag-selection-single-key 'expert))
13834 (buffer-tags nil)
13835 (fwidth (+ maxlen 3 1 3))
13836 (ncol (/ (- (window-width) 4) fwidth))
13837 (i-face 'org-done)
13838 (c-face 'org-todo)
13839 tg cnt e c char c1 c2 ntable tbl rtn
13840 ov-start ov-end ov-prefix
13841 (exit-after-next org-fast-tag-selection-single-key)
13842 (done-keywords org-done-keywords)
13843 groups ingroup)
13844 (save-excursion
13845 (beginning-of-line 1)
13846 (if (looking-at
13847 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13848 (setq ov-start (match-beginning 1)
13849 ov-end (match-end 1)
13850 ov-prefix "")
13851 (setq ov-start (1- (point-at-eol))
13852 ov-end (1+ ov-start))
13853 (skip-chars-forward "^\n\r")
13854 (setq ov-prefix
13855 (concat
13856 (buffer-substring (1- (point)) (point))
13857 (if (> (current-column) org-tags-column)
13859 (make-string (- org-tags-column (current-column)) ?\ ))))))
13860 (move-overlay org-tags-overlay ov-start ov-end)
13861 (save-window-excursion
13862 (if expert
13863 (set-buffer (get-buffer-create " *Org tags*"))
13864 (delete-other-windows)
13865 (split-window-vertically)
13866 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13867 (erase-buffer)
13868 (org-set-local 'org-done-keywords done-keywords)
13869 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13870 (org-fast-tag-insert "Current" current c-face "\n\n")
13871 (org-fast-tag-show-exit exit-after-next)
13872 (org-set-current-tags-overlay current ov-prefix)
13873 (setq tbl fulltable char ?a cnt 0)
13874 (while (setq e (pop tbl))
13875 (cond
13876 ((equal (car e) :startgroup)
13877 (push '() groups) (setq ingroup t)
13878 (when (not (= cnt 0))
13879 (setq cnt 0)
13880 (insert "\n"))
13881 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13882 ((equal (car e) :endgroup)
13883 (setq ingroup nil cnt 0)
13884 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13885 ((equal e '(:newline))
13886 (when (not (= cnt 0))
13887 (setq cnt 0)
13888 (insert "\n")
13889 (setq e (car tbl))
13890 (while (equal (car tbl) '(:newline))
13891 (insert "\n")
13892 (setq tbl (cdr tbl)))))
13894 (setq tg (copy-sequence (car e)) c2 nil)
13895 (if (cdr e)
13896 (setq c (cdr e))
13897 ;; automatically assign a character.
13898 (setq c1 (string-to-char
13899 (downcase (substring
13900 tg (if (= (string-to-char tg) ?@) 1 0)))))
13901 (if (or (rassoc c1 ntable) (rassoc c1 table))
13902 (while (or (rassoc char ntable) (rassoc char table))
13903 (setq char (1+ char)))
13904 (setq c2 c1))
13905 (setq c (or c2 char)))
13906 (if ingroup (push tg (car groups)))
13907 (setq tg (org-add-props tg nil 'face
13908 (cond
13909 ((not (assoc tg table))
13910 (org-get-todo-face tg))
13911 ((member tg current) c-face)
13912 ((member tg inherited) i-face)
13913 (t nil))))
13914 (if (and (= cnt 0) (not ingroup)) (insert " "))
13915 (insert "[" c "] " tg (make-string
13916 (- fwidth 4 (length tg)) ?\ ))
13917 (push (cons tg c) ntable)
13918 (when (= (setq cnt (1+ cnt)) ncol)
13919 (insert "\n")
13920 (if ingroup (insert " "))
13921 (setq cnt 0)))))
13922 (setq ntable (nreverse ntable))
13923 (insert "\n")
13924 (goto-char (point-min))
13925 (if (not expert) (org-fit-window-to-buffer))
13926 (setq rtn
13927 (catch 'exit
13928 (while t
13929 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13930 (if (not groups) "no " "")
13931 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13932 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13933 (setq org-last-tag-selection-key c)
13934 (cond
13935 ((= c ?\r) (throw 'exit t))
13936 ((= c ?!)
13937 (setq groups (not groups))
13938 (goto-char (point-min))
13939 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13940 ((= c ?\C-c)
13941 (if (not expert)
13942 (org-fast-tag-show-exit
13943 (setq exit-after-next (not exit-after-next)))
13944 (setq expert nil)
13945 (delete-other-windows)
13946 (set-window-buffer (split-window-vertically) " *Org tags*")
13947 (org-switch-to-buffer-other-window " *Org tags*")
13948 (org-fit-window-to-buffer)))
13949 ((or (= c ?\C-g)
13950 (and (= c ?q) (not (rassoc c ntable))))
13951 (org-detach-overlay org-tags-overlay)
13952 (setq quit-flag t))
13953 ((= c ?\ )
13954 (setq current nil)
13955 (if exit-after-next (setq exit-after-next 'now)))
13956 ((= c ?\t)
13957 (condition-case nil
13958 (setq tg (org-icompleting-read
13959 "Tag: "
13960 (or buffer-tags
13961 (with-current-buffer buf
13962 (org-get-buffer-tags)))))
13963 (quit (setq tg "")))
13964 (when (string-match "\\S-" tg)
13965 (add-to-list 'buffer-tags (list tg))
13966 (if (member tg current)
13967 (setq current (delete tg current))
13968 (push tg current)))
13969 (if exit-after-next (setq exit-after-next 'now)))
13970 ((setq e (rassoc c todo-table) tg (car e))
13971 (with-current-buffer buf
13972 (save-excursion (org-todo tg)))
13973 (if exit-after-next (setq exit-after-next 'now)))
13974 ((setq e (rassoc c ntable) tg (car e))
13975 (if (member tg current)
13976 (setq current (delete tg current))
13977 (loop for g in groups do
13978 (if (member tg g)
13979 (mapc (lambda (x)
13980 (setq current (delete x current)))
13981 g)))
13982 (push tg current))
13983 (if exit-after-next (setq exit-after-next 'now))))
13985 ;; Create a sorted list
13986 (setq current
13987 (sort current
13988 (lambda (a b)
13989 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13990 (if (eq exit-after-next 'now) (throw 'exit t))
13991 (goto-char (point-min))
13992 (beginning-of-line 2)
13993 (delete-region (point) (point-at-eol))
13994 (org-fast-tag-insert "Current" current c-face)
13995 (org-set-current-tags-overlay current ov-prefix)
13996 (while (re-search-forward
13997 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13998 (setq tg (match-string 1))
13999 (add-text-properties
14000 (match-beginning 1) (match-end 1)
14001 (list 'face
14002 (cond
14003 ((member tg current) c-face)
14004 ((member tg inherited) i-face)
14005 (t (get-text-property (match-beginning 1) 'face))))))
14006 (goto-char (point-min)))))
14007 (org-detach-overlay org-tags-overlay)
14008 (if rtn
14009 (mapconcat 'identity current ":")
14010 nil))))
14012 (defun org-get-tags-string ()
14013 "Get the TAGS string in the current headline."
14014 (unless (org-at-heading-p t)
14015 (error "Not on a heading"))
14016 (save-excursion
14017 (beginning-of-line 1)
14018 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14019 (org-match-string-no-properties 1)
14020 "")))
14022 (defun org-get-tags ()
14023 "Get the list of tags specified in the current headline."
14024 (org-split-string (org-get-tags-string) ":"))
14026 (defun org-get-buffer-tags ()
14027 "Get a table of all tags used in the buffer, for completion."
14028 (let (tags)
14029 (save-excursion
14030 (goto-char (point-min))
14031 (while (re-search-forward
14032 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14033 (when (equal (char-after (point-at-bol 0)) ?*)
14034 (mapc (lambda (x) (add-to-list 'tags x))
14035 (org-split-string (org-match-string-no-properties 1) ":")))))
14036 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14037 (mapcar 'list tags)))
14039 ;;;; The mapping API
14041 ;;;###autoload
14042 (defun org-map-entries (func &optional match scope &rest skip)
14043 "Call FUNC at each headline selected by MATCH in SCOPE.
14045 FUNC is a function or a lisp form. The function will be called without
14046 arguments, with the cursor positioned at the beginning of the headline.
14047 The return values of all calls to the function will be collected and
14048 returned as a list.
14050 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14051 does not need to preserve point. After evaluation, the cursor will be
14052 moved to the end of the line (presumably of the headline of the
14053 processed entry) and search continues from there. Under some
14054 circumstances, this may not produce the wanted results. For example,
14055 if you have removed (e.g. archived) the current (sub)tree it could
14056 mean that the next entry will be skipped entirely. In such cases, you
14057 can specify the position from where search should continue by making
14058 FUNC set the variable `org-map-continue-from' to the desired buffer
14059 position.
14061 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14062 Only headlines that are matched by this query will be considered during
14063 the iteration. When MATCH is nil or t, all headlines will be
14064 visited by the iteration.
14066 SCOPE determines the scope of this command. It can be any of:
14068 nil The current buffer, respecting the restriction if any
14069 tree The subtree started with the entry at point
14070 region The entries within the active region, if any
14071 region-start-level
14072 The entries within the active region, but only those at
14073 the same level than the first one.
14074 file The current buffer, without restriction
14075 file-with-archives
14076 The current buffer, and any archives associated with it
14077 agenda All agenda files
14078 agenda-with-archives
14079 All agenda files with any archive files associated with them
14080 \(file1 file2 ...)
14081 If this is a list, all files in the list will be scanned
14083 The remaining args are treated as settings for the skipping facilities of
14084 the scanner. The following items can be given here:
14086 archive skip trees with the archive tag.
14087 comment skip trees with the COMMENT keyword
14088 function or Emacs Lisp form:
14089 will be used as value for `org-agenda-skip-function', so whenever
14090 the function returns t, FUNC will not be called for that
14091 entry and search will continue from the point where the
14092 function leaves it.
14094 If your function needs to retrieve the tags including inherited tags
14095 at the *current* entry, you can use the value of the variable
14096 `org-scanner-tags' which will be much faster than getting the value
14097 with `org-get-tags-at'. If your function gets properties with
14098 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14099 to t around the call to `org-entry-properties' to get the same speedup.
14100 Note that if your function moves around to retrieve tags and properties at
14101 a *different* entry, you cannot use these techniques."
14102 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14103 (not (org-region-active-p)))
14104 (let* ((org-agenda-archives-mode nil) ; just to make sure
14105 (org-agenda-skip-archived-trees (memq 'archive skip))
14106 (org-agenda-skip-comment-trees (memq 'comment skip))
14107 (org-agenda-skip-function
14108 (car (org-delete-all '(comment archive) skip)))
14109 (org-tags-match-list-sublevels t)
14110 (start-level (eq scope 'region-start-level))
14111 matcher file res
14112 org-todo-keywords-for-agenda
14113 org-done-keywords-for-agenda
14114 org-todo-keyword-alist-for-agenda
14115 org-drawers-for-agenda
14116 org-tag-alist-for-agenda
14117 todo-only)
14119 (cond
14120 ((eq match t) (setq matcher t))
14121 ((eq match nil) (setq matcher t))
14122 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14124 (save-excursion
14125 (save-restriction
14126 (cond ((eq scope 'tree)
14127 (org-back-to-heading t)
14128 (org-narrow-to-subtree)
14129 (setq scope nil))
14130 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14131 (org-region-active-p))
14132 ;; If needed, set start-level to a string like "2"
14133 (when start-level
14134 (save-excursion
14135 (goto-char (region-beginning))
14136 (unless (org-at-heading-p) (outline-next-heading))
14137 (setq start-level (org-current-level))))
14138 (narrow-to-region (region-beginning)
14139 (save-excursion
14140 (goto-char (region-end))
14141 (unless (and (bolp) (org-at-heading-p))
14142 (outline-next-heading))
14143 (point)))
14144 (setq scope nil)))
14146 (if (not scope)
14147 (progn
14148 (org-prepare-agenda-buffers
14149 (list (buffer-file-name (current-buffer))))
14150 (setq res (org-scan-tags func matcher todo-only start-level)))
14151 ;; Get the right scope
14152 (cond
14153 ((and scope (listp scope) (symbolp (car scope)))
14154 (setq scope (eval scope)))
14155 ((eq scope 'agenda)
14156 (setq scope (org-agenda-files t)))
14157 ((eq scope 'agenda-with-archives)
14158 (setq scope (org-agenda-files t))
14159 (setq scope (org-add-archive-files scope)))
14160 ((eq scope 'file)
14161 (setq scope (list (buffer-file-name))))
14162 ((eq scope 'file-with-archives)
14163 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14164 (org-prepare-agenda-buffers scope)
14165 (while (setq file (pop scope))
14166 (with-current-buffer (org-find-base-buffer-visiting file)
14167 (save-excursion
14168 (save-restriction
14169 (widen)
14170 (goto-char (point-min))
14171 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14172 res)))
14174 ;;;; Properties
14176 ;;; Setting and retrieving properties
14178 (defconst org-special-properties
14179 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14180 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14181 "The special properties valid in Org-mode.
14183 These are properties that are not defined in the property drawer,
14184 but in some other way.")
14186 (defconst org-default-properties
14187 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14188 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14189 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14190 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14191 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14192 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14193 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14194 "Some properties that are used by Org-mode for various purposes.
14195 Being in this list makes sure that they are offered for completion.")
14197 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14198 "Regular expression matching the first line of a property drawer.")
14200 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14201 "Regular expression matching the last line of a property drawer.")
14203 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14204 "Regular expression matching the first line of a property drawer.")
14206 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14207 "Regular expression matching the first line of a property drawer.")
14209 (defconst org-property-drawer-re
14210 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14211 org-property-end-re "\\)\n?")
14212 "Matches an entire property drawer.")
14214 (defconst org-clock-drawer-re
14215 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14216 org-property-end-re "\\)\n?")
14217 "Matches an entire clock drawer.")
14219 (defsubst org-re-property (property)
14220 "Return a regexp matching a PROPERTY line.
14221 Match group 1 will be set to the value."
14222 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14224 (defsubst org-re-property-keyword (property)
14225 "Return a regexp matching a PROPERTY line, possibly with no
14226 value for the property."
14227 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14229 (defun org-property-action ()
14230 "Do an action on properties."
14231 (interactive)
14232 (let (c)
14233 (org-at-property-p)
14234 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14235 (setq c (read-char-exclusive))
14236 (cond
14237 ((equal c ?s)
14238 (call-interactively 'org-set-property))
14239 ((equal c ?d)
14240 (call-interactively 'org-delete-property))
14241 ((equal c ?D)
14242 (call-interactively 'org-delete-property-globally))
14243 ((equal c ?c)
14244 (call-interactively 'org-compute-property-at-point))
14245 (t (error "No such property action %c" c)))))
14247 (defun org-inc-effort ()
14248 "Increment the value of the effort property in the current entry."
14249 (interactive)
14250 (org-set-effort nil t))
14252 (defun org-set-effort (&optional value increment)
14253 "Set the effort property of the current entry.
14254 With numerical prefix arg, use the nth allowed value, 0 stands for the
14255 10th allowed value.
14257 When INCREMENT is non-nil, set the property to the next allowed value."
14258 (interactive "P")
14259 (if (equal value 0) (setq value 10))
14260 (let* ((completion-ignore-case t)
14261 (prop org-effort-property)
14262 (cur (org-entry-get nil prop))
14263 (allowed (org-property-get-allowed-values nil prop 'table))
14264 (existing (mapcar 'list (org-property-values prop)))
14266 (val (cond
14267 ((stringp value) value)
14268 ((and allowed (integerp value))
14269 (or (car (nth (1- value) allowed))
14270 (car (org-last allowed))))
14271 ((and allowed increment)
14272 (or (caadr (member (list cur) allowed))
14273 (error "Allowed effort values are not set")))
14274 (allowed
14275 (message "Select 1-9,0, [RET%s]: %s"
14276 (if cur (concat "=" cur) "")
14277 (mapconcat 'car allowed " "))
14278 (setq rpl (read-char-exclusive))
14279 (if (equal rpl ?\r)
14281 (setq rpl (- rpl ?0))
14282 (if (equal rpl 0) (setq rpl 10))
14283 (if (and (> rpl 0) (<= rpl (length allowed)))
14284 (car (nth (1- rpl) allowed))
14285 (org-completing-read "Effort: " allowed nil))))
14287 (let (org-completion-use-ido org-completion-use-iswitchb)
14288 (org-completing-read
14289 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14290 (concat "[" cur "]") "")
14291 ": ")
14292 existing nil nil "" nil cur))))))
14293 (unless (equal (org-entry-get nil prop) val)
14294 (org-entry-put nil prop val))
14295 (message "%s is now %s" prop val)))
14297 (defun org-at-property-p ()
14298 "Is cursor inside a property drawer?"
14299 (save-excursion
14300 (beginning-of-line 1)
14301 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14302 (save-match-data ;; Used by calling procedures
14303 (let ((p (point))
14304 (range (unless (org-before-first-heading-p)
14305 (org-get-property-block))))
14306 (and range (<= (car range) p) (< p (cdr range))))))))
14308 (defun org-get-property-block (&optional beg end force)
14309 "Return the (beg . end) range of the body of the property drawer.
14310 BEG and END are the beginning and end of the current subtree, or of
14311 the part before the first headline. If they are not given, they will
14312 be found. If the drawer does not exist and FORCE is non-nil, create
14313 the drawer."
14314 (catch 'exit
14315 (save-excursion
14316 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14317 (progn (org-back-to-heading t) (point))))
14318 (end (or end (and (not (outline-next-heading)) (point-max))
14319 (point))))
14320 (goto-char beg)
14321 (if (re-search-forward org-property-start-re end t)
14322 (setq beg (1+ (match-end 0)))
14323 (if force
14324 (save-excursion
14325 (org-insert-property-drawer)
14326 (setq end (progn (outline-next-heading) (point))))
14327 (throw 'exit nil))
14328 (goto-char beg)
14329 (if (re-search-forward org-property-start-re end t)
14330 (setq beg (1+ (match-end 0)))))
14331 (if (re-search-forward org-property-end-re end t)
14332 (setq end (match-beginning 0))
14333 (or force (throw 'exit nil))
14334 (goto-char beg)
14335 (setq end beg)
14336 (org-indent-line)
14337 (insert ":END:\n"))
14338 (cons beg end)))))
14340 (defun org-entry-properties (&optional pom which specific)
14341 "Get all properties of the entry at point-or-marker POM.
14342 This includes the TODO keyword, the tags, time strings for deadline,
14343 scheduled, and clocking, and any additional properties defined in the
14344 entry. The return value is an alist, keys may occur multiple times
14345 if the property key was used several times.
14346 POM may also be nil, in which case the current entry is used.
14347 If WHICH is nil or `all', get all properties. If WHICH is
14348 `special' or `standard', only get that subclass. If WHICH
14349 is a string only get exactly this property. SPECIFIC can be a string, the
14350 specific property we are interested in. Specifying it can speed
14351 things up because then unnecessary parsing is avoided."
14352 (setq which (or which 'all))
14353 (org-with-point-at pom
14354 (let ((clockstr (substring org-clock-string 0 -1))
14355 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14356 (case-fold-search nil)
14357 beg end range props sum-props key key1 value string clocksum clocksumt)
14358 (save-excursion
14359 (when (condition-case nil
14360 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14361 (error nil))
14362 (setq beg (point))
14363 (setq sum-props (get-text-property (point) 'org-summaries))
14364 (setq clocksum (get-text-property (point) :org-clock-minutes)
14365 clocksumt (get-text-property (point) :org-clock-minutes-today))
14366 (outline-next-heading)
14367 (setq end (point))
14368 (when (memq which '(all special))
14369 ;; Get the special properties, like TODO and tags
14370 (goto-char beg)
14371 (when (and (or (not specific) (string= specific "TODO"))
14372 (looking-at org-todo-line-regexp) (match-end 2))
14373 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14374 (when (and (or (not specific) (string= specific "PRIORITY"))
14375 (looking-at org-priority-regexp))
14376 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14377 (when (or (not specific) (string= specific "FILE"))
14378 (push (cons "FILE" buffer-file-name) props))
14379 (when (and (or (not specific) (string= specific "TAGS"))
14380 (setq value (org-get-tags-string))
14381 (string-match "\\S-" value))
14382 (push (cons "TAGS" value) props))
14383 (when (and (or (not specific) (string= specific "ALLTAGS"))
14384 (setq value (org-get-tags-at)))
14385 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14386 ":"))
14387 props))
14388 (when (or (not specific) (string= specific "BLOCKED"))
14389 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14390 (when (or (not specific)
14391 (member specific
14392 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14393 "TIMESTAMP" "TIMESTAMP_IA")))
14394 (catch 'match
14395 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14396 (setq key (if (match-end 1)
14397 (substring (org-match-string-no-properties 1)
14398 0 -1))
14399 string (if (equal key clockstr)
14400 (org-no-properties
14401 (org-trim
14402 (buffer-substring
14403 (match-beginning 3) (goto-char
14404 (point-at-eol)))))
14405 (substring (org-match-string-no-properties 3)
14406 1 -1)))
14407 ;; Get the correct property name from the key. This is
14408 ;; necessary if the user has configured time keywords.
14409 (setq key1 (concat key ":"))
14410 (cond
14411 ((not key)
14412 (setq key
14413 (if (= (char-after (match-beginning 3)) ?\[)
14414 "TIMESTAMP_IA" "TIMESTAMP")))
14415 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14416 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14417 ((equal key1 org-closed-string) (setq key "CLOSED"))
14418 ((equal key1 org-clock-string) (setq key "CLOCK")))
14419 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14420 (progn
14421 (push (cons key string) props)
14422 ;; no need to search further if match is found
14423 (throw 'match t))
14424 (when (or (equal key "CLOCK") (not (assoc key props)))
14425 (push (cons key string) props)))))))
14427 (when (memq which '(all standard))
14428 ;; Get the standard properties, like :PROP: ...
14429 (setq range (org-get-property-block beg end))
14430 (when range
14431 (goto-char (car range))
14432 (while (re-search-forward
14433 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14434 (cdr range) t)
14435 (setq key (org-match-string-no-properties 1)
14436 value (org-trim (or (org-match-string-no-properties 2) "")))
14437 (unless (member key excluded)
14438 (push (cons key (or value "")) props)))))
14439 (if clocksum
14440 (push (cons "CLOCKSUM"
14441 (org-columns-number-to-string (/ (float clocksum) 60.)
14442 'add_times))
14443 props))
14444 (if clocksumt
14445 (push (cons "CLOCKSUM_T"
14446 (org-columns-number-to-string (/ (float clocksumt) 60.)
14447 'add_times))
14448 props))
14449 (unless (assoc "CATEGORY" props)
14450 (push (cons "CATEGORY" (org-get-category)) props))
14451 (append sum-props (nreverse props)))))))
14453 (defun org-entry-get (pom property &optional inherit literal-nil)
14454 "Get value of PROPERTY for entry or content at point-or-marker POM.
14455 If INHERIT is non-nil and the entry does not have the property,
14456 then also check higher levels of the hierarchy.
14457 If INHERIT is the symbol `selective', use inheritance only if the setting
14458 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14459 If the property is present but empty, the return value is the empty string.
14460 If the property is not present at all, nil is returned.
14462 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14463 do not interpret it as the list atom nil. This is used for inheritance
14464 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14465 (org-with-point-at pom
14466 (if (and inherit (if (eq inherit 'selective)
14467 (org-property-inherit-p property)
14469 (org-entry-get-with-inheritance property literal-nil)
14470 (if (member property org-special-properties)
14471 ;; We need a special property. Use `org-entry-properties' to
14472 ;; retrieve it, but specify the wanted property
14473 (cdr (assoc property (org-entry-properties nil 'special property)))
14474 (let* ((range (org-get-property-block))
14475 (props (list (or (assoc property org-file-properties)
14476 (assoc property org-global-properties)
14477 (assoc property org-global-properties-fixed))))
14478 (ap (lambda (key)
14479 (when (re-search-forward
14480 (org-re-property key) (cdr range) t)
14481 (setq props
14482 (org-update-property-plist
14484 (if (match-end 1)
14485 (org-match-string-no-properties 1) "")
14486 props)))))
14487 val)
14488 (when (and range (goto-char (car range)))
14489 (funcall ap property)
14490 (goto-char (car range))
14491 (while (funcall ap (concat property "+")))
14492 (setq val (cdr (assoc property props)))
14493 (when val (if literal-nil val (org-not-nil val)))))))))
14495 (defun org-property-or-variable-value (var &optional inherit)
14496 "Check if there is a property fixing the value of VAR.
14497 If yes, return this value. If not, return the current value of the variable."
14498 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14499 (if (and prop (stringp prop) (string-match "\\S-" prop))
14500 (read prop)
14501 (symbol-value var))))
14503 (defun org-entry-delete (pom property)
14504 "Delete the property PROPERTY from entry at point-or-marker POM."
14505 (org-with-point-at pom
14506 (if (member property org-special-properties)
14507 nil ; cannot delete these properties.
14508 (let ((range (org-get-property-block)))
14509 (if (and range
14510 (goto-char (car range))
14511 (re-search-forward
14512 (org-re-property property)
14513 (cdr range) t))
14514 (progn
14515 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14517 nil)))))
14519 ;; Multi-values properties are properties that contain multiple values
14520 ;; These values are assumed to be single words, separated by whitespace.
14521 (defun org-entry-add-to-multivalued-property (pom property value)
14522 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14523 (let* ((old (org-entry-get pom property))
14524 (values (and old (org-split-string old "[ \t]"))))
14525 (setq value (org-entry-protect-space value))
14526 (unless (member value values)
14527 (setq values (cons value values))
14528 (org-entry-put pom property
14529 (mapconcat 'identity values " ")))))
14531 (defun org-entry-remove-from-multivalued-property (pom property value)
14532 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14533 (let* ((old (org-entry-get pom property))
14534 (values (and old (org-split-string old "[ \t]"))))
14535 (setq value (org-entry-protect-space value))
14536 (when (member value values)
14537 (setq values (delete value values))
14538 (org-entry-put pom property
14539 (mapconcat 'identity values " ")))))
14541 (defun org-entry-member-in-multivalued-property (pom property value)
14542 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14543 (let* ((old (org-entry-get pom property))
14544 (values (and old (org-split-string old "[ \t]"))))
14545 (setq value (org-entry-protect-space value))
14546 (member value values)))
14548 (defun org-entry-get-multivalued-property (pom property)
14549 "Return a list of values in a multivalued property."
14550 (let* ((value (org-entry-get pom property))
14551 (values (and value (org-split-string value "[ \t]"))))
14552 (mapcar 'org-entry-restore-space values)))
14554 (defun org-entry-put-multivalued-property (pom property &rest values)
14555 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14556 VALUES should be a list of strings. Spaces will be protected."
14557 (org-entry-put pom property
14558 (mapconcat 'org-entry-protect-space values " "))
14559 (let* ((value (org-entry-get pom property))
14560 (values (and value (org-split-string value "[ \t]"))))
14561 (mapcar 'org-entry-restore-space values)))
14563 (defun org-entry-protect-space (s)
14564 "Protect spaces and newline in string S."
14565 (while (string-match " " s)
14566 (setq s (replace-match "%20" t t s)))
14567 (while (string-match "\n" s)
14568 (setq s (replace-match "%0A" t t s)))
14571 (defun org-entry-restore-space (s)
14572 "Restore spaces and newline in string S."
14573 (while (string-match "%20" s)
14574 (setq s (replace-match " " t t s)))
14575 (while (string-match "%0A" s)
14576 (setq s (replace-match "\n" t t s)))
14579 (defvar org-entry-property-inherited-from (make-marker)
14580 "Marker pointing to the entry from where a property was inherited.
14581 Each call to `org-entry-get-with-inheritance' will set this marker to the
14582 location of the entry where the inheritance search matched. If there was
14583 no match, the marker will point nowhere.
14584 Note that also `org-entry-get' calls this function, if the INHERIT flag
14585 is set.")
14587 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14588 "Get PROPERTY of entry or content at point, search higher levels if needed.
14589 The search will stop at the first ancestor which has the property defined.
14590 If the value found is \"nil\", return nil to show that the property
14591 should be considered as undefined (this is the meaning of nil here).
14592 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14593 (move-marker org-entry-property-inherited-from nil)
14594 (let (tmp)
14595 (save-excursion
14596 (save-restriction
14597 (widen)
14598 (catch 'ex
14599 (while t
14600 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14601 (or (ignore-errors (org-back-to-heading t))
14602 (goto-char (point-min)))
14603 (move-marker org-entry-property-inherited-from (point))
14604 (throw 'ex tmp))
14605 (or (ignore-errors (org-up-heading-safe))
14606 (throw 'ex nil))))))
14607 (setq tmp (or tmp
14608 (cdr (assoc property org-file-properties))
14609 (cdr (assoc property org-global-properties))
14610 (cdr (assoc property org-global-properties-fixed))))
14611 (if literal-nil tmp (org-not-nil tmp))))
14613 (defvar org-property-changed-functions nil
14614 "Hook called when the value of a property has changed.
14615 Each hook function should accept two arguments, the name of the property
14616 and the new value.")
14618 (defun org-entry-put (pom property value)
14619 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14620 (org-with-point-at pom
14621 (org-back-to-heading t)
14622 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14623 range)
14624 (cond
14625 ((equal property "TODO")
14626 (when (and (stringp value) (string-match "\\S-" value)
14627 (not (member value org-todo-keywords-1)))
14628 (error "\"%s\" is not a valid TODO state" value))
14629 (if (or (not value)
14630 (not (string-match "\\S-" value)))
14631 (setq value 'none))
14632 (org-todo value)
14633 (org-set-tags nil 'align))
14634 ((equal property "PRIORITY")
14635 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14636 (string-to-char value) ?\ ))
14637 (org-set-tags nil 'align))
14638 ((equal property "SCHEDULED")
14639 (if (re-search-forward org-scheduled-time-regexp end t)
14640 (cond
14641 ((eq value 'earlier) (org-timestamp-change -1 'day))
14642 ((eq value 'later) (org-timestamp-change 1 'day))
14643 (t (call-interactively 'org-schedule)))
14644 (call-interactively 'org-schedule)))
14645 ((equal property "DEADLINE")
14646 (if (re-search-forward org-deadline-time-regexp end t)
14647 (cond
14648 ((eq value 'earlier) (org-timestamp-change -1 'day))
14649 ((eq value 'later) (org-timestamp-change 1 'day))
14650 (t (call-interactively 'org-deadline)))
14651 (call-interactively 'org-deadline)))
14652 ((member property org-special-properties)
14653 (error "The %s property can not yet be set with `org-entry-put'"
14654 property))
14655 (t ; a non-special property
14656 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14657 (setq range (org-get-property-block beg end 'force))
14658 (goto-char (car range))
14659 (if (re-search-forward
14660 (org-re-property-keyword property) (cdr range) t)
14661 (progn
14662 (delete-region (match-beginning 0) (match-end 0))
14663 (goto-char (match-beginning 0)))
14664 (goto-char (cdr range))
14665 (insert "\n")
14666 (backward-char 1)
14667 (org-indent-line))
14668 (insert ":" property ":")
14669 (and value (insert " " value))
14670 (org-indent-line)))))
14671 (run-hook-with-args 'org-property-changed-functions property value)))
14673 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14674 "Get all property keys in the current buffer.
14675 With INCLUDE-SPECIALS, also list the special properties that reflect things
14676 like tags and TODO state.
14677 With INCLUDE-DEFAULTS, also include properties that has special meaning
14678 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14679 and others.
14680 With INCLUDE-COLUMNS, also include property names given in COLUMN
14681 formats in the current buffer."
14682 (let (rtn range cfmt s p)
14683 (save-excursion
14684 (save-restriction
14685 (widen)
14686 (goto-char (point-min))
14687 (while (re-search-forward org-property-start-re nil t)
14688 (setq range (org-get-property-block))
14689 (goto-char (car range))
14690 (while (re-search-forward
14691 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14692 (cdr range) t)
14693 (add-to-list 'rtn (org-match-string-no-properties 1)))
14694 (outline-next-heading))))
14696 (when include-specials
14697 (setq rtn (append org-special-properties rtn)))
14699 (when include-defaults
14700 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14701 (add-to-list 'rtn org-effort-property))
14703 (when include-columns
14704 (save-excursion
14705 (save-restriction
14706 (widen)
14707 (goto-char (point-min))
14708 (while (re-search-forward
14709 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14710 nil t)
14711 (setq cfmt (match-string 2) s 0)
14712 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14713 cfmt s)
14714 (setq s (match-end 0)
14715 p (match-string 1 cfmt))
14716 (unless (or (equal p "ITEM")
14717 (member p org-special-properties))
14718 (add-to-list 'rtn (match-string 1 cfmt))))))))
14720 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14722 (defun org-property-values (key)
14723 "Return a list of all values of property KEY in the current buffer."
14724 (save-excursion
14725 (save-restriction
14726 (widen)
14727 (goto-char (point-min))
14728 (let ((re (org-re-property key))
14729 values)
14730 (while (re-search-forward re nil t)
14731 (add-to-list 'values (org-trim (match-string 1))))
14732 (delete "" values)))))
14734 (defun org-insert-property-drawer ()
14735 "Insert a property drawer into the current entry."
14736 (org-back-to-heading t)
14737 (looking-at org-outline-regexp)
14738 (let ((indent (if org-adapt-indentation
14739 (- (match-end 0) (match-beginning 0))
14741 (beg (point))
14742 (re (concat "^[ \t]*" org-keyword-time-regexp))
14743 end hiddenp)
14744 (outline-next-heading)
14745 (setq end (point))
14746 (goto-char beg)
14747 (while (re-search-forward re end t))
14748 (setq hiddenp (outline-invisible-p))
14749 (end-of-line 1)
14750 (and (equal (char-after) ?\n) (forward-char 1))
14751 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14752 (if (member (match-string 1) '("CLOCK:" ":END:"))
14753 ;; just skip this line
14754 (beginning-of-line 2)
14755 ;; Drawer start, find the end
14756 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14757 (beginning-of-line 1)))
14758 (org-skip-over-state-notes)
14759 (skip-chars-backward " \t\n\r")
14760 (if (eq (char-before) ?*) (forward-char 1))
14761 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14762 (beginning-of-line 0)
14763 (org-indent-to-column indent)
14764 (beginning-of-line 2)
14765 (org-indent-to-column indent)
14766 (beginning-of-line 0)
14767 (if hiddenp
14768 (save-excursion
14769 (org-back-to-heading t)
14770 (hide-entry))
14771 (org-flag-drawer t))))
14773 (defun org-insert-drawer (&optional arg drawer)
14774 "Insert a drawer at point.
14776 Optional argument DRAWER, when non-nil, is a string representing
14777 drawer's name. Otherwise, the user is prompted for a name.
14779 If a region is active, insert the drawer around that region
14780 instead.
14782 Point is left between drawer's boundaries."
14783 (interactive "P")
14784 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14785 "LOGBOOK"))
14786 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14787 ;; internally by Org. They are meant to be inserted
14788 ;; automatically.
14789 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14790 ;; Remove system drawers from list. Note: For some reason,
14791 ;; `org-completing-read' ignores the predicate while
14792 ;; `completing-read' handles it fine.
14793 (drawer (if arg "PROPERTIES"
14794 (or drawer
14795 (completing-read
14796 "Drawer: " org-drawers
14797 (lambda (d) (not (member d system-drawers))))))))
14798 (cond
14799 ;; With C-u, fall back on `org-insert-property-drawer'
14800 (arg (org-insert-property-drawer))
14801 ;; With an active region, insert a drawer at point.
14802 ((not (org-region-active-p))
14803 (progn
14804 (unless (bolp) (insert "\n"))
14805 (insert (format ":%s:\n\n:END:\n" drawer))
14806 (forward-line -2)))
14807 ;; Otherwise, insert the drawer at point
14809 (let ((rbeg (region-beginning))
14810 (rend (copy-marker (region-end))))
14811 (unwind-protect
14812 (progn
14813 (goto-char rbeg)
14814 (beginning-of-line)
14815 (when (save-excursion
14816 (re-search-forward org-outline-regexp-bol rend t))
14817 (error "Drawers cannot contain headlines"))
14818 ;; Position point at the beginning of the first
14819 ;; non-blank line in region. Insert drawer's opening
14820 ;; there, then indent it.
14821 (org-skip-whitespace)
14822 (beginning-of-line)
14823 (insert ":" drawer ":\n")
14824 (forward-line -1)
14825 (indent-for-tab-command)
14826 ;; Move point to the beginning of the first blank line
14827 ;; after the last non-blank line in region. Insert
14828 ;; drawer's closing, then indent it.
14829 (goto-char rend)
14830 (skip-chars-backward " \r\t\n")
14831 (insert "\n:END:")
14832 (indent-for-tab-command)
14833 (unless (eolp) (insert "\n")))
14834 ;; Clear marker, whatever the outcome of insertion is.
14835 (set-marker rend nil)))))))
14837 (defvar org-property-set-functions-alist nil
14838 "Property set function alist.
14839 Each entry should have the following format:
14841 (PROPERTY . READ-FUNCTION)
14843 The read function will be called with the same argument as
14844 `org-completing-read'.")
14846 (defun org-set-property-function (property)
14847 "Get the function that should be used to set PROPERTY.
14848 This is computed according to `org-property-set-functions-alist'."
14849 (or (cdr (assoc property org-property-set-functions-alist))
14850 'org-completing-read))
14852 (defun org-read-property-value (property)
14853 "Read PROPERTY value from user."
14854 (let* ((completion-ignore-case t)
14855 (allowed (org-property-get-allowed-values nil property 'table))
14856 (cur (org-entry-get nil property))
14857 (prompt (concat property " value"
14858 (if (and cur (string-match "\\S-" cur))
14859 (concat " [" cur "]") "") ": "))
14860 (set-function (org-set-property-function property))
14861 (val (if allowed
14862 (funcall set-function prompt allowed nil
14863 (not (get-text-property 0 'org-unrestricted
14864 (caar allowed))))
14865 (let (org-completion-use-ido org-completion-use-iswitchb)
14866 (funcall set-function prompt
14867 (mapcar 'list (org-property-values property))
14868 nil nil "" nil cur)))))
14869 (if (equal val "")
14871 val)))
14873 (defvar org-last-set-property nil)
14874 (defun org-read-property-name ()
14875 "Read a property name."
14876 (let* ((completion-ignore-case t)
14877 (keys (org-buffer-property-keys nil t t))
14878 (default-prop (or (save-excursion
14879 (save-match-data
14880 (beginning-of-line)
14881 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14882 (null (string= (match-string 1) "END"))
14883 (match-string 1))))
14884 org-last-set-property))
14885 (property (org-icompleting-read
14886 (concat "Property"
14887 (if default-prop (concat " [" default-prop "]") "")
14888 ": ")
14889 (mapcar 'list keys)
14890 nil nil nil nil
14891 default-prop
14893 (if (member property keys)
14894 property
14895 (or (cdr (assoc (downcase property)
14896 (mapcar (lambda (x) (cons (downcase x) x))
14897 keys)))
14898 property))))
14900 (defun org-set-property (property value)
14901 "In the current entry, set PROPERTY to VALUE.
14902 When called interactively, this will prompt for a property name, offering
14903 completion on existing and default properties. And then it will prompt
14904 for a value, offering completion either on allowed values (via an inherited
14905 xxx_ALL property) or on existing values in other instances of this property
14906 in the current file."
14907 (interactive (list nil nil))
14908 (let* ((property (or property (org-read-property-name)))
14909 (value (or value (org-read-property-value property)))
14910 (fn (cdr (assoc property org-properties-postprocess-alist))))
14911 (setq org-last-set-property property)
14912 ;; Possibly postprocess the inserted value:
14913 (when fn (setq value (funcall fn value)))
14914 (unless (equal (org-entry-get nil property) value)
14915 (org-entry-put nil property value))))
14917 (defun org-delete-property (property)
14918 "In the current entry, delete PROPERTY."
14919 (interactive
14920 (let* ((completion-ignore-case t)
14921 (prop (org-icompleting-read "Property: "
14922 (org-entry-properties nil 'standard))))
14923 (list prop)))
14924 (message "Property %s %s" property
14925 (if (org-entry-delete nil property)
14926 "deleted"
14927 "was not present in the entry")))
14929 (defun org-delete-property-globally (property)
14930 "Remove PROPERTY globally, from all entries."
14931 (interactive
14932 (let* ((completion-ignore-case t)
14933 (prop (org-icompleting-read
14934 "Globally remove property: "
14935 (mapcar 'list (org-buffer-property-keys)))))
14936 (list prop)))
14937 (save-excursion
14938 (save-restriction
14939 (widen)
14940 (goto-char (point-min))
14941 (let ((cnt 0))
14942 (while (re-search-forward
14943 (org-re-property property)
14944 nil t)
14945 (setq cnt (1+ cnt))
14946 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14947 (message "Property \"%s\" removed from %d entries" property cnt)))))
14949 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14951 (defun org-compute-property-at-point ()
14952 "Compute the property at point.
14953 This looks for an enclosing column format, extracts the operator and
14954 then applies it to the property in the column format's scope."
14955 (interactive)
14956 (unless (org-at-property-p)
14957 (error "Not at a property"))
14958 (let ((prop (org-match-string-no-properties 2)))
14959 (org-columns-get-format-and-top-level)
14960 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14961 (error "No operator defined for property %s" prop))
14962 (org-columns-compute prop)))
14964 (defvar org-property-allowed-value-functions nil
14965 "Hook for functions supplying allowed values for a specific property.
14966 The functions must take a single argument, the name of the property, and
14967 return a flat list of allowed values. If \":ETC\" is one of
14968 the values, this means that these values are intended as defaults for
14969 completion, but that other values should be allowed too.
14970 The functions must return nil if they are not responsible for this
14971 property.")
14973 (defun org-property-get-allowed-values (pom property &optional table)
14974 "Get allowed values for the property PROPERTY.
14975 When TABLE is non-nil, return an alist that can directly be used for
14976 completion."
14977 (let (vals)
14978 (cond
14979 ((equal property "TODO")
14980 (setq vals (org-with-point-at pom
14981 (append org-todo-keywords-1 '("")))))
14982 ((equal property "PRIORITY")
14983 (let ((n org-lowest-priority))
14984 (while (>= n org-highest-priority)
14985 (push (char-to-string n) vals)
14986 (setq n (1- n)))))
14987 ((member property org-special-properties))
14988 ((setq vals (run-hook-with-args-until-success
14989 'org-property-allowed-value-functions property)))
14991 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14992 (when (and vals (string-match "\\S-" vals))
14993 (setq vals (car (read-from-string (concat "(" vals ")"))))
14994 (setq vals (mapcar (lambda (x)
14995 (cond ((stringp x) x)
14996 ((numberp x) (number-to-string x))
14997 ((symbolp x) (symbol-name x))
14998 (t "???")))
14999 vals)))))
15000 (when (member ":ETC" vals)
15001 (setq vals (remove ":ETC" vals))
15002 (org-add-props (car vals) '(org-unrestricted t)))
15003 (if table (mapcar 'list vals) vals)))
15005 (defun org-property-previous-allowed-value (&optional previous)
15006 "Switch to the next allowed value for this property."
15007 (interactive)
15008 (org-property-next-allowed-value t))
15010 (defun org-property-next-allowed-value (&optional previous)
15011 "Switch to the next allowed value for this property."
15012 (interactive)
15013 (unless (org-at-property-p)
15014 (error "Not at a property"))
15015 (let* ((key (match-string 2))
15016 (value (match-string 3))
15017 (allowed (or (org-property-get-allowed-values (point) key)
15018 (and (member value '("[ ]" "[-]" "[X]"))
15019 '("[ ]" "[X]"))))
15020 nval)
15021 (unless allowed
15022 (error "Allowed values for this property have not been defined"))
15023 (if previous (setq allowed (reverse allowed)))
15024 (if (member value allowed)
15025 (setq nval (car (cdr (member value allowed)))))
15026 (setq nval (or nval (car allowed)))
15027 (if (equal nval value)
15028 (error "Only one allowed value for this property"))
15029 (org-at-property-p)
15030 (replace-match (concat " :" key ": " nval) t t)
15031 (org-indent-line)
15032 (beginning-of-line 1)
15033 (skip-chars-forward " \t")
15034 (run-hook-with-args 'org-property-changed-functions key nval)))
15036 (defun org-find-olp (path &optional this-buffer)
15037 "Return a marker pointing to the entry at outline path OLP.
15038 If anything goes wrong, throw an error.
15039 You can wrap this call to catch the error like this:
15041 (condition-case msg
15042 (org-mobile-locate-entry (match-string 4))
15043 (error (nth 1 msg)))
15045 The return value will then be either a string with the error message,
15046 or a marker if everything is OK.
15048 If THIS-BUFFER is set, the outline path does not contain a file,
15049 only headings."
15050 (let* ((file (if this-buffer buffer-file-name (pop path)))
15051 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15052 (level 1)
15053 (lmin 1)
15054 (lmax 1)
15055 limit re end found pos heading cnt flevel)
15056 (unless buffer (error "File not found :%s" file))
15057 (with-current-buffer buffer
15058 (save-excursion
15059 (save-restriction
15060 (widen)
15061 (setq limit (point-max))
15062 (goto-char (point-min))
15063 (while (setq heading (pop path))
15064 (setq re (format org-complex-heading-regexp-format
15065 (regexp-quote heading)))
15066 (setq cnt 0 pos (point))
15067 (while (re-search-forward re end t)
15068 (setq level (- (match-end 1) (match-beginning 1)))
15069 (if (and (>= level lmin) (<= level lmax))
15070 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15071 (when (= cnt 0) (error "Heading not found on level %d: %s"
15072 lmax heading))
15073 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15074 lmax heading))
15075 (goto-char found)
15076 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15077 (setq end (save-excursion (org-end-of-subtree t t))))
15078 (when (org-at-heading-p)
15079 (move-marker (make-marker) (point))))))))
15081 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15082 "Find node HEADING in BUFFER.
15083 Return a marker to the heading if it was found, or nil if not.
15084 If POS-ONLY is set, return just the position instead of a marker.
15086 The heading text must match exact, but it may have a TODO keyword,
15087 a priority cookie and tags in the standard locations."
15088 (with-current-buffer (or buffer (current-buffer))
15089 (save-excursion
15090 (save-restriction
15091 (widen)
15092 (goto-char (point-min))
15093 (let (case-fold-search)
15094 (if (re-search-forward
15095 (format org-complex-heading-regexp-format
15096 (regexp-quote heading)) nil t)
15097 (if pos-only
15098 (match-beginning 0)
15099 (move-marker (make-marker) (match-beginning 0)))))))))
15101 (defun org-find-exact-heading-in-directory (heading &optional dir)
15102 "Find Org node headline HEADING in all .org files in directory DIR.
15103 When the target headline is found, return a marker to this location."
15104 (let ((files (directory-files (or dir default-directory)
15105 nil "\\`[^.#].*\\.org\\'"))
15106 file visiting m buffer)
15107 (catch 'found
15108 (while (setq file (pop files))
15109 (message "trying %s" file)
15110 (setq visiting (org-find-base-buffer-visiting file))
15111 (setq buffer (or visiting (find-file-noselect file)))
15112 (setq m (org-find-exact-headline-in-buffer
15113 heading buffer))
15114 (when (and (not m) (not visiting)) (kill-buffer buffer))
15115 (and m (throw 'found m))))))
15117 (defun org-find-entry-with-id (ident)
15118 "Locate the entry that contains the ID property with exact value IDENT.
15119 IDENT can be a string, a symbol or a number, this function will search for
15120 the string representation of it.
15121 Return the position where this entry starts, or nil if there is no such entry."
15122 (interactive "sID: ")
15123 (let ((id (cond
15124 ((stringp ident) ident)
15125 ((symbol-name ident) (symbol-name ident))
15126 ((numberp ident) (number-to-string ident))
15127 (t (error "IDENT %s must be a string, symbol or number" ident))))
15128 (case-fold-search nil))
15129 (save-excursion
15130 (save-restriction
15131 (widen)
15132 (goto-char (point-min))
15133 (when (re-search-forward
15134 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15135 nil t)
15136 (org-back-to-heading t)
15137 (point))))))
15139 ;;;; Timestamps
15141 (defvar org-last-changed-timestamp nil)
15142 (defvar org-last-inserted-timestamp nil
15143 "The last time stamp inserted with `org-insert-time-stamp'.")
15144 (defvar org-time-was-given) ; dynamically scoped parameter
15145 (defvar org-end-time-was-given) ; dynamically scoped parameter
15146 (defvar org-ts-what) ; dynamically scoped parameter
15148 (defun org-time-stamp (arg &optional inactive)
15149 "Prompt for a date/time and insert a time stamp.
15150 If the user specifies a time like HH:MM or if this command is
15151 called with at least one prefix argument, the time stamp contains
15152 the date and the time. Otherwise, only the date is be included.
15154 All parts of a date not specified by the user is filled in from
15155 the current date/time. So if you just press return without
15156 typing anything, the time stamp will represent the current
15157 date/time.
15159 If there is already a timestamp at the cursor, it will be
15160 modified.
15162 With two universal prefix arguments, insert an active timestamp
15163 with the current time without prompting the user."
15164 (interactive "P")
15165 (let* ((ts nil)
15166 (default-time
15167 ;; Default time is either today, or, when entering a range,
15168 ;; the range start.
15169 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15170 (save-excursion
15171 (re-search-backward
15172 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15173 (- (point) 20) t)))
15174 (apply 'encode-time (org-parse-time-string (match-string 1)))
15175 (current-time)))
15176 (default-input (and ts (org-get-compact-tod ts)))
15177 (repeater (save-excursion
15178 (save-match-data
15179 (beginning-of-line)
15180 (when (re-search-forward
15181 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15182 (save-excursion (progn (end-of-line) (point))) t)
15183 (match-string 0)))))
15184 org-time-was-given org-end-time-was-given time)
15185 (cond
15186 ((and (org-at-timestamp-p t)
15187 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15188 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15189 (insert "--")
15190 (setq time (let ((this-command this-command))
15191 (org-read-date arg 'totime nil nil
15192 default-time default-input inactive)))
15193 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15194 ((org-at-timestamp-p t)
15195 (setq time (let ((this-command this-command))
15196 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15197 (when (org-at-timestamp-p t) ; just to get the match data
15198 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15199 (replace-match "")
15200 (setq org-last-changed-timestamp
15201 (org-insert-time-stamp
15202 time (or org-time-was-given arg)
15203 inactive nil nil (list org-end-time-was-given)))
15204 (when repeater (goto-char (1- (point))) (insert " " repeater)
15205 (setq org-last-changed-timestamp
15206 (concat (substring org-last-inserted-timestamp 0 -1)
15207 " " repeater ">"))))
15208 (message "Timestamp updated"))
15209 ((equal arg '(16))
15210 (org-insert-time-stamp (current-time) t))
15212 (setq time (let ((this-command this-command))
15213 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15214 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15215 nil nil (list org-end-time-was-given))))))
15217 ;; FIXME: can we use this for something else, like computing time differences?
15218 (defun org-get-compact-tod (s)
15219 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15220 (let* ((t1 (match-string 1 s))
15221 (h1 (string-to-number (match-string 2 s)))
15222 (m1 (string-to-number (match-string 3 s)))
15223 (t2 (and (match-end 4) (match-string 5 s)))
15224 (h2 (and t2 (string-to-number (match-string 6 s))))
15225 (m2 (and t2 (string-to-number (match-string 7 s))))
15226 dh dm)
15227 (if (not t2)
15229 (setq dh (- h2 h1) dm (- m2 m1))
15230 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15231 (concat t1 "+" (number-to-string dh)
15232 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15234 (defun org-time-stamp-inactive (&optional arg)
15235 "Insert an inactive time stamp.
15236 An inactive time stamp is enclosed in square brackets instead of angle
15237 brackets. It is inactive in the sense that it does not trigger agenda entries,
15238 does not link to the calendar and cannot be changed with the S-cursor keys.
15239 So these are more for recording a certain time/date."
15240 (interactive "P")
15241 (org-time-stamp arg 'inactive))
15243 (defvar org-date-ovl (make-overlay 1 1))
15244 (overlay-put org-date-ovl 'face 'org-date-selected)
15245 (org-detach-overlay org-date-ovl)
15247 (defvar org-ans1) ; dynamically scoped parameter
15248 (defvar org-ans2) ; dynamically scoped parameter
15250 (defvar org-plain-time-of-day-regexp) ; defined below
15252 (defvar org-overriding-default-time nil) ; dynamically scoped
15253 (defvar org-read-date-overlay nil)
15254 (defvar org-dcst nil) ; dynamically scoped
15255 (defvar org-read-date-history nil)
15256 (defvar org-read-date-final-answer nil)
15257 (defvar org-read-date-analyze-futurep nil)
15258 (defvar org-read-date-analyze-forced-year nil)
15259 (defvar org-read-date-inactive)
15261 (defun org-read-date (&optional org-with-time to-time from-string prompt
15262 default-time default-input inactive)
15263 "Read a date, possibly a time, and make things smooth for the user.
15264 The prompt will suggest to enter an ISO date, but you can also enter anything
15265 which will at least partially be understood by `parse-time-string'.
15266 Unrecognized parts of the date will default to the current day, month, year,
15267 hour and minute. If this command is called to replace a timestamp at point,
15268 or to enter the second timestamp of a range, the default time is taken
15269 from the existing stamp. Furthermore, the command prefers the future,
15270 so if you are giving a date where the year is not given, and the day-month
15271 combination is already past in the current year, it will assume you
15272 mean next year. For details, see the manual. A few examples:
15274 3-2-5 --> 2003-02-05
15275 feb 15 --> currentyear-02-15
15276 2/15 --> currentyear-02-15
15277 sep 12 9 --> 2009-09-12
15278 12:45 --> today 12:45
15279 22 sept 0:34 --> currentyear-09-22 0:34
15280 12 --> currentyear-currentmonth-12
15281 Fri --> nearest Friday (today or later)
15282 etc.
15284 Furthermore you can specify a relative date by giving, as the *first* thing
15285 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15286 change in days weeks, months, years.
15287 With a single plus or minus, the date is relative to today. With a double
15288 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15289 +4d --> four days from today
15290 +4 --> same as above
15291 +2w --> two weeks from today
15292 ++5 --> five days from default date
15294 The function understands only English month and weekday abbreviations.
15296 While prompting, a calendar is popped up - you can also select the
15297 date with the mouse (button 1). The calendar shows a period of three
15298 months. To scroll it to other months, use the keys `>' and `<'.
15299 If you don't like the calendar, turn it off with
15300 \(setq org-read-date-popup-calendar nil)
15302 With optional argument TO-TIME, the date will immediately be converted
15303 to an internal time.
15304 With an optional argument WITH-TIME, the prompt will suggest to also
15305 insert a time. Note that when WITH-TIME is not set, you can still
15306 enter a time, and this function will inform the calling routine about
15307 this change. The calling routine may then choose to change the format
15308 used to insert the time stamp into the buffer to include the time.
15309 With optional argument FROM-STRING, read from this string instead from
15310 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15311 the time/date that is used for everything that is not specified by the
15312 user."
15313 (require 'parse-time)
15314 (let* ((org-time-stamp-rounding-minutes
15315 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15316 (org-dcst org-display-custom-times)
15317 (ct (org-current-time))
15318 (org-def (or org-overriding-default-time default-time ct))
15319 (org-defdecode (decode-time org-def))
15320 (dummy (progn
15321 (when (< (nth 2 org-defdecode) org-extend-today-until)
15322 (setcar (nthcdr 2 org-defdecode) -1)
15323 (setcar (nthcdr 1 org-defdecode) 59)
15324 (setq org-def (apply 'encode-time org-defdecode)
15325 org-defdecode (decode-time org-def)))))
15326 (calendar-frame-setup nil)
15327 (calendar-setup nil)
15328 (calendar-move-hook nil)
15329 (calendar-view-diary-initially-flag nil)
15330 (calendar-view-holidays-initially-flag nil)
15331 (timestr (format-time-string
15332 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15333 (prompt (concat (if prompt (concat prompt " ") "")
15334 (format "Date+time [%s]: " timestr)))
15335 ans (org-ans0 "") org-ans1 org-ans2 final)
15337 (cond
15338 (from-string (setq ans from-string))
15339 (org-read-date-popup-calendar
15340 (save-excursion
15341 (save-window-excursion
15342 (calendar)
15343 (org-eval-in-calendar '(setq cursor-type nil) t)
15344 (unwind-protect
15345 (progn
15346 (calendar-forward-day (- (time-to-days org-def)
15347 (calendar-absolute-from-gregorian
15348 (calendar-current-date))))
15349 (org-eval-in-calendar nil t)
15350 (let* ((old-map (current-local-map))
15351 (map (copy-keymap calendar-mode-map))
15352 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15353 (org-defkey map (kbd "RET") 'org-calendar-select)
15354 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15355 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15356 (org-defkey minibuffer-local-map [(meta shift left)]
15357 (lambda () (interactive)
15358 (org-eval-in-calendar '(calendar-backward-month 1))))
15359 (org-defkey minibuffer-local-map [(meta shift right)]
15360 (lambda () (interactive)
15361 (org-eval-in-calendar '(calendar-forward-month 1))))
15362 (org-defkey minibuffer-local-map [(meta shift up)]
15363 (lambda () (interactive)
15364 (org-eval-in-calendar '(calendar-backward-year 1))))
15365 (org-defkey minibuffer-local-map [(meta shift down)]
15366 (lambda () (interactive)
15367 (org-eval-in-calendar '(calendar-forward-year 1))))
15368 (org-defkey minibuffer-local-map [?\e (shift left)]
15369 (lambda () (interactive)
15370 (org-eval-in-calendar '(calendar-backward-month 1))))
15371 (org-defkey minibuffer-local-map [?\e (shift right)]
15372 (lambda () (interactive)
15373 (org-eval-in-calendar '(calendar-forward-month 1))))
15374 (org-defkey minibuffer-local-map [?\e (shift up)]
15375 (lambda () (interactive)
15376 (org-eval-in-calendar '(calendar-backward-year 1))))
15377 (org-defkey minibuffer-local-map [?\e (shift down)]
15378 (lambda () (interactive)
15379 (org-eval-in-calendar '(calendar-forward-year 1))))
15380 (org-defkey minibuffer-local-map [(shift up)]
15381 (lambda () (interactive)
15382 (org-eval-in-calendar '(calendar-backward-week 1))))
15383 (org-defkey minibuffer-local-map [(shift down)]
15384 (lambda () (interactive)
15385 (org-eval-in-calendar '(calendar-forward-week 1))))
15386 (org-defkey minibuffer-local-map [(shift left)]
15387 (lambda () (interactive)
15388 (org-eval-in-calendar '(calendar-backward-day 1))))
15389 (org-defkey minibuffer-local-map [(shift right)]
15390 (lambda () (interactive)
15391 (org-eval-in-calendar '(calendar-forward-day 1))))
15392 (org-defkey minibuffer-local-map ">"
15393 (lambda () (interactive)
15394 (org-eval-in-calendar '(scroll-calendar-left 1))))
15395 (org-defkey minibuffer-local-map "<"
15396 (lambda () (interactive)
15397 (org-eval-in-calendar '(scroll-calendar-right 1))))
15398 (org-defkey minibuffer-local-map "\C-v"
15399 (lambda () (interactive)
15400 (org-eval-in-calendar
15401 '(calendar-scroll-left-three-months 1))))
15402 (org-defkey minibuffer-local-map "\M-v"
15403 (lambda () (interactive)
15404 (org-eval-in-calendar
15405 '(calendar-scroll-right-three-months 1))))
15406 (run-hooks 'org-read-date-minibuffer-setup-hook)
15407 (unwind-protect
15408 (progn
15409 (use-local-map map)
15410 (setq org-read-date-inactive inactive)
15411 (add-hook 'post-command-hook 'org-read-date-display)
15412 (setq org-ans0 (read-string prompt default-input
15413 'org-read-date-history nil))
15414 ;; org-ans0: from prompt
15415 ;; org-ans1: from mouse click
15416 ;; org-ans2: from calendar motion
15417 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15418 (remove-hook 'post-command-hook 'org-read-date-display)
15419 (use-local-map old-map)
15420 (when org-read-date-overlay
15421 (delete-overlay org-read-date-overlay)
15422 (setq org-read-date-overlay nil)))))
15423 (bury-buffer "*Calendar*")))))
15425 (t ; Naked prompt only
15426 (unwind-protect
15427 (setq ans (read-string prompt default-input
15428 'org-read-date-history timestr))
15429 (when org-read-date-overlay
15430 (delete-overlay org-read-date-overlay)
15431 (setq org-read-date-overlay nil)))))
15433 (setq final (org-read-date-analyze ans org-def org-defdecode))
15435 (when org-read-date-analyze-forced-year
15436 (message "Year was forced into %s"
15437 (if org-read-date-force-compatible-dates
15438 "compatible range (1970-2037)"
15439 "range representable on this machine"))
15440 (ding))
15442 ;; One round trip to get rid of 34th of August and stuff like that....
15443 (setq final (decode-time (apply 'encode-time final)))
15445 (setq org-read-date-final-answer ans)
15447 (if to-time
15448 (apply 'encode-time final)
15449 (if (and (boundp 'org-time-was-given) org-time-was-given)
15450 (format "%04d-%02d-%02d %02d:%02d"
15451 (nth 5 final) (nth 4 final) (nth 3 final)
15452 (nth 2 final) (nth 1 final))
15453 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15455 (defvar org-def)
15456 (defvar org-defdecode)
15457 (defvar org-with-time)
15458 (defun org-read-date-display ()
15459 "Display the current date prompt interpretation in the minibuffer."
15460 (when org-read-date-display-live
15461 (when org-read-date-overlay
15462 (delete-overlay org-read-date-overlay))
15463 (when (minibufferp (current-buffer))
15464 (save-excursion
15465 (end-of-line 1)
15466 (while (not (equal (buffer-substring
15467 (max (point-min) (- (point) 4)) (point))
15468 " "))
15469 (insert " ")))
15470 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15471 " " (or org-ans1 org-ans2)))
15472 (org-end-time-was-given nil)
15473 (f (org-read-date-analyze ans org-def org-defdecode))
15474 (fmts (if org-dcst
15475 org-time-stamp-custom-formats
15476 org-time-stamp-formats))
15477 (fmt (if (or org-with-time
15478 (and (boundp 'org-time-was-given) org-time-was-given))
15479 (cdr fmts)
15480 (car fmts)))
15481 (txt (format-time-string fmt (apply 'encode-time f)))
15482 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15483 (txt (concat "=> " txt)))
15484 (when (and org-end-time-was-given
15485 (string-match org-plain-time-of-day-regexp txt))
15486 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15487 org-end-time-was-given
15488 (substring txt (match-end 0)))))
15489 (when org-read-date-analyze-futurep
15490 (setq txt (concat txt " (=>F)")))
15491 (setq org-read-date-overlay
15492 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15493 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15495 (defun org-read-date-analyze (ans org-def org-defdecode)
15496 "Analyze the combined answer of the date prompt."
15497 ;; FIXME: cleanup and comment
15498 (let ((nowdecode (decode-time (current-time)))
15499 delta deltan deltaw deltadef year month day
15500 hour minute second wday pm h2 m2 tl wday1
15501 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15502 (setq org-read-date-analyze-futurep nil
15503 org-read-date-analyze-forced-year nil)
15504 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15505 (setq ans "+0"))
15507 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15508 (setq ans (replace-match "" t t ans)
15509 deltan (car delta)
15510 deltaw (nth 1 delta)
15511 deltadef (nth 2 delta)))
15513 ;; Check if there is an iso week date in there
15514 ;; If yes, store the info and postpone interpreting it until the rest
15515 ;; of the parsing is done
15516 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15517 (setq iso-year (if (match-end 1)
15518 (org-small-year-to-year
15519 (string-to-number (match-string 1 ans))))
15520 iso-weekday (if (match-end 3)
15521 (string-to-number (match-string 3 ans)))
15522 iso-week (string-to-number (match-string 2 ans)))
15523 (setq ans (replace-match "" t t ans)))
15525 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15526 (when (string-match
15527 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15528 (setq year (if (match-end 2)
15529 (string-to-number (match-string 2 ans))
15530 (progn (setq kill-year t)
15531 (string-to-number (format-time-string "%Y"))))
15532 month (string-to-number (match-string 3 ans))
15533 day (string-to-number (match-string 4 ans)))
15534 (if (< year 100) (setq year (+ 2000 year)))
15535 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15536 t nil ans)))
15538 ;; Help matching dotted european dates
15539 (when (string-match
15540 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15541 (setq year (if (match-end 3)
15542 (string-to-number (match-string 3 ans))
15543 (progn (setq kill-year t)
15544 (string-to-number (format-time-string "%Y"))))
15545 day (string-to-number (match-string 1 ans))
15546 month (string-to-number (match-string 2 ans))
15547 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15548 t nil ans)))
15550 ;; Help matching american dates, like 5/30 or 5/30/7
15551 (when (string-match
15552 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15553 (setq year (if (match-end 4)
15554 (string-to-number (match-string 4 ans))
15555 (progn (setq kill-year t)
15556 (string-to-number (format-time-string "%Y"))))
15557 month (string-to-number (match-string 1 ans))
15558 day (string-to-number (match-string 2 ans)))
15559 (if (< year 100) (setq year (+ 2000 year)))
15560 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15561 t nil ans)))
15562 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15563 ;; If there is a time with am/pm, and *no* time without it, we convert
15564 ;; so that matching will be successful.
15565 (loop for i from 1 to 2 do ; twice, for end time as well
15566 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15567 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15568 (setq hour (string-to-number (match-string 1 ans))
15569 minute (if (match-end 3)
15570 (string-to-number (match-string 3 ans))
15572 pm (equal ?p
15573 (string-to-char (downcase (match-string 4 ans)))))
15574 (if (and (= hour 12) (not pm))
15575 (setq hour 0)
15576 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15577 (setq ans (replace-match (format "%02d:%02d" hour minute)
15578 t t ans))))
15580 ;; Check if a time range is given as a duration
15581 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15582 (setq hour (string-to-number (match-string 1 ans))
15583 h2 (+ hour (string-to-number (match-string 3 ans)))
15584 minute (string-to-number (match-string 2 ans))
15585 m2 (+ minute (if (match-end 5) (string-to-number
15586 (match-string 5 ans))0)))
15587 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15588 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15589 t t ans)))
15591 ;; Check if there is a time range
15592 (when (boundp 'org-end-time-was-given)
15593 (setq org-time-was-given nil)
15594 (when (and (string-match org-plain-time-of-day-regexp ans)
15595 (match-end 8))
15596 (setq org-end-time-was-given (match-string 8 ans))
15597 (setq ans (concat (substring ans 0 (match-beginning 7))
15598 (substring ans (match-end 7))))))
15600 (setq tl (parse-time-string ans)
15601 day (or (nth 3 tl) (nth 3 org-defdecode))
15602 month (or (nth 4 tl)
15603 (if (and org-read-date-prefer-future
15604 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15605 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15606 (nth 4 org-defdecode)))
15607 year (or (and (not kill-year) (nth 5 tl))
15608 (if (and org-read-date-prefer-future
15609 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15610 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15611 (nth 5 org-defdecode)))
15612 hour (or (nth 2 tl) (nth 2 org-defdecode))
15613 minute (or (nth 1 tl) (nth 1 org-defdecode))
15614 second (or (nth 0 tl) 0)
15615 wday (nth 6 tl))
15617 (when (and (eq org-read-date-prefer-future 'time)
15618 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15619 (equal day (nth 3 nowdecode))
15620 (equal month (nth 4 nowdecode))
15621 (equal year (nth 5 nowdecode))
15622 (nth 2 tl)
15623 (or (< (nth 2 tl) (nth 2 nowdecode))
15624 (and (= (nth 2 tl) (nth 2 nowdecode))
15625 (nth 1 tl)
15626 (< (nth 1 tl) (nth 1 nowdecode)))))
15627 (setq day (1+ day)
15628 futurep t))
15630 ;; Special date definitions below
15631 (cond
15632 (iso-week
15633 ;; There was an iso week
15634 (require 'cal-iso)
15635 (setq futurep nil)
15636 (setq year (or iso-year year)
15637 day (or iso-weekday wday 1)
15638 wday nil ; to make sure that the trigger below does not match
15639 iso-date (calendar-gregorian-from-absolute
15640 (calendar-absolute-from-iso
15641 (list iso-week day year))))
15642 ; FIXME: Should we also push ISO weeks into the future?
15643 ; (when (and org-read-date-prefer-future
15644 ; (not iso-year)
15645 ; (< (calendar-absolute-from-gregorian iso-date)
15646 ; (time-to-days (current-time))))
15647 ; (setq year (1+ year)
15648 ; iso-date (calendar-gregorian-from-absolute
15649 ; (calendar-absolute-from-iso
15650 ; (list iso-week day year)))))
15651 (setq month (car iso-date)
15652 year (nth 2 iso-date)
15653 day (nth 1 iso-date)))
15654 (deltan
15655 (setq futurep nil)
15656 (unless deltadef
15657 (let ((now (decode-time (current-time))))
15658 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15659 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15660 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15661 ((equal deltaw "m") (setq month (+ month deltan)))
15662 ((equal deltaw "y") (setq year (+ year deltan)))))
15663 ((and wday (not (nth 3 tl)))
15664 (setq futurep nil)
15665 ;; Weekday was given, but no day, so pick that day in the week
15666 ;; on or after the derived date.
15667 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15668 (unless (equal wday wday1)
15669 (setq day (+ day (% (- wday wday1 -7) 7))))))
15670 (if (and (boundp 'org-time-was-given)
15671 (nth 2 tl))
15672 (setq org-time-was-given t))
15673 (if (< year 100) (setq year (+ 2000 year)))
15674 ;; Check of the date is representable
15675 (if org-read-date-force-compatible-dates
15676 (progn
15677 (if (< year 1970)
15678 (setq year 1970 org-read-date-analyze-forced-year t))
15679 (if (> year 2037)
15680 (setq year 2037 org-read-date-analyze-forced-year t)))
15681 (condition-case nil
15682 (ignore (encode-time second minute hour day month year))
15683 (error
15684 (setq year (nth 5 org-defdecode))
15685 (setq org-read-date-analyze-forced-year t))))
15686 (setq org-read-date-analyze-futurep futurep)
15687 (list second minute hour day month year)))
15689 (defvar parse-time-weekdays)
15690 (defun org-read-date-get-relative (s today default)
15691 "Check string S for special relative date string.
15692 TODAY and DEFAULT are internal times, for today and for a default.
15693 Return shift list (N what def-flag)
15694 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15695 N is the number of WHATs to shift.
15696 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15697 the DEFAULT date rather than TODAY."
15698 (require 'parse-time)
15699 (when (and
15700 (string-match
15701 (concat
15702 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15703 "\\([0-9]+\\)?"
15704 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15705 "\\([ \t]\\|$\\)") s)
15706 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15707 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15708 (string-to-char (substring (match-string 1 s) -1))
15709 ?+))
15710 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15711 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15712 (what (if (match-end 3) (match-string 3 s) "d"))
15713 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15714 (date (if rel default today))
15715 (wday (nth 6 (decode-time date)))
15716 delta)
15717 (if wday1
15718 (progn
15719 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15720 (if (= dir ?-) (setq delta (- delta 7)))
15721 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15722 (list delta "d" rel))
15723 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15725 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15726 "Turn a user-specified date into the internal representation.
15727 The internal representation needed by the calendar is (month day year).
15728 This is a wrapper to handle the brain-dead convention in calendar that
15729 user function argument order change dependent on argument order."
15730 (if (boundp 'calendar-date-style)
15731 (cond
15732 ((eq calendar-date-style 'american)
15733 (list arg1 arg2 arg3))
15734 ((eq calendar-date-style 'european)
15735 (list arg2 arg1 arg3))
15736 ((eq calendar-date-style 'iso)
15737 (list arg2 arg3 arg1)))
15738 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15739 (if (org-bound-and-true-p european-calendar-style)
15740 (list arg2 arg1 arg3)
15741 (list arg1 arg2 arg3)))))
15743 (defun org-eval-in-calendar (form &optional keepdate)
15744 "Eval FORM in the calendar window and return to current window.
15745 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15746 otherwise stick to the current value of `org-ans2'."
15747 (let ((sf (selected-frame))
15748 (sw (selected-window)))
15749 (select-window (get-buffer-window "*Calendar*" t))
15750 (eval form)
15751 (when (and (not keepdate) (calendar-cursor-to-date))
15752 (let* ((date (calendar-cursor-to-date))
15753 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15754 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15755 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15756 (select-window sw)
15757 (org-select-frame-set-input-focus sf)))
15759 (defun org-calendar-select ()
15760 "Return to `org-read-date' with the date currently selected.
15761 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15762 (interactive)
15763 (when (calendar-cursor-to-date)
15764 (let* ((date (calendar-cursor-to-date))
15765 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15766 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15767 (if (active-minibuffer-window) (exit-minibuffer))))
15769 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15770 "Insert a date stamp for the date given by the internal TIME.
15771 WITH-HM means use the stamp format that includes the time of the day.
15772 INACTIVE means use square brackets instead of angular ones, so that the
15773 stamp will not contribute to the agenda.
15774 PRE and POST are optional strings to be inserted before and after the
15775 stamp.
15776 The command returns the inserted time stamp."
15777 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15778 stamp)
15779 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15780 (insert-before-markers (or pre ""))
15781 (when (listp extra)
15782 (setq extra (car extra))
15783 (if (and (stringp extra)
15784 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15785 (setq extra (format "-%02d:%02d"
15786 (string-to-number (match-string 1 extra))
15787 (string-to-number (match-string 2 extra))))
15788 (setq extra nil)))
15789 (when extra
15790 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15791 (insert-before-markers (setq stamp (format-time-string fmt time)))
15792 (insert-before-markers (or post ""))
15793 (setq org-last-inserted-timestamp stamp)))
15795 (defun org-toggle-time-stamp-overlays ()
15796 "Toggle the use of custom time stamp formats."
15797 (interactive)
15798 (setq org-display-custom-times (not org-display-custom-times))
15799 (unless org-display-custom-times
15800 (let ((p (point-min)) (bmp (buffer-modified-p)))
15801 (while (setq p (next-single-property-change p 'display))
15802 (if (and (get-text-property p 'display)
15803 (eq (get-text-property p 'face) 'org-date))
15804 (remove-text-properties
15805 p (setq p (next-single-property-change p 'display))
15806 '(display t))))
15807 (set-buffer-modified-p bmp)))
15808 (if (featurep 'xemacs)
15809 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15810 (org-restart-font-lock)
15811 (setq org-table-may-need-update t)
15812 (if org-display-custom-times
15813 (message "Time stamps are overlaid with custom format")
15814 (message "Time stamp overlays removed")))
15816 (defun org-display-custom-time (beg end)
15817 "Overlay modified time stamp format over timestamp between BEG and END."
15818 (let* ((ts (buffer-substring beg end))
15819 t1 w1 with-hm tf time str w2 (off 0))
15820 (save-match-data
15821 (setq t1 (org-parse-time-string ts t))
15822 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15823 (setq off (- (match-end 0) (match-beginning 0)))))
15824 (setq end (- end off))
15825 (setq w1 (- end beg)
15826 with-hm (and (nth 1 t1) (nth 2 t1))
15827 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15828 time (org-fix-decoded-time t1)
15829 str (org-add-props
15830 (format-time-string
15831 (substring tf 1 -1) (apply 'encode-time time))
15832 nil 'mouse-face 'highlight)
15833 w2 (length str))
15834 (if (not (= w2 w1))
15835 (add-text-properties (1+ beg) (+ 2 beg)
15836 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15837 (if (featurep 'xemacs)
15838 (progn
15839 (put-text-property beg end 'invisible t)
15840 (put-text-property beg end 'end-glyph (make-glyph str)))
15841 (put-text-property beg end 'display str))))
15843 (defun org-translate-time (string)
15844 "Translate all timestamps in STRING to custom format.
15845 But do this only if the variable `org-display-custom-times' is set."
15846 (when org-display-custom-times
15847 (save-match-data
15848 (let* ((start 0)
15849 (re org-ts-regexp-both)
15850 t1 with-hm inactive tf time str beg end)
15851 (while (setq start (string-match re string start))
15852 (setq beg (match-beginning 0)
15853 end (match-end 0)
15854 t1 (save-match-data
15855 (org-parse-time-string (substring string beg end) t))
15856 with-hm (and (nth 1 t1) (nth 2 t1))
15857 inactive (equal (substring string beg (1+ beg)) "[")
15858 tf (funcall (if with-hm 'cdr 'car)
15859 org-time-stamp-custom-formats)
15860 time (org-fix-decoded-time t1)
15861 str (format-time-string
15862 (concat
15863 (if inactive "[" "<") (substring tf 1 -1)
15864 (if inactive "]" ">"))
15865 (apply 'encode-time time))
15866 string (replace-match str t t string)
15867 start (+ start (length str)))))))
15868 string)
15870 (defun org-fix-decoded-time (time)
15871 "Set 0 instead of nil for the first 6 elements of time.
15872 Don't touch the rest."
15873 (let ((n 0))
15874 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15876 (defun org-days-to-time (timestamp-string)
15877 "Difference between TIMESTAMP-STRING and now in days."
15878 (- (time-to-days (org-time-string-to-time timestamp-string))
15879 (time-to-days (current-time))))
15881 (defun org-deadline-close (timestamp-string &optional ndays)
15882 "Is the time in TIMESTAMP-STRING close to the current date?"
15883 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15884 (and (< (org-days-to-time timestamp-string) ndays)
15885 (not (org-entry-is-done-p))))
15887 (defun org-get-wdays (ts)
15888 "Get the deadline lead time appropriate for timestring TS."
15889 (cond
15890 ((<= org-deadline-warning-days 0)
15891 ;; 0 or negative, enforce this value no matter what
15892 (- org-deadline-warning-days))
15893 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15894 ;; lead time is specified.
15895 (floor (* (string-to-number (match-string 1 ts))
15896 (cdr (assoc (match-string 2 ts)
15897 '(("d" . 1) ("w" . 7)
15898 ("m" . 30.4) ("y" . 365.25)))))))
15899 ;; go for the default.
15900 (t org-deadline-warning-days)))
15902 (defun org-calendar-select-mouse (ev)
15903 "Return to `org-read-date' with the date currently selected.
15904 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15905 (interactive "e")
15906 (mouse-set-point ev)
15907 (when (calendar-cursor-to-date)
15908 (let* ((date (calendar-cursor-to-date))
15909 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15910 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15911 (if (active-minibuffer-window) (exit-minibuffer))))
15913 (defun org-check-deadlines (ndays)
15914 "Check if there are any deadlines due or past due.
15915 A deadline is considered due if it happens within `org-deadline-warning-days'
15916 days from today's date. If the deadline appears in an entry marked DONE,
15917 it is not shown. The prefix arg NDAYS can be used to test that many
15918 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15919 (interactive "P")
15920 (let* ((org-warn-days
15921 (cond
15922 ((equal ndays '(4)) 100000)
15923 (ndays (prefix-numeric-value ndays))
15924 (t (abs org-deadline-warning-days))))
15925 (case-fold-search nil)
15926 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15927 (callback
15928 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15930 (message "%d deadlines past-due or due within %d days"
15931 (org-occur regexp nil callback)
15932 org-warn-days)))
15934 (defsubst org-re-timestamp (type)
15935 "Return a regexp for timestamp TYPE.
15936 Allowed values for TYPE are:
15938 all: all timestamps
15939 active: only active timestamps (<...>)
15940 inactive: only inactive timestamps ([...])
15941 scheduled: only scheduled timestamps
15942 deadline: only deadline timestamps
15944 When TYPE is nil, fall back on returning a regexp that matches
15945 both scheduled and deadline timestamps."
15946 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15947 ((eq type 'active) org-ts-regexp)
15948 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15949 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15950 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15951 ((eq type 'scheduled-or-deadline)
15952 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15954 (defun org-check-before-date (date)
15955 "Check if there are deadlines or scheduled entries before DATE."
15956 (interactive (list (org-read-date)))
15957 (let ((case-fold-search nil)
15958 (regexp (org-re-timestamp org-ts-type))
15959 (callback
15960 (lambda () (time-less-p
15961 (org-time-string-to-time (match-string 1))
15962 (org-time-string-to-time date)))))
15963 (message "%d entries before %s"
15964 (org-occur regexp nil callback) date)))
15966 (defun org-check-after-date (date)
15967 "Check if there are deadlines or scheduled entries after DATE."
15968 (interactive (list (org-read-date)))
15969 (let ((case-fold-search nil)
15970 (regexp (org-re-timestamp org-ts-type))
15971 (callback
15972 (lambda () (not
15973 (time-less-p
15974 (org-time-string-to-time (match-string 1))
15975 (org-time-string-to-time date))))))
15976 (message "%d entries after %s"
15977 (org-occur regexp nil callback) date)))
15979 (defun org-check-dates-range (start-date end-date)
15980 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15981 (interactive (list (org-read-date nil nil nil "Range starts")
15982 (org-read-date nil nil nil "Range end")))
15983 (let ((case-fold-search nil)
15984 (regexp (org-re-timestamp org-ts-type))
15985 (callback
15986 (lambda ()
15987 (let ((match (match-string 1)))
15988 (and
15989 (not (time-less-p
15990 (org-time-string-to-time match)
15991 (org-time-string-to-time start-date)))
15992 (time-less-p
15993 (org-time-string-to-time match)
15994 (org-time-string-to-time end-date)))))))
15995 (message "%d entries between %s and %s"
15996 (org-occur regexp nil callback) start-date end-date)))
15998 (defun org-evaluate-time-range (&optional to-buffer)
15999 "Evaluate a time range by computing the difference between start and end.
16000 Normally the result is just printed in the echo area, but with prefix arg
16001 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16002 If the time range is actually in a table, the result is inserted into the
16003 next column.
16004 For time difference computation, a year is assumed to be exactly 365
16005 days in order to avoid rounding problems."
16006 (interactive "P")
16008 (org-clock-update-time-maybe)
16009 (save-excursion
16010 (unless (org-at-date-range-p t)
16011 (goto-char (point-at-bol))
16012 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16013 (if (not (org-at-date-range-p t))
16014 (error "Not at a time-stamp range, and none found in current line")))
16015 (let* ((ts1 (match-string 1))
16016 (ts2 (match-string 2))
16017 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16018 (match-end (match-end 0))
16019 (time1 (org-time-string-to-time ts1))
16020 (time2 (org-time-string-to-time ts2))
16021 (t1 (org-float-time time1))
16022 (t2 (org-float-time time2))
16023 (diff (abs (- t2 t1)))
16024 (negative (< (- t2 t1) 0))
16025 ;; (ys (floor (* 365 24 60 60)))
16026 (ds (* 24 60 60))
16027 (hs (* 60 60))
16028 (fy "%dy %dd %02d:%02d")
16029 (fy1 "%dy %dd")
16030 (fd "%dd %02d:%02d")
16031 (fd1 "%dd")
16032 (fh "%02d:%02d")
16033 y d h m align)
16034 (if havetime
16035 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16037 d (floor (/ diff ds)) diff (mod diff ds)
16038 h (floor (/ diff hs)) diff (mod diff hs)
16039 m (floor (/ diff 60)))
16040 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16042 d (floor (+ (/ diff ds) 0.5))
16043 h 0 m 0))
16044 (if (not to-buffer)
16045 (message "%s" (org-make-tdiff-string y d h m))
16046 (if (org-at-table-p)
16047 (progn
16048 (goto-char match-end)
16049 (setq align t)
16050 (and (looking-at " *|") (goto-char (match-end 0))))
16051 (goto-char match-end))
16052 (if (looking-at
16053 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16054 (replace-match ""))
16055 (if negative (insert " -"))
16056 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16057 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16058 (insert " " (format fh h m))))
16059 (if align (org-table-align))
16060 (message "Time difference inserted")))))
16062 (defun org-make-tdiff-string (y d h m)
16063 (let ((fmt "")
16064 (l nil))
16065 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16066 l (push y l)))
16067 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16068 l (push d l)))
16069 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16070 l (push h l)))
16071 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16072 l (push m l)))
16073 (apply 'format fmt (nreverse l))))
16075 (defun org-time-string-to-time (s &optional buffer pos)
16076 (condition-case errdata
16077 (apply 'encode-time (org-parse-time-string s))
16078 (error (error "Bad timestamp `%s'%s\nError was: %s"
16079 s (if (not (and buffer pos))
16081 (format " at %d in buffer `%s'" pos buffer))
16082 (cdr errdata)))))
16084 (defun org-time-string-to-seconds (s)
16085 (org-float-time (org-time-string-to-time s)))
16087 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16088 "Convert a time stamp to an absolute day number.
16089 If there is a specifier for a cyclic time stamp, get the closest date to
16090 DAYNR.
16091 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16092 The variable date is bound by the calendar when this is called."
16093 (cond
16094 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16095 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16096 daynr
16097 (+ daynr 1000)))
16098 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16099 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16100 (time-to-days (current-time))) (match-string 0 s)
16101 prefer show-all))
16102 (t (time-to-days
16103 (condition-case errdata
16104 (apply 'encode-time (org-parse-time-string s))
16105 (error (error "Bad timestamp `%s'%s\nError was: %s"
16106 s (if (not (and buffer pos))
16108 (format " at %d in buffer `%s'" pos buffer))
16109 (cdr errdata))))))))
16111 (defun org-days-to-iso-week (days)
16112 "Return the iso week number."
16113 (require 'cal-iso)
16114 (car (calendar-iso-from-absolute days)))
16116 (defun org-small-year-to-year (year)
16117 "Convert 2-digit years into 4-digit years.
16118 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16119 The year 2000 cannot be abbreviated. Any year larger than 99
16120 is returned unchanged."
16121 (if (< year 38)
16122 (setq year (+ 2000 year))
16123 (if (< year 100)
16124 (setq year (+ 1900 year))))
16125 year)
16127 (defun org-time-from-absolute (d)
16128 "Return the time corresponding to date D.
16129 D may be an absolute day number, or a calendar-type list (month day year)."
16130 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16131 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16133 (defun org-calendar-holiday ()
16134 "List of holidays, for Diary display in Org-mode."
16135 (require 'holidays)
16136 (let ((hl (funcall
16137 (if (fboundp 'calendar-check-holidays)
16138 'calendar-check-holidays 'check-calendar-holidays) date)))
16139 (if hl (mapconcat 'identity hl "; "))))
16141 (defun org-diary-sexp-entry (sexp entry date)
16142 "Process a SEXP diary ENTRY for DATE."
16143 (require 'diary-lib)
16144 (let ((result (if calendar-debug-sexp
16145 (let ((stack-trace-on-error t))
16146 (eval (car (read-from-string sexp))))
16147 (condition-case nil
16148 (eval (car (read-from-string sexp)))
16149 (error
16150 (beep)
16151 (message "Bad sexp at line %d in %s: %s"
16152 (org-current-line)
16153 (buffer-file-name) sexp)
16154 (sleep-for 2))))))
16155 (cond ((stringp result) (split-string result "; "))
16156 ((and (consp result)
16157 (not (consp (cdr result)))
16158 (stringp (cdr result))) (cdr result))
16159 ((and (consp result)
16160 (stringp (car result))) result)
16161 (result entry)
16162 (t nil))))
16164 (defun org-diary-to-ical-string (frombuf)
16165 "Get iCalendar entries from diary entries in buffer FROMBUF.
16166 This uses the icalendar.el library."
16167 (let* ((tmpdir (if (featurep 'xemacs)
16168 (temp-directory)
16169 temporary-file-directory))
16170 (tmpfile (make-temp-name
16171 (expand-file-name "orgics" tmpdir)))
16172 buf rtn b e)
16173 (with-current-buffer frombuf
16174 (icalendar-export-region (point-min) (point-max) tmpfile)
16175 (setq buf (find-buffer-visiting tmpfile))
16176 (set-buffer buf)
16177 (goto-char (point-min))
16178 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16179 (setq b (match-beginning 0)))
16180 (goto-char (point-max))
16181 (if (re-search-backward "^END:VEVENT" nil t)
16182 (setq e (match-end 0)))
16183 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16184 (kill-buffer buf)
16185 (delete-file tmpfile)
16186 rtn))
16188 (defun org-closest-date (start current change prefer show-all)
16189 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16190 When PREFER is `past', return a date that is either CURRENT or past.
16191 When PREFER is `future', return a date that is either CURRENT or future.
16192 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16193 ;; Make the proper lists from the dates
16194 (catch 'exit
16195 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16196 dn dw sday cday n1 n2 n0
16197 d m y y1 y2 date1 date2 nmonths nm ny m2)
16199 (setq start (org-date-to-gregorian start)
16200 current (org-date-to-gregorian
16201 (if show-all
16202 current
16203 (time-to-days (current-time))))
16204 sday (calendar-absolute-from-gregorian start)
16205 cday (calendar-absolute-from-gregorian current))
16207 (if (<= cday sday) (throw 'exit sday))
16209 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16210 (setq dn (string-to-number (match-string 1 change))
16211 dw (cdr (assoc (match-string 2 change) a1)))
16212 (error "Invalid change specifier: %s" change))
16213 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16214 (cond
16215 ((eq dw 'day)
16216 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16217 n2 (+ n1 dn)))
16218 ((eq dw 'year)
16219 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16220 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16221 (setq date1 (list m d y1)
16222 n1 (calendar-absolute-from-gregorian date1)
16223 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16224 n2 (calendar-absolute-from-gregorian date2)))
16225 ((eq dw 'month)
16226 ;; approx number of month between the two dates
16227 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16228 ;; How often does dn fit in there?
16229 (setq d (nth 1 start) m (car start) y (nth 2 start)
16230 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16231 m (+ m nm)
16232 ny (floor (/ m 12))
16233 y (+ y ny)
16234 m (- m (* ny 12)))
16235 (while (> m 12) (setq m (- m 12) y (1+ y)))
16236 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16237 (setq m2 (+ m dn) y2 y)
16238 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16239 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16240 (while (<= n2 cday)
16241 (setq n1 n2 m m2 y y2)
16242 (setq m2 (+ m dn) y2 y)
16243 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16244 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16245 ;; Make sure n1 is the earlier date
16246 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16247 (if show-all
16248 (cond
16249 ((eq prefer 'past) (if (= cday n2) n2 n1))
16250 ((eq prefer 'future) (if (= cday n1) n1 n2))
16251 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16252 (cond
16253 ((eq prefer 'past) (if (= cday n2) n2 n1))
16254 ((eq prefer 'future) (if (= cday n1) n1 n2))
16255 (t (if (= cday n1) n1 n2)))))))
16257 (defun org-date-to-gregorian (date)
16258 "Turn any specification of DATE into a Gregorian date for the calendar."
16259 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16260 ((and (listp date) (= (length date) 3)) date)
16261 ((stringp date)
16262 (setq date (org-parse-time-string date))
16263 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16264 ((listp date)
16265 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16267 (defun org-parse-time-string (s &optional nodefault)
16268 "Parse the standard Org-mode time string.
16269 This should be a lot faster than the normal `parse-time-string'.
16270 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16271 hour and minute fields will be nil if not given."
16272 (if (string-match org-ts-regexp0 s)
16273 (list 0
16274 (if (or (match-beginning 8) (not nodefault))
16275 (string-to-number (or (match-string 8 s) "0")))
16276 (if (or (match-beginning 7) (not nodefault))
16277 (string-to-number (or (match-string 7 s) "0")))
16278 (string-to-number (match-string 4 s))
16279 (string-to-number (match-string 3 s))
16280 (string-to-number (match-string 2 s))
16281 nil nil nil)
16282 (error "Not a standard Org-mode time string: %s" s)))
16284 (defun org-timestamp-up (&optional arg)
16285 "Increase the date item at the cursor by one.
16286 If the cursor is on the year, change the year. If it is on the month,
16287 the day or the time, change that.
16288 With prefix ARG, change by that many units."
16289 (interactive "p")
16290 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16292 (defun org-timestamp-down (&optional arg)
16293 "Decrease the date item at the cursor by one.
16294 If the cursor is on the year, change the year. If it is on the month,
16295 the day or the time, change that.
16296 With prefix ARG, change by that many units."
16297 (interactive "p")
16298 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16300 (defun org-timestamp-up-day (&optional arg)
16301 "Increase the date in the time stamp by one day.
16302 With prefix ARG, change that many days."
16303 (interactive "p")
16304 (if (and (not (org-at-timestamp-p t))
16305 (org-at-heading-p))
16306 (org-todo 'up)
16307 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16309 (defun org-timestamp-down-day (&optional arg)
16310 "Decrease the date in the time stamp by one day.
16311 With prefix ARG, change that many days."
16312 (interactive "p")
16313 (if (and (not (org-at-timestamp-p t))
16314 (org-at-heading-p))
16315 (org-todo 'down)
16316 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16318 (defun org-at-timestamp-p (&optional inactive-ok)
16319 "Determine if the cursor is in or at a timestamp."
16320 (interactive)
16321 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16322 (pos (point))
16323 (ans (or (looking-at tsr)
16324 (save-excursion
16325 (skip-chars-backward "^[<\n\r\t")
16326 (if (> (point) (point-min)) (backward-char 1))
16327 (and (looking-at tsr)
16328 (> (- (match-end 0) pos) -1))))))
16329 (and ans
16330 (boundp 'org-ts-what)
16331 (setq org-ts-what
16332 (cond
16333 ((= pos (match-beginning 0)) 'bracket)
16334 ;; Point is considered to be "on the bracket" whether
16335 ;; it's really on it or right after it.
16336 ((= pos (1- (match-end 0))) 'bracket)
16337 ((= pos (match-end 0)) 'after)
16338 ((org-pos-in-match-range pos 2) 'year)
16339 ((org-pos-in-match-range pos 3) 'month)
16340 ((org-pos-in-match-range pos 7) 'hour)
16341 ((org-pos-in-match-range pos 8) 'minute)
16342 ((or (org-pos-in-match-range pos 4)
16343 (org-pos-in-match-range pos 5)) 'day)
16344 ((and (> pos (or (match-end 8) (match-end 5)))
16345 (< pos (match-end 0)))
16346 (- pos (or (match-end 8) (match-end 5))))
16347 (t 'day))))
16348 ans))
16350 (defun org-toggle-timestamp-type ()
16351 "Toggle the type (<active> or [inactive]) of a time stamp."
16352 (interactive)
16353 (when (org-at-timestamp-p t)
16354 (let ((beg (match-beginning 0)) (end (match-end 0))
16355 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16356 (save-excursion
16357 (goto-char beg)
16358 (while (re-search-forward "[][<>]" end t)
16359 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16360 t t)))
16361 (message "Timestamp is now %sactive"
16362 (if (equal (char-after beg) ?<) "" "in")))))
16364 (defvar org-clock-history) ; defined in org-clock.el
16365 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16366 (defun org-timestamp-change (n &optional what updown)
16367 "Change the date in the time stamp at point.
16368 The date will be changed by N times WHAT. WHAT can be `day', `month',
16369 `year', `minute', `second'. If WHAT is not given, the cursor position
16370 in the timestamp determines what will be changed."
16371 (let ((origin (point)) origin-cat
16372 with-hm inactive
16373 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16374 org-ts-what
16375 extra rem
16376 ts time time0 fixnext clrgx)
16377 (if (not (org-at-timestamp-p t))
16378 (error "Not at a timestamp"))
16379 (if (and (not what) (eq org-ts-what 'bracket))
16380 (org-toggle-timestamp-type)
16381 ;; Point isn't on brackets. Remember the part of the time-stamp
16382 ;; the point was in. Indeed, size of time-stamps may change,
16383 ;; but point must be kept in the same category nonetheless.
16384 (setq origin-cat org-ts-what)
16385 (if (and (not what) (not (eq org-ts-what 'day))
16386 org-display-custom-times
16387 (get-text-property (point) 'display)
16388 (not (get-text-property (1- (point)) 'display)))
16389 (setq org-ts-what 'day))
16390 (setq org-ts-what (or what org-ts-what)
16391 inactive (= (char-after (match-beginning 0)) ?\[)
16392 ts (match-string 0))
16393 (replace-match "")
16394 (if (string-match
16395 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16397 (setq extra (match-string 1 ts)))
16398 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16399 (setq with-hm t))
16400 (setq time0 (org-parse-time-string ts))
16401 (when (and updown
16402 (eq org-ts-what 'minute)
16403 (not current-prefix-arg))
16404 ;; This looks like s-up and s-down. Change by one rounding step.
16405 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16406 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16407 (setcar (cdr time0) (+ (nth 1 time0)
16408 (if (> n 0) (- rem) (- dm rem))))))
16409 (setq time
16410 (encode-time (or (car time0) 0)
16411 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16412 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16413 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16414 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16415 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16416 (nthcdr 6 time0)))
16417 (when (and (member org-ts-what '(hour minute))
16418 extra
16419 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16420 (setq extra (org-modify-ts-extra
16421 extra
16422 (if (eq org-ts-what 'hour) 2 5)
16423 n dm)))
16424 (when (integerp org-ts-what)
16425 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16426 (if (eq what 'calendar)
16427 (let ((cal-date (org-get-date-from-calendar)))
16428 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16429 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16430 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16431 (setcar time0 (or (car time0) 0))
16432 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16433 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16434 (setq time (apply 'encode-time time0))))
16435 ;; Insert the new time-stamp, and ensure point stays in the same
16436 ;; category as before (i.e. not after the last position in that
16437 ;; category).
16438 (let ((pos (point)))
16439 ;; Stay before inserted string. `save-excursion' is of no use.
16440 (setq org-last-changed-timestamp
16441 (org-insert-time-stamp time with-hm inactive nil nil extra))
16442 (goto-char pos))
16443 (save-match-data
16444 (looking-at org-ts-regexp3)
16445 (goto-char (cond
16446 ;; `day' category ends before `hour' if any, or at
16447 ;; the end of the day name.
16448 ((eq origin-cat 'day)
16449 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16450 ((eq origin-cat 'hour) (min (match-end 7) origin))
16451 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16452 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16453 ;; `year' and `month' have both fixed size: point
16454 ;; couldn't have moved into another part.
16455 (t origin))))
16456 ;; Update clock if on a CLOCK line.
16457 (org-clock-update-time-maybe)
16458 ;; Maybe adjust the closest clock in `org-clock-history'
16459 (when org-clock-adjust-closest
16460 (if (not (and (org-at-clock-log-p)
16461 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16462 org-clock-history))))))
16463 (message "No clock to adjust")
16464 (cond ((save-excursion ; fix previous clock?
16465 (re-search-backward org-ts-regexp0 nil t)
16466 (looking-back (concat org-clock-string " \\[")))
16467 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16468 ((save-excursion ; fix next clock?
16469 (re-search-backward org-ts-regexp0 nil t)
16470 (looking-at (concat org-ts-regexp0 "\\] =>")))
16471 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16472 (save-window-excursion
16473 ;; Find closest clock to point, adjust the previous/next one in history
16474 (let* ((p (save-excursion (org-back-to-heading t)))
16475 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16476 (clfixnth
16477 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16478 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16479 (if (not clfixpos)
16480 (message "No clock to adjust")
16481 (org-goto-marker-or-bmk clfixpos)
16482 (org-show-subtree)
16483 (when (re-search-forward clrgx nil t)
16484 (goto-char (match-beginning 1))
16485 (let (org-clock-adjust-closest)
16486 (org-timestamp-change n org-ts-what updown))
16487 (message "Clock adjusted in %s for heading: %s"
16488 (file-name-nondirectory (buffer-file-name))
16489 (org-get-heading t t))))))))
16490 ;; Try to recenter the calendar window, if any.
16491 (if (and org-calendar-follow-timestamp-change
16492 (get-buffer-window "*Calendar*" t)
16493 (memq org-ts-what '(day month year)))
16494 (org-recenter-calendar (time-to-days time))))))
16496 (defun org-modify-ts-extra (s pos n dm)
16497 "Change the different parts of the lead-time and repeat fields in timestamp."
16498 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16499 ng h m new rem)
16500 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16501 (cond
16502 ((or (org-pos-in-match-range pos 2)
16503 (org-pos-in-match-range pos 3))
16504 (setq m (string-to-number (match-string 3 s))
16505 h (string-to-number (match-string 2 s)))
16506 (if (org-pos-in-match-range pos 2)
16507 (setq h (+ h n))
16508 (setq n (* dm (org-no-warnings (signum n))))
16509 (when (not (= 0 (setq rem (% m dm))))
16510 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16511 (setq m (+ m n)))
16512 (if (< m 0) (setq m (+ m 60) h (1- h)))
16513 (if (> m 59) (setq m (- m 60) h (1+ h)))
16514 (setq h (min 24 (max 0 h)))
16515 (setq ng 1 new (format "-%02d:%02d" h m)))
16516 ((org-pos-in-match-range pos 6)
16517 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16518 ((org-pos-in-match-range pos 5)
16519 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16521 ((org-pos-in-match-range pos 9)
16522 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16523 ((org-pos-in-match-range pos 8)
16524 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16526 (when ng
16527 (setq s (concat
16528 (substring s 0 (match-beginning ng))
16530 (substring s (match-end ng))))))
16533 (defun org-recenter-calendar (date)
16534 "If the calendar is visible, recenter it to DATE."
16535 (let ((cwin (get-buffer-window "*Calendar*" t)))
16536 (when cwin
16537 (let ((calendar-move-hook nil))
16538 (with-selected-window cwin
16539 (calendar-goto-date (if (listp date) date
16540 (calendar-gregorian-from-absolute date))))))))
16542 (defun org-goto-calendar (&optional arg)
16543 "Go to the Emacs calendar at the current date.
16544 If there is a time stamp in the current line, go to that date.
16545 A prefix ARG can be used to force the current date."
16546 (interactive "P")
16547 (let ((tsr org-ts-regexp) diff
16548 (calendar-move-hook nil)
16549 (calendar-view-holidays-initially-flag nil)
16550 (calendar-view-diary-initially-flag nil))
16551 (if (or (org-at-timestamp-p)
16552 (save-excursion
16553 (beginning-of-line 1)
16554 (looking-at (concat ".*" tsr))))
16555 (let ((d1 (time-to-days (current-time)))
16556 (d2 (time-to-days
16557 (org-time-string-to-time (match-string 1)))))
16558 (setq diff (- d2 d1))))
16559 (calendar)
16560 (calendar-goto-today)
16561 (if (and diff (not arg)) (calendar-forward-day diff))))
16563 (defun org-get-date-from-calendar ()
16564 "Return a list (month day year) of date at point in calendar."
16565 (with-current-buffer "*Calendar*"
16566 (save-match-data
16567 (calendar-cursor-to-date))))
16569 (defun org-date-from-calendar ()
16570 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16571 If there is already a time stamp at the cursor position, update it."
16572 (interactive)
16573 (if (org-at-timestamp-p t)
16574 (org-timestamp-change 0 'calendar)
16575 (let ((cal-date (org-get-date-from-calendar)))
16576 (org-insert-time-stamp
16577 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16579 (defun org-minutes-to-hh:mm-string (m)
16580 "Compute H:MM from a number of minutes."
16581 (let ((h (/ m 60)))
16582 (setq m (- m (* 60 h)))
16583 (format org-time-clocksum-format h m)))
16585 (defun org-hh:mm-string-to-minutes (s)
16586 "Convert a string H:MM to a number of minutes.
16587 If the string is just a number, interpret it as minutes.
16588 In fact, the first hh:mm or number in the string will be taken,
16589 there can be extra stuff in the string.
16590 If no number is found, the return value is 0."
16591 (cond
16592 ((integerp s) s)
16593 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16594 (+ (* (string-to-number (match-string 1 s)) 60)
16595 (string-to-number (match-string 2 s))))
16596 ((string-match "\\([0-9]+\\)" s)
16597 (string-to-number (match-string 1 s)))
16598 (t 0)))
16600 (defcustom org-effort-durations
16601 `(("h" . 60)
16602 ("d" . ,(* 60 8))
16603 ("w" . ,(* 60 8 5))
16604 ("m" . ,(* 60 8 5 4))
16605 ("y" . ,(* 60 8 5 40)))
16606 "Conversion factor to minutes for an effort modifier.
16608 Each entry has the form (MODIFIER . MINUTES).
16610 In an effort string, a number followed by MODIFIER is multiplied
16611 by the specified number of MINUTES to obtain an effort in
16612 minutes.
16614 For example, if the value of this variable is ((\"hours\" . 60)), then an
16615 effort string \"2hours\" is equivalent to 120 minutes."
16616 :group 'org-agenda
16617 :version "24.1"
16618 :type '(alist :key-type (string :tag "Modifier")
16619 :value-type (number :tag "Minutes")))
16621 (defun org-duration-string-to-minutes (s &optional output-to-string)
16622 "Convert a duration string S to minutes.
16624 A bare number is interpreted as minutes, modifiers can be set by
16625 customizing `org-effort-durations' (which see).
16627 Entries containing a colon are interpreted as H:MM by
16628 `org-hh:mm-string-to-minutes'."
16629 (let ((result 0)
16630 (re (concat "\\([0-9.]+\\) *\\("
16631 (regexp-opt (mapcar 'car org-effort-durations))
16632 "\\)")))
16633 (while (string-match re s)
16634 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16635 (string-to-number (match-string 1 s))))
16636 (setq s (replace-match "" nil t s)))
16637 (setq result (floor result))
16638 (incf result (org-hh:mm-string-to-minutes s))
16639 (if output-to-string (number-to-string result) result)))
16641 ;;;; Files
16643 (defun org-save-all-org-buffers ()
16644 "Save all Org-mode buffers without user confirmation."
16645 (interactive)
16646 (message "Saving all Org-mode buffers...")
16647 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16648 (when (featurep 'org-id) (org-id-locations-save))
16649 (message "Saving all Org-mode buffers... done"))
16651 (defun org-revert-all-org-buffers ()
16652 "Revert all Org-mode buffers.
16653 Prompt for confirmation when there are unsaved changes.
16654 Be sure you know what you are doing before letting this function
16655 overwrite your changes.
16657 This function is useful in a setup where one tracks org files
16658 with a version control system, to revert on one machine after pulling
16659 changes from another. I believe the procedure must be like this:
16661 1. M-x org-save-all-org-buffers
16662 2. Pull changes from the other machine, resolve conflicts
16663 3. M-x org-revert-all-org-buffers"
16664 (interactive)
16665 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16666 (error "Abort"))
16667 (save-excursion
16668 (save-window-excursion
16669 (mapc
16670 (lambda (b)
16671 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16672 (with-current-buffer b buffer-file-name))
16673 (org-pop-to-buffer-same-window b)
16674 (revert-buffer t 'no-confirm)))
16675 (buffer-list))
16676 (when (and (featurep 'org-id) org-id-track-globally)
16677 (org-id-locations-load)))))
16679 ;;;; Agenda files
16681 ;;;###autoload
16682 (defun org-switchb (&optional arg)
16683 "Switch between Org buffers.
16684 With one prefix argument, restrict available buffers to files.
16685 With two prefix arguments, restrict available buffers to agenda files.
16687 Defaults to `iswitchb' for buffer name completion.
16688 Set `org-completion-use-ido' to make it use ido instead."
16689 (interactive "P")
16690 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16691 ((equal arg '(16)) (org-buffer-list 'agenda))
16692 (t (org-buffer-list))))
16693 (org-completion-use-iswitchb org-completion-use-iswitchb)
16694 (org-completion-use-ido org-completion-use-ido))
16695 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16696 (setq org-completion-use-iswitchb t))
16697 (org-pop-to-buffer-same-window
16698 (org-icompleting-read "Org buffer: "
16699 (mapcar 'list (mapcar 'buffer-name blist))
16700 nil t))))
16702 ;;; Define some older names previously used for this functionality
16703 ;;;###autoload
16704 (defalias 'org-ido-switchb 'org-switchb)
16705 ;;;###autoload
16706 (defalias 'org-iswitchb 'org-switchb)
16708 (defun org-buffer-list (&optional predicate exclude-tmp)
16709 "Return a list of Org buffers.
16710 PREDICATE can be `export', `files' or `agenda'.
16712 export restrict the list to Export buffers.
16713 files restrict the list to buffers visiting Org files.
16714 agenda restrict the list to buffers visiting agenda files.
16716 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16717 (let* ((bfn nil)
16718 (agenda-files (and (eq predicate 'agenda)
16719 (mapcar 'file-truename (org-agenda-files t))))
16720 (filter
16721 (cond
16722 ((eq predicate 'files)
16723 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16724 ((eq predicate 'export)
16725 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16726 ((eq predicate 'agenda)
16727 (lambda (b)
16728 (with-current-buffer b
16729 (and (derived-mode-p 'org-mode)
16730 (setq bfn (buffer-file-name b))
16731 (member (file-truename bfn) agenda-files)))))
16732 (t (lambda (b) (with-current-buffer b
16733 (or (derived-mode-p 'org-mode)
16734 (string-match "\*Org .*Export"
16735 (buffer-name b)))))))))
16736 (delq nil
16737 (mapcar
16738 (lambda(b)
16739 (if (and (funcall filter b)
16740 (or (not exclude-tmp)
16741 (not (string-match "tmp" (buffer-name b)))))
16743 nil))
16744 (buffer-list)))))
16746 (defun org-agenda-files (&optional unrestricted archives)
16747 "Get the list of agenda files.
16748 Optional UNRESTRICTED means return the full list even if a restriction
16749 is currently in place.
16750 When ARCHIVES is t, include all archive files that are really being
16751 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16752 `org-agenda-archives-mode' is t."
16753 (let ((files
16754 (cond
16755 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16756 ((stringp org-agenda-files) (org-read-agenda-file-list))
16757 ((listp org-agenda-files) org-agenda-files)
16758 (t (error "Invalid value of `org-agenda-files'")))))
16759 (setq files (apply 'append
16760 (mapcar (lambda (f)
16761 (if (file-directory-p f)
16762 (directory-files
16763 f t org-agenda-file-regexp)
16764 (list f)))
16765 files)))
16766 (when org-agenda-skip-unavailable-files
16767 (setq files (delq nil
16768 (mapcar (function
16769 (lambda (file)
16770 (and (file-readable-p file) file)))
16771 files))))
16772 (when (or (eq archives t)
16773 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16774 (setq files (org-add-archive-files files)))
16775 files))
16777 (defun org-agenda-file-p (&optional file)
16778 "Return non-nil, if FILE is an agenda file.
16779 If FILE is omitted, use the file associated with the current
16780 buffer."
16781 (member (or file (buffer-file-name))
16782 (org-agenda-files t)))
16784 (defun org-edit-agenda-file-list ()
16785 "Edit the list of agenda files.
16786 Depending on setup, this either uses customize to edit the variable
16787 `org-agenda-files', or it visits the file that is holding the list. In the
16788 latter case, the buffer is set up in a way that saving it automatically kills
16789 the buffer and restores the previous window configuration."
16790 (interactive)
16791 (if (stringp org-agenda-files)
16792 (let ((cw (current-window-configuration)))
16793 (find-file org-agenda-files)
16794 (org-set-local 'org-window-configuration cw)
16795 (org-add-hook 'after-save-hook
16796 (lambda ()
16797 (set-window-configuration
16798 (prog1 org-window-configuration
16799 (kill-buffer (current-buffer))))
16800 (org-install-agenda-files-menu)
16801 (message "New agenda file list installed"))
16802 nil 'local)
16803 (message "%s" (substitute-command-keys
16804 "Edit list and finish with \\[save-buffer]")))
16805 (customize-variable 'org-agenda-files)))
16807 (defun org-store-new-agenda-file-list (list)
16808 "Set new value for the agenda file list and save it correctly."
16809 (if (stringp org-agenda-files)
16810 (let ((fe (org-read-agenda-file-list t)) b u)
16811 (while (setq b (find-buffer-visiting org-agenda-files))
16812 (kill-buffer b))
16813 (with-temp-file org-agenda-files
16814 (insert
16815 (mapconcat
16816 (lambda (f) ;; Keep un-expanded entries.
16817 (if (setq u (assoc f fe))
16818 (cdr u)
16820 list "\n")
16821 "\n")))
16822 (let ((org-mode-hook nil) (org-inhibit-startup t)
16823 (org-insert-mode-line-in-empty-file nil))
16824 (setq org-agenda-files list)
16825 (customize-save-variable 'org-agenda-files org-agenda-files))))
16827 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16828 "Read the list of agenda files from a file.
16829 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16830 filenames, used by `org-store-new-agenda-file-list' to write back
16831 un-expanded file names."
16832 (when (file-directory-p org-agenda-files)
16833 (error "`org-agenda-files' cannot be a single directory"))
16834 (when (stringp org-agenda-files)
16835 (with-temp-buffer
16836 (insert-file-contents org-agenda-files)
16837 (mapcar
16838 (lambda (f)
16839 (let ((e (expand-file-name (substitute-in-file-name f)
16840 org-directory)))
16841 (if pair-with-expansion
16842 (cons e f)
16843 e)))
16844 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16846 ;;;###autoload
16847 (defun org-cycle-agenda-files ()
16848 "Cycle through the files in `org-agenda-files'.
16849 If the current buffer visits an agenda file, find the next one in the list.
16850 If the current buffer does not, find the first agenda file."
16851 (interactive)
16852 (let* ((fs (org-agenda-files t))
16853 (files (append fs (list (car fs))))
16854 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16855 file)
16856 (unless files (error "No agenda files"))
16857 (catch 'exit
16858 (while (setq file (pop files))
16859 (if (equal (file-truename file) tcf)
16860 (when (car files)
16861 (find-file (car files))
16862 (throw 'exit t))))
16863 (find-file (car fs)))
16864 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16866 (defun org-agenda-file-to-front (&optional to-end)
16867 "Move/add the current file to the top of the agenda file list.
16868 If the file is not present in the list, it is added to the front. If it is
16869 present, it is moved there. With optional argument TO-END, add/move to the
16870 end of the list."
16871 (interactive "P")
16872 (let ((org-agenda-skip-unavailable-files nil)
16873 (file-alist (mapcar (lambda (x)
16874 (cons (file-truename x) x))
16875 (org-agenda-files t)))
16876 (ctf (file-truename buffer-file-name))
16877 x had)
16878 (setq x (assoc ctf file-alist) had x)
16880 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16881 (if to-end
16882 (setq file-alist (append (delq x file-alist) (list x)))
16883 (setq file-alist (cons x (delq x file-alist))))
16884 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16885 (org-install-agenda-files-menu)
16886 (message "File %s to %s of agenda file list"
16887 (if had "moved" "added") (if to-end "end" "front"))))
16889 (defun org-remove-file (&optional file)
16890 "Remove current file from the list of files in variable `org-agenda-files'.
16891 These are the files which are being checked for agenda entries.
16892 Optional argument FILE means use this file instead of the current."
16893 (interactive)
16894 (let* ((org-agenda-skip-unavailable-files nil)
16895 (file (or file buffer-file-name))
16896 (true-file (file-truename file))
16897 (afile (abbreviate-file-name file))
16898 (files (delq nil (mapcar
16899 (lambda (x)
16900 (if (equal true-file
16901 (file-truename x))
16902 nil x))
16903 (org-agenda-files t)))))
16904 (if (not (= (length files) (length (org-agenda-files t))))
16905 (progn
16906 (org-store-new-agenda-file-list files)
16907 (org-install-agenda-files-menu)
16908 (message "Removed file: %s" afile))
16909 (message "File was not in list: %s (not removed)" afile))))
16911 (defun org-file-menu-entry (file)
16912 (vector file (list 'find-file file) t))
16914 (defun org-check-agenda-file (file)
16915 "Make sure FILE exists. If not, ask user what to do."
16916 (when (not (file-exists-p file))
16917 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16918 (abbreviate-file-name file))
16919 (let ((r (downcase (read-char-exclusive))))
16920 (cond
16921 ((equal r ?r)
16922 (org-remove-file file)
16923 (throw 'nextfile t))
16924 (t (error "Abort"))))))
16926 (defun org-get-agenda-file-buffer (file)
16927 "Get a buffer visiting FILE. If the buffer needs to be created, add
16928 it to the list of buffers which might be released later."
16929 (let ((buf (org-find-base-buffer-visiting file)))
16930 (if buf
16931 buf ; just return it
16932 ;; Make a new buffer and remember it
16933 (setq buf (find-file-noselect file))
16934 (if buf (push buf org-agenda-new-buffers))
16935 buf)))
16937 (defun org-release-buffers (blist)
16938 "Release all buffers in list, asking the user for confirmation when needed.
16939 When a buffer is unmodified, it is just killed. When modified, it is saved
16940 \(if the user agrees) and then killed."
16941 (let (buf file)
16942 (while (setq buf (pop blist))
16943 (setq file (buffer-file-name buf))
16944 (when (and (buffer-modified-p buf)
16945 file
16946 (y-or-n-p (format "Save file %s? " file)))
16947 (with-current-buffer buf (save-buffer)))
16948 (kill-buffer buf))))
16950 (defun org-prepare-agenda-buffers (files)
16951 "Create buffers for all agenda files, protect archived trees and comments."
16952 (interactive)
16953 (let ((pa '(:org-archived t))
16954 (pc '(:org-comment t))
16955 (pall '(:org-archived t :org-comment t))
16956 (inhibit-read-only t)
16957 (rea (concat ":" org-archive-tag ":"))
16958 bmp file re)
16959 (save-excursion
16960 (save-restriction
16961 (while (setq file (pop files))
16962 (catch 'nextfile
16963 (if (bufferp file)
16964 (set-buffer file)
16965 (org-check-agenda-file file)
16966 (set-buffer (org-get-agenda-file-buffer file)))
16967 (widen)
16968 (setq bmp (buffer-modified-p))
16969 (org-refresh-category-properties)
16970 (setq org-todo-keywords-for-agenda
16971 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16972 (setq org-done-keywords-for-agenda
16973 (append org-done-keywords-for-agenda org-done-keywords))
16974 (setq org-todo-keyword-alist-for-agenda
16975 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16976 (setq org-drawers-for-agenda
16977 (append org-drawers-for-agenda org-drawers))
16978 (setq org-tag-alist-for-agenda
16979 (append org-tag-alist-for-agenda org-tag-alist))
16981 (save-excursion
16982 (remove-text-properties (point-min) (point-max) pall)
16983 (when org-agenda-skip-archived-trees
16984 (goto-char (point-min))
16985 (while (re-search-forward rea nil t)
16986 (if (org-at-heading-p t)
16987 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16988 (goto-char (point-min))
16989 (setq re (format org-heading-keyword-regexp-format
16990 org-comment-string))
16991 (while (re-search-forward re nil t)
16992 (add-text-properties
16993 (match-beginning 0) (org-end-of-subtree t) pc)))
16994 (set-buffer-modified-p bmp)))))
16995 (setq org-todo-keywords-for-agenda
16996 (org-uniquify org-todo-keywords-for-agenda))
16997 (setq org-todo-keyword-alist-for-agenda
16998 (org-uniquify org-todo-keyword-alist-for-agenda)
16999 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17001 ;;;; Embedded LaTeX
17003 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17004 "Keymap for the minor `org-cdlatex-mode'.")
17006 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17007 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17008 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17009 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17010 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17012 (defvar org-cdlatex-texmathp-advice-is-done nil
17013 "Flag remembering if we have applied the advice to texmathp already.")
17015 (define-minor-mode org-cdlatex-mode
17016 "Toggle the minor `org-cdlatex-mode'.
17017 This mode supports entering LaTeX environment and math in LaTeX fragments
17018 in Org-mode.
17019 \\{org-cdlatex-mode-map}"
17020 nil " OCDL" nil
17021 (when org-cdlatex-mode
17022 (require 'cdlatex)
17023 (run-hooks 'cdlatex-mode-hook)
17024 (cdlatex-compute-tables))
17025 (unless org-cdlatex-texmathp-advice-is-done
17026 (setq org-cdlatex-texmathp-advice-is-done t)
17027 (defadvice texmathp (around org-math-always-on activate)
17028 "Always return t in org-mode buffers.
17029 This is because we want to insert math symbols without dollars even outside
17030 the LaTeX math segments. If Orgmode thinks that point is actually inside
17031 an embedded LaTeX fragment, let texmathp do its job.
17032 \\[org-cdlatex-mode-map]"
17033 (interactive)
17034 (let (p)
17035 (cond
17036 ((not (derived-mode-p 'org-mode)) ad-do-it)
17037 ((eq this-command 'cdlatex-math-symbol)
17038 (setq ad-return-value t
17039 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17041 (let ((p (org-inside-LaTeX-fragment-p)))
17042 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17043 (setq ad-return-value t
17044 texmathp-why '("Org-mode embedded math" . 0))
17045 (if p ad-do-it)))))))))
17047 (defun turn-on-org-cdlatex ()
17048 "Unconditionally turn on `org-cdlatex-mode'."
17049 (org-cdlatex-mode 1))
17051 (defun org-inside-LaTeX-fragment-p ()
17052 "Test if point is inside a LaTeX fragment.
17053 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17054 sequence appearing also before point.
17055 Even though the matchers for math are configurable, this function assumes
17056 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17057 delimiters are skipped when they have been removed by customization.
17058 The return value is nil, or a cons cell with the delimiter and the
17059 position of this delimiter.
17061 This function does a reasonably good job, but can locally be fooled by
17062 for example currency specifications. For example it will assume being in
17063 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17064 fragments that are properly closed, but during editing, we have to live
17065 with the uncertainty caused by missing closing delimiters. This function
17066 looks only before point, not after."
17067 (catch 'exit
17068 (let ((pos (point))
17069 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17070 (lim (progn
17071 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17072 (point)))
17073 dd-on str (start 0) m re)
17074 (goto-char pos)
17075 (when dodollar
17076 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17077 re (nth 1 (assoc "$" org-latex-regexps)))
17078 (while (string-match re str start)
17079 (cond
17080 ((= (match-end 0) (length str))
17081 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17082 ((= (match-end 0) (- (length str) 5))
17083 (throw 'exit nil))
17084 (t (setq start (match-end 0))))))
17085 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17086 (goto-char pos)
17087 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17088 (and (match-beginning 2) (throw 'exit nil))
17089 ;; count $$
17090 (while (re-search-backward "\\$\\$" lim t)
17091 (setq dd-on (not dd-on)))
17092 (goto-char pos)
17093 (if dd-on (cons "$$" m))))))
17095 (defun org-inside-latex-macro-p ()
17096 "Is point inside a LaTeX macro or its arguments?"
17097 (save-match-data
17098 (org-in-regexp
17099 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17101 (defun org-try-cdlatex-tab ()
17102 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17103 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17104 - inside a LaTeX fragment, or
17105 - after the first word in a line, where an abbreviation expansion could
17106 insert a LaTeX environment."
17107 (when org-cdlatex-mode
17108 (cond
17109 ;; Before any word on the line: No expansion possible.
17110 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17111 ;; Just after first word on the line: Expand it. Make sure it
17112 ;; cannot happen on headlines, though.
17113 ((save-excursion
17114 (skip-chars-backward "a-zA-Z0-9*")
17115 (skip-chars-backward " \t")
17116 (and (bolp) (not (org-at-heading-p))))
17117 (cdlatex-tab) t)
17118 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17120 (defun org-cdlatex-underscore-caret (&optional arg)
17121 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17122 Revert to the normal definition outside of these fragments."
17123 (interactive "P")
17124 (if (org-inside-LaTeX-fragment-p)
17125 (call-interactively 'cdlatex-sub-superscript)
17126 (let (org-cdlatex-mode)
17127 (call-interactively (key-binding (vector last-input-event))))))
17129 (defun org-cdlatex-math-modify (&optional arg)
17130 "Execute `cdlatex-math-modify' in LaTeX fragments.
17131 Revert to the normal definition outside of these fragments."
17132 (interactive "P")
17133 (if (org-inside-LaTeX-fragment-p)
17134 (call-interactively 'cdlatex-math-modify)
17135 (let (org-cdlatex-mode)
17136 (call-interactively (key-binding (vector last-input-event))))))
17138 (defvar org-latex-fragment-image-overlays nil
17139 "List of overlays carrying the images of latex fragments.")
17140 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17142 (defun org-remove-latex-fragment-image-overlays ()
17143 "Remove all overlays with LaTeX fragment images in current buffer."
17144 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17145 (setq org-latex-fragment-image-overlays nil))
17147 (defun org-preview-latex-fragment (&optional subtree)
17148 "Preview the LaTeX fragment at point, or all locally or globally.
17149 If the cursor is in a LaTeX fragment, create the image and overlay
17150 it over the source code. If there is no fragment at point, display
17151 all fragments in the current text, from one headline to the next. With
17152 prefix SUBTREE, display all fragments in the current subtree. With a
17153 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17154 the cursor is before the first headline,
17155 display all fragments in the buffer.
17156 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17157 (interactive "P")
17158 (unless buffer-file-name
17159 (error "Can't preview LaTeX fragment in a non-file buffer"))
17160 (org-remove-latex-fragment-image-overlays)
17161 (save-excursion
17162 (save-restriction
17163 (let (beg end at msg)
17164 (cond
17165 ((or (equal subtree '(16))
17166 (not (save-excursion
17167 (re-search-backward org-outline-regexp-bol nil t))))
17168 (setq beg (point-min) end (point-max)
17169 msg "Creating images for buffer...%s"))
17170 ((equal subtree '(4))
17171 (org-back-to-heading)
17172 (setq beg (point) end (org-end-of-subtree t)
17173 msg "Creating images for subtree...%s"))
17175 (if (setq at (org-inside-LaTeX-fragment-p))
17176 (goto-char (max (point-min) (- (cdr at) 2)))
17177 (org-back-to-heading))
17178 (setq beg (point) end (progn (outline-next-heading) (point))
17179 msg (if at "Creating image...%s"
17180 "Creating images for entry...%s"))))
17181 (message msg "")
17182 (narrow-to-region beg end)
17183 (goto-char beg)
17184 (org-format-latex
17185 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17186 (file-name-nondirectory
17187 buffer-file-name)))
17188 default-directory 'overlays msg at 'forbuffer
17189 org-latex-create-formula-image-program)
17190 (message msg "done. Use `C-c C-c' to remove images.")))))
17192 (defvar org-latex-regexps
17193 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17194 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17195 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17196 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17197 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17198 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17199 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17200 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17201 "Regular expressions for matching embedded LaTeX.")
17203 (defvar org-export-have-math nil) ;; dynamic scoping
17204 (defun org-format-latex (prefix &optional dir overlays msg at
17205 forbuffer processing-type)
17206 "Replace LaTeX fragments with links to an image, and produce images.
17207 Some of the options can be changed using the variable
17208 `org-format-latex-options'."
17209 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17210 (let* ((prefixnodir (file-name-nondirectory prefix))
17211 (absprefix (expand-file-name prefix dir))
17212 (todir (file-name-directory absprefix))
17213 (opt org-format-latex-options)
17214 (matchers (plist-get opt :matchers))
17215 (re-list org-latex-regexps)
17216 (org-format-latex-header-extra
17217 (plist-get (org-infile-export-plist) :latex-header-extra))
17218 (cnt 0) txt hash link beg end re e checkdir
17219 executables-checked string
17220 m n block-type block linkfile movefile ov)
17221 ;; Check the different regular expressions
17222 (while (setq e (pop re-list))
17223 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17224 block (if block-type "\n\n" ""))
17225 (when (member m matchers)
17226 (goto-char (point-min))
17227 (while (re-search-forward re nil t)
17228 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17229 (not (get-text-property (match-beginning n)
17230 'org-protected))
17231 (or (not overlays)
17232 (not (eq (get-char-property (match-beginning n)
17233 'org-overlay-type)
17234 'org-latex-overlay))))
17235 (setq org-export-have-math t)
17236 (cond
17237 ((eq processing-type 'verbatim)
17238 ;; Leave the text verbatim, just protect it
17239 (add-text-properties (match-beginning n) (match-end n)
17240 '(org-protected t)))
17241 ((eq processing-type 'mathjax)
17242 ;; Prepare for MathJax processing
17243 (setq string (match-string n))
17244 (if (member m '("$" "$1"))
17245 (save-excursion
17246 (delete-region (match-beginning n) (match-end n))
17247 (goto-char (match-beginning n))
17248 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17249 "\\)")
17250 '(org-protected t))))
17251 (add-text-properties (match-beginning n) (match-end n)
17252 '(org-protected t))))
17253 ((or (eq processing-type 'dvipng)
17254 (eq processing-type 'imagemagick))
17255 ;; Process to an image
17256 (setq txt (match-string n)
17257 beg (match-beginning n) end (match-end n)
17258 cnt (1+ cnt))
17259 (let (print-length print-level) ; make sure full list is printed
17260 (setq hash (sha1 (prin1-to-string
17261 (list org-format-latex-header
17262 org-format-latex-header-extra
17263 org-export-latex-default-packages-alist
17264 org-export-latex-packages-alist
17265 org-format-latex-options
17266 forbuffer txt)))
17267 linkfile (format "%s_%s.png" prefix hash)
17268 movefile (format "%s_%s.png" absprefix hash)))
17269 (setq link (concat block "[[file:" linkfile "]]" block))
17270 (if msg (message msg cnt))
17271 (goto-char beg)
17272 (unless checkdir ; make sure the directory exists
17273 (setq checkdir t)
17274 (or (file-directory-p todir) (make-directory todir t)))
17275 (cond
17276 ((eq processing-type 'dvipng)
17277 (unless executables-checked
17278 (org-check-external-command
17279 "latex" "needed to convert LaTeX fragments to images")
17280 (org-check-external-command
17281 "dvipng" "needed to convert LaTeX fragments to images")
17282 (setq executables-checked t))
17283 (unless (file-exists-p movefile)
17284 (org-create-formula-image-with-dvipng
17285 txt movefile opt forbuffer)))
17286 ((eq processing-type 'imagemagick)
17287 (unless executables-checked
17288 (org-check-external-command
17289 "convert" "you need to install imagemagick")
17290 (setq executables-checked t))
17291 (unless (file-exists-p movefile)
17292 (org-create-formula-image-with-imagemagick
17293 txt movefile opt forbuffer))))
17294 (if overlays
17295 (progn
17296 (mapc (lambda (o)
17297 (if (eq (overlay-get o 'org-overlay-type)
17298 'org-latex-overlay)
17299 (delete-overlay o)))
17300 (overlays-in beg end))
17301 (setq ov (make-overlay beg end))
17302 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17303 (if (featurep 'xemacs)
17304 (progn
17305 (overlay-put ov 'invisible t)
17306 (overlay-put
17307 ov 'end-glyph
17308 (make-glyph (vector 'png :file movefile))))
17309 (overlay-put
17310 ov 'display
17311 (list 'image :type 'png :file movefile :ascent 'center)))
17312 (push ov org-latex-fragment-image-overlays)
17313 (goto-char end))
17314 (delete-region beg end)
17315 (insert (org-add-props link
17316 (list 'org-latex-src
17317 (replace-regexp-in-string
17318 "\"" "" txt)
17319 'org-latex-src-embed-type
17320 (if block-type 'paragraph 'character))))))
17321 ((eq processing-type 'mathml)
17322 ;; Process to MathML
17323 (unless executables-checked
17324 (unless (save-match-data (org-format-latex-mathml-available-p))
17325 (error "LaTeX to MathML converter not configured"))
17326 (setq executables-checked t))
17327 (setq txt (match-string n)
17328 beg (match-beginning n) end (match-end n)
17329 cnt (1+ cnt))
17330 (if msg (message msg cnt))
17331 (goto-char beg)
17332 (delete-region beg end)
17333 (insert (org-format-latex-as-mathml
17334 txt block-type prefix dir)))
17336 (error "Unknown conversion type %s for latex fragments"
17337 processing-type)))))))))
17339 (defun org-create-math-formula (latex-frag &optional mathml-file)
17340 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17341 Use `org-latex-to-mathml-convert-command'. If the conversion is
17342 sucessful, return the portion between \"<math...> </math>\"
17343 elements otherwise return nil. When MATHML-FILE is specified,
17344 write the results in to that file. When invoked as an
17345 interactive command, prompt for LATEX-FRAG, with initial value
17346 set to the current active region and echo the results for user
17347 inspection."
17348 (interactive (list (let ((frag (when (region-active-p)
17349 (buffer-substring-no-properties
17350 (region-beginning) (region-end)))))
17351 (read-string "LaTeX Fragment: " frag nil frag))))
17352 (unless latex-frag (error "Invalid latex-frag"))
17353 (let* ((tmp-in-file (file-relative-name
17354 (make-temp-name (expand-file-name "ltxmathml-in"))))
17355 (ignore (write-region latex-frag nil tmp-in-file))
17356 (tmp-out-file (file-relative-name
17357 (make-temp-name (expand-file-name "ltxmathml-out"))))
17358 (cmd (format-spec
17359 org-latex-to-mathml-convert-command
17360 `((?j . ,(shell-quote-argument
17361 (expand-file-name org-latex-to-mathml-jar-file)))
17362 (?I . ,(shell-quote-argument tmp-in-file))
17363 (?o . ,(shell-quote-argument tmp-out-file)))))
17364 mathml shell-command-output)
17365 (when (org-called-interactively-p 'any)
17366 (unless (org-format-latex-mathml-available-p)
17367 (error "LaTeX to MathML converter not configured")))
17368 (message "Running %s" cmd)
17369 (setq shell-command-output (shell-command-to-string cmd))
17370 (setq mathml
17371 (when (file-readable-p tmp-out-file)
17372 (with-current-buffer (find-file-noselect tmp-out-file t)
17373 (goto-char (point-min))
17374 (when (re-search-forward
17375 (concat
17376 (regexp-quote
17377 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17378 "\\(.\\|\n\\)*"
17379 (regexp-quote "</math>")) nil t)
17380 (prog1 (match-string 0) (kill-buffer))))))
17381 (cond
17382 (mathml
17383 (setq mathml
17384 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17385 (when mathml-file
17386 (write-region mathml nil mathml-file))
17387 (when (org-called-interactively-p 'any)
17388 (message mathml)))
17389 ((message "LaTeX to MathML conversion failed")
17390 (message shell-command-output)))
17391 (delete-file tmp-in-file)
17392 (when (file-exists-p tmp-out-file)
17393 (delete-file tmp-out-file))
17394 mathml))
17396 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17397 prefix &optional dir)
17398 "Use `org-create-math-formula' but check local cache first."
17399 (let* ((absprefix (expand-file-name prefix dir))
17400 (print-length nil) (print-level nil)
17401 (formula-id (concat
17402 "formula-"
17403 (sha1
17404 (prin1-to-string
17405 (list latex-frag
17406 org-latex-to-mathml-convert-command)))))
17407 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17408 (formula-cache-dir (file-name-directory formula-cache)))
17410 (unless (file-directory-p formula-cache-dir)
17411 (make-directory formula-cache-dir t))
17413 (unless (file-exists-p formula-cache)
17414 (org-create-math-formula latex-frag formula-cache))
17416 (if (file-exists-p formula-cache)
17417 ;; Successful conversion. Return the link to MathML file.
17418 (org-add-props
17419 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17420 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17421 'org-latex-src-embed-type (if latex-frag-type
17422 'paragraph 'character)))
17423 ;; Failed conversion. Return the LaTeX fragment verbatim
17424 (add-text-properties
17425 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17426 latex-frag)))
17428 ;; This function borrows from Ganesh Swami's latex2png.el
17429 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17430 "This calls dvipng."
17431 (require 'org-latex)
17432 (let* ((tmpdir (if (featurep 'xemacs)
17433 (temp-directory)
17434 temporary-file-directory))
17435 (texfilebase (make-temp-name
17436 (expand-file-name "orgtex" tmpdir)))
17437 (texfile (concat texfilebase ".tex"))
17438 (dvifile (concat texfilebase ".dvi"))
17439 (pngfile (concat texfilebase ".png"))
17440 (fnh (if (featurep 'xemacs)
17441 (font-height (face-font 'default))
17442 (face-attribute 'default :height nil)))
17443 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17444 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17445 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17446 "Black"))
17447 (bg (or (plist-get options (if buffer :background :html-background))
17448 "Transparent")))
17449 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17450 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17451 (with-temp-file texfile
17452 (insert (org-splice-latex-header
17453 org-format-latex-header
17454 org-export-latex-default-packages-alist
17455 org-export-latex-packages-alist t
17456 org-format-latex-header-extra))
17457 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17458 (require 'org-latex)
17459 (org-export-latex-fix-inputenc))
17460 (let ((dir default-directory))
17461 (condition-case nil
17462 (progn
17463 (cd tmpdir)
17464 (call-process "latex" nil nil nil texfile))
17465 (error nil))
17466 (cd dir))
17467 (if (not (file-exists-p dvifile))
17468 (progn (message "Failed to create dvi file from %s" texfile) nil)
17469 (condition-case nil
17470 (if (featurep 'xemacs)
17471 (call-process "dvipng" nil nil nil
17472 "-fg" fg "-bg" bg
17473 "-T" "tight"
17474 "-o" pngfile
17475 dvifile)
17476 (call-process "dvipng" nil nil nil
17477 "-fg" fg "-bg" bg
17478 "-D" dpi
17479 ;;"-x" scale "-y" scale
17480 "-T" "tight"
17481 "-o" pngfile
17482 dvifile))
17483 (error nil))
17484 (if (not (file-exists-p pngfile))
17485 (if org-format-latex-signal-error
17486 (error "Failed to create png file from %s" texfile)
17487 (message "Failed to create png file from %s" texfile)
17488 nil)
17489 ;; Use the requested file name and clean up
17490 (copy-file pngfile tofile 'replace)
17491 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17492 (if (file-exists-p (concat texfilebase e))
17493 (delete-file (concat texfilebase e))))
17494 pngfile))))
17496 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17497 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17498 "This calls convert, which is included into imagemagick."
17499 (require 'org-latex)
17500 (let* ((tmpdir (if (featurep 'xemacs)
17501 (temp-directory)
17502 temporary-file-directory))
17503 (texfilebase (make-temp-name
17504 (expand-file-name "orgtex" tmpdir)))
17505 (texfile (concat texfilebase ".tex"))
17506 (pdffile (concat texfilebase ".pdf"))
17507 (pngfile (concat texfilebase ".png"))
17508 (fnh (if (featurep 'xemacs)
17509 (font-height (face-font 'default))
17510 (face-attribute 'default :height nil)))
17511 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17512 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17513 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17514 "black"))
17515 (bg (or (plist-get options (if buffer :background :html-background))
17516 "white")))
17517 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17518 (setq fg (org-latex-color-format fg)))
17519 (if (eq bg 'default) (setq bg (org-latex-color :background))
17520 (setq bg (org-latex-color-format
17521 (if (string= bg "Transparent")(setq bg "white")))))
17522 (with-temp-file texfile
17523 (insert (org-splice-latex-header
17524 org-format-latex-header
17525 org-export-latex-default-packages-alist
17526 org-export-latex-packages-alist t
17527 org-format-latex-header-extra))
17528 (insert "\n\\begin{document}\n"
17529 "\\definecolor{fg}{rgb}{" fg "}\n"
17530 "\\definecolor{bg}{rgb}{" bg "}\n"
17531 "\n\\pagecolor{bg}\n"
17532 "\n{\\color{fg}\n"
17533 string
17534 "\n}\n"
17535 "\n\\end{document}\n" )
17536 (require 'org-latex)
17537 (org-export-latex-fix-inputenc))
17538 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17539 (condition-case nil
17540 (progn
17541 (cd tmpdir)
17542 (setq cmds org-latex-to-pdf-process)
17543 (while cmds
17544 (setq latex-frags-cmds (pop cmds))
17545 (if (listp latex-frags-cmds)
17546 (setq cmds nil)
17547 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17548 (while latex-frags-cmds
17549 (setq cmd (pop latex-frags-cmds))
17550 (while (string-match "%b" cmd)
17551 (setq cmd (replace-match
17552 (save-match-data
17553 (shell-quote-argument texfile))
17554 t t cmd)))
17555 (while (string-match "%f" cmd)
17556 (setq cmd (replace-match
17557 (save-match-data
17558 (shell-quote-argument (file-name-nondirectory texfile)))
17559 t t cmd)))
17560 (while (string-match "%o" cmd)
17561 (setq cmd (replace-match
17562 (save-match-data
17563 (shell-quote-argument (file-name-directory texfile)))
17564 t t cmd)))
17565 (setq cmd (split-string cmd))
17566 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17567 (error nil))
17568 (cd dir))
17569 (if (not (file-exists-p pdffile))
17570 (progn (message "Failed to create pdf file from %s" texfile) nil)
17571 (condition-case nil
17572 (if (featurep 'xemacs)
17573 (call-process "convert" nil nil nil
17574 "-density" "96"
17575 "-trim"
17576 "-antialias"
17577 pdffile
17578 "-quality" "100"
17579 ;; "-sharpen" "0x1.0"
17580 pngfile)
17581 (call-process "convert" nil nil nil
17582 "-density" dpi
17583 "-trim"
17584 "-antialias"
17585 pdffile
17586 "-quality" "100"
17587 ; "-sharpen" "0x1.0"
17588 pngfile))
17589 (error nil))
17590 (if (not (file-exists-p pngfile))
17591 (if org-format-latex-signal-error
17592 (error "Failed to create png file from %s" texfile)
17593 (message "Failed to create png file from %s" texfile)
17594 nil)
17595 ;; Use the requested file name and clean up
17596 (copy-file pngfile tofile 'replace)
17597 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17598 (if (file-exists-p (concat texfilebase e))
17599 (delete-file (concat texfilebase e))))
17600 pngfile))))
17602 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17603 "Fill a LaTeX header template TPL.
17604 In the template, the following place holders will be recognized:
17606 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17607 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17608 [PACKAGES] \\usepackage statements for PKG
17609 [NO-PACKAGES] do not include PKG
17610 [EXTRA] the string EXTRA
17611 [NO-EXTRA] do not include EXTRA
17613 For backward compatibility, if both the positive and the negative place
17614 holder is missing, the positive one (without the \"NO-\") will be
17615 assumed to be present at the end of the template.
17616 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17617 EXTRA is a string.
17618 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17619 (let (rpl (end ""))
17620 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17621 (setq rpl (if (or (match-end 1) (not def-pkg))
17622 "" (org-latex-packages-to-string def-pkg snippets-p t))
17623 tpl (replace-match rpl t t tpl))
17624 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17626 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17627 (setq rpl (if (or (match-end 1) (not pkg))
17628 "" (org-latex-packages-to-string pkg snippets-p t))
17629 tpl (replace-match rpl t t tpl))
17630 (if pkg (setq end
17631 (concat end "\n"
17632 (org-latex-packages-to-string pkg snippets-p)))))
17634 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17635 (setq rpl (if (or (match-end 1) (not extra))
17636 "" (concat extra "\n"))
17637 tpl (replace-match rpl t t tpl))
17638 (if (and extra (string-match "\\S-" extra))
17639 (setq end (concat end "\n" extra))))
17641 (if (string-match "\\S-" end)
17642 (concat tpl "\n" end)
17643 tpl)))
17645 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17646 "Turn an alist of packages into a string with the \\usepackage macros."
17647 (setq pkg (mapconcat (lambda(p)
17648 (cond
17649 ((stringp p) p)
17650 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17651 (format "%% Package %s omitted" (cadr p)))
17652 ((equal "" (car p))
17653 (format "\\usepackage{%s}" (cadr p)))
17655 (format "\\usepackage[%s]{%s}"
17656 (car p) (cadr p)))))
17658 "\n"))
17659 (if newline (concat pkg "\n") pkg))
17661 (defun org-dvipng-color (attr)
17662 "Return a RGB color specification for dvipng."
17663 (apply 'format "rgb %s %s %s"
17664 (mapcar 'org-normalize-color
17665 (if (featurep 'xemacs)
17666 (color-rgb-components
17667 (face-property 'default
17668 (cond ((eq attr :foreground) 'foreground)
17669 ((eq attr :background) 'background))))
17670 (color-values (face-attribute 'default attr nil))))))
17672 (defun org-latex-color (attr)
17673 "Return a RGB color for the LaTeX color package."
17674 (apply 'format "%s,%s,%s"
17675 (mapcar 'org-normalize-color
17676 (if (featurep 'xemacs)
17677 (color-rgb-components
17678 (face-property 'default
17679 (cond ((eq attr :foreground) 'foreground)
17680 ((eq attr :background) 'background))))
17681 (color-values (face-attribute 'default attr nil))))))
17683 (defun org-latex-color-format (color-name)
17684 "Convert COLOR-NAME to a RGB color value."
17685 (apply 'format "%s,%s,%s"
17686 (mapcar 'org-normalize-color
17687 (color-values color-name))))
17689 (defun org-normalize-color (value)
17690 "Return string to be used as color value for an RGB component."
17691 (format "%g" (/ value 65535.0)))
17693 ;; Image display
17696 (defvar org-inline-image-overlays nil)
17697 (make-variable-buffer-local 'org-inline-image-overlays)
17699 (defun org-toggle-inline-images (&optional include-linked)
17700 "Toggle the display of inline images.
17701 INCLUDE-LINKED is passed to `org-display-inline-images'."
17702 (interactive "P")
17703 (if org-inline-image-overlays
17704 (progn
17705 (org-remove-inline-images)
17706 (message "Inline image display turned off"))
17707 (org-display-inline-images include-linked)
17708 (if org-inline-image-overlays
17709 (message "%d images displayed inline"
17710 (length org-inline-image-overlays))
17711 (message "No images to display inline"))))
17713 (defun org-display-inline-images (&optional include-linked refresh beg end)
17714 "Display inline images.
17715 Normally only links without a description part are inlined, because this
17716 is how it will work for export. When INCLUDE-LINKED is set, also links
17717 with a description part will be inlined. This can be nice for a quick
17718 look at those images, but it does not reflect what exported files will look
17719 like.
17720 When REFRESH is set, refresh existing images between BEG and END.
17721 This will create new image displays only if necessary.
17722 BEG and END default to the buffer boundaries."
17723 (interactive "P")
17724 (unless refresh
17725 (org-remove-inline-images)
17726 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17727 (save-excursion
17728 (save-restriction
17729 (widen)
17730 (setq beg (or beg (point-min)) end (or end (point-max)))
17731 (goto-char beg)
17732 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17733 (substring (org-image-file-name-regexp) 0 -2)
17734 "\\)\\]" (if include-linked "" "\\]")))
17735 old file ov img)
17736 (while (re-search-forward re end t)
17737 (setq old (get-char-property-and-overlay (match-beginning 1)
17738 'org-image-overlay))
17739 (setq file (expand-file-name
17740 (concat (or (match-string 3) "") (match-string 4))))
17741 (when (file-exists-p file)
17742 (if (and (car-safe old) refresh)
17743 (image-refresh (overlay-get (cdr old) 'display))
17744 (setq img (save-match-data (create-image file)))
17745 (when img
17746 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17747 (overlay-put ov 'display img)
17748 (overlay-put ov 'face 'default)
17749 (overlay-put ov 'org-image-overlay t)
17750 (overlay-put ov 'modification-hooks
17751 (list 'org-display-inline-modification-hook))
17752 (push ov org-inline-image-overlays)))))))))
17754 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17755 "Remove inline-display overlay if a corresponding region is modified."
17756 (let ((inhibit-modification-hooks t))
17757 (when (and ov after)
17758 (delete ov org-inline-image-overlays)
17759 (delete-overlay ov))))
17761 (defun org-remove-inline-images ()
17762 "Remove inline display of images."
17763 (interactive)
17764 (mapc 'delete-overlay org-inline-image-overlays)
17765 (setq org-inline-image-overlays nil))
17767 ;;;; Key bindings
17769 ;; Outline functions from `outline-mode-prefix-map'
17770 ;; that can be remapped in Org:
17771 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17772 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17773 (define-key org-mode-map [remap outline-forward-same-level]
17774 'org-forward-heading-same-level)
17775 (define-key org-mode-map [remap outline-backward-same-level]
17776 'org-backward-heading-same-level)
17777 (define-key org-mode-map [remap show-branches]
17778 'org-kill-note-or-show-branches)
17779 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17780 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17781 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17783 ;; Outline functions from `outline-mode-prefix-map' that can not
17784 ;; be remapped in Org:
17786 ;; - the column "key binding" shows whether the Outline function is still
17787 ;; available in Org mode on the same key that it has been bound to in
17788 ;; Outline mode:
17789 ;; - "overridden": key used for a different functionality in Org mode
17790 ;; - else: key still bound to the same Outline function in Org mode
17792 ;; | Outline function | key binding | Org replacement |
17793 ;; |------------------------------------+-------------+-----------------------|
17794 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17795 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17796 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17797 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17798 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17799 ;; | `show-entry' | overridden | no replacement |
17800 ;; | `show-children' | `C-c C-i' | visibility cycling |
17801 ;; | `show-branches' | `C-c C-k' | still same function |
17802 ;; | `show-subtree' | overridden | visibility cycling |
17803 ;; | `show-all' | overridden | no replacement |
17804 ;; | `hide-subtree' | overridden | visibility cycling |
17805 ;; | `hide-body' | overridden | no replacement |
17806 ;; | `hide-entry' | overridden | visibility cycling |
17807 ;; | `hide-leaves' | overridden | no replacement |
17808 ;; | `hide-sublevels' | overridden | no replacement |
17809 ;; | `hide-other' | overridden | no replacement |
17811 ;; Make `C-c C-x' a prefix key
17812 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17814 ;; TAB key with modifiers
17815 (org-defkey org-mode-map "\C-i" 'org-cycle)
17816 (org-defkey org-mode-map [(tab)] 'org-cycle)
17817 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17818 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17819 ;; The following line is necessary under Suse GNU/Linux
17820 (unless (featurep 'xemacs)
17821 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17822 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17823 (define-key org-mode-map [backtab] 'org-shifttab)
17825 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17826 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17827 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17829 ;; Cursor keys with modifiers
17830 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17831 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17832 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17833 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17835 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17836 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17837 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17838 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17840 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17841 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17842 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17843 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17845 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17846 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17847 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17848 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17850 ;; Babel keys
17851 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17852 (mapc (lambda (pair)
17853 (define-key org-babel-map (car pair) (cdr pair)))
17854 org-babel-key-bindings)
17856 ;;; Extra keys for tty access.
17857 ;; We only set them when really needed because otherwise the
17858 ;; menus don't show the simple keys
17860 (when (or org-use-extra-keys
17861 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17862 (not window-system))
17863 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17864 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17865 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17866 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17867 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17868 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17869 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17870 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17871 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17872 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17873 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17874 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17875 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17876 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17877 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17878 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17879 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17880 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17881 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17882 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17883 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17884 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17885 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17886 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17887 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17888 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17889 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17890 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17892 ;; All the other keys
17894 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17895 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17896 (if (boundp 'narrow-map)
17897 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17898 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17899 (if (boundp 'narrow-map)
17900 (org-defkey narrow-map "b" 'org-narrow-to-block)
17901 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17902 (if (boundp 'narrow-map)
17903 (org-defkey narrow-map "e" 'org-narrow-to-element)
17904 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17905 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17906 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17907 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17908 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17909 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17910 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17911 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17912 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17913 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17914 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17915 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17916 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17917 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17918 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17919 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17920 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17921 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17922 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17923 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17924 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17925 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17926 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17927 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17928 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17929 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17930 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17931 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17932 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17933 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17934 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17935 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17936 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17937 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17938 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17939 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17940 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17941 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17942 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17943 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17944 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17945 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17946 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17947 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17948 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17949 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17950 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17951 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17952 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17953 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17954 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17955 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17956 (org-defkey org-mode-map "\C-c^" 'org-sort)
17957 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17958 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17959 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17960 (org-defkey org-mode-map "\C-m" 'org-return)
17961 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17962 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17963 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17964 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17965 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17966 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17967 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17968 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17969 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17970 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17971 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17972 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17973 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17974 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17975 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17976 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17977 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17978 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17979 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17980 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17981 (org-defkey org-mode-map "\M-h" 'org-mark-element)
17982 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17983 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17985 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17986 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17987 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17988 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17990 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17991 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17992 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17993 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
17994 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17995 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17996 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17997 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17998 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17999 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18000 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18001 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18002 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18003 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18004 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18005 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18006 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18007 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18008 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18009 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18010 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18012 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18013 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18014 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18015 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18016 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18018 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18020 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18022 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18023 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18025 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18028 (when (featurep 'xemacs)
18029 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18032 (defconst org-speed-commands-default
18034 ("Outline Navigation")
18035 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18036 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18037 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18038 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18039 ("u" . (org-speed-move-safe 'outline-up-heading))
18040 ("j" . org-goto)
18041 ("g" . (org-refile t))
18042 ("Outline Visibility")
18043 ("c" . org-cycle)
18044 ("C" . org-shifttab)
18045 (" " . org-display-outline-path)
18046 (":" . org-columns)
18047 ("Outline Structure Editing")
18048 ("U" . org-shiftmetaup)
18049 ("D" . org-shiftmetadown)
18050 ("r" . org-metaright)
18051 ("l" . org-metaleft)
18052 ("R" . org-shiftmetaright)
18053 ("L" . org-shiftmetaleft)
18054 ("i" . (progn (forward-char 1) (call-interactively
18055 'org-insert-heading-respect-content)))
18056 ("^" . org-sort)
18057 ("w" . org-refile)
18058 ("a" . org-archive-subtree-default-with-confirmation)
18059 ("." . org-mark-subtree)
18060 ("#" . org-toggle-comment)
18061 ("Clock Commands")
18062 ("I" . org-clock-in)
18063 ("O" . org-clock-out)
18064 ("Meta Data Editing")
18065 ("t" . org-todo)
18066 ("0" . (org-priority ?\ ))
18067 ("1" . (org-priority ?A))
18068 ("2" . (org-priority ?B))
18069 ("3" . (org-priority ?C))
18070 (";" . org-set-tags-command)
18071 ("e" . org-set-effort)
18072 ("E" . org-inc-effort)
18073 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18074 (org-entry-put (point) "APPT_WARNTIME" m)))
18075 ("Agenda Views etc")
18076 ("v" . org-agenda)
18077 ("/" . org-sparse-tree)
18078 ("Misc")
18079 ("o" . org-open-at-point)
18080 ("?" . org-speed-command-help)
18081 ("<" . (org-agenda-set-restriction-lock 'subtree))
18082 (">" . (org-agenda-remove-restriction-lock))
18084 "The default speed commands.")
18086 (defun org-print-speed-command (e)
18087 (if (> (length (car e)) 1)
18088 (progn
18089 (princ "\n")
18090 (princ (car e))
18091 (princ "\n")
18092 (princ (make-string (length (car e)) ?-))
18093 (princ "\n"))
18094 (princ (car e))
18095 (princ " ")
18096 (if (symbolp (cdr e))
18097 (princ (symbol-name (cdr e)))
18098 (prin1 (cdr e)))
18099 (princ "\n")))
18101 (defun org-speed-command-help ()
18102 "Show the available speed commands."
18103 (interactive)
18104 (if (not org-use-speed-commands)
18105 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18106 (with-output-to-temp-buffer "*Help*"
18107 (princ "User-defined Speed commands\n===========================\n")
18108 (mapc 'org-print-speed-command org-speed-commands-user)
18109 (princ "\n")
18110 (princ "Built-in Speed commands\n=======================\n")
18111 (mapc 'org-print-speed-command org-speed-commands-default))
18112 (with-current-buffer "*Help*"
18113 (setq truncate-lines t))))
18115 (defun org-speed-move-safe (cmd)
18116 "Execute CMD, but make sure that the cursor always ends up in a headline.
18117 If not, return to the original position and throw an error."
18118 (interactive)
18119 (let ((pos (point)))
18120 (call-interactively cmd)
18121 (unless (and (bolp) (org-at-heading-p))
18122 (goto-char pos)
18123 (error "Boundary reached while executing %s" cmd))))
18125 (defvar org-self-insert-command-undo-counter 0)
18127 (defvar org-table-auto-blank-field) ; defined in org-table.el
18128 (defvar org-speed-command nil)
18130 (defun org-speed-command-default-hook (keys)
18131 "Hook for activating single-letter speed commands.
18132 `org-speed-commands-default' specifies a minimal command set.
18133 Use `org-speed-commands-user' for further customization."
18134 (when (or (and (bolp) (looking-at org-outline-regexp))
18135 (and (functionp org-use-speed-commands)
18136 (funcall org-use-speed-commands)))
18137 (cdr (assoc keys (append org-speed-commands-user
18138 org-speed-commands-default)))))
18140 (defun org-babel-speed-command-hook (keys)
18141 "Hook for activating single-letter code block commands."
18142 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18143 (cdr (assoc keys org-babel-key-bindings))))
18145 (defcustom org-speed-command-hook
18146 '(org-speed-command-default-hook org-babel-speed-command-hook)
18147 "Hook for activating speed commands at strategic locations.
18148 Hook functions are called in sequence until a valid handler is
18149 found.
18151 Each hook takes a single argument, a user-pressed command key
18152 which is also a `self-insert-command' from the global map.
18154 Within the hook, examine the cursor position and the command key
18155 and return nil or a valid handler as appropriate. Handler could
18156 be one of an interactive command, a function, or a form.
18158 Set `org-use-speed-commands' to non-nil value to enable this
18159 hook. The default setting is `org-speed-command-default-hook'."
18160 :group 'org-structure
18161 :version "24.1"
18162 :type 'hook)
18164 (defun org-self-insert-command (N)
18165 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18166 If the cursor is in a table looking at whitespace, the whitespace is
18167 overwritten, and the table is not marked as requiring realignment."
18168 (interactive "p")
18169 (org-check-before-invisible-edit 'insert)
18170 (cond
18171 ((and org-use-speed-commands
18172 (setq org-speed-command
18173 (run-hook-with-args-until-success
18174 'org-speed-command-hook (this-command-keys))))
18175 (cond
18176 ((commandp org-speed-command)
18177 (setq this-command org-speed-command)
18178 (call-interactively org-speed-command))
18179 ((functionp org-speed-command)
18180 (funcall org-speed-command))
18181 ((and org-speed-command (listp org-speed-command))
18182 (eval org-speed-command))
18183 (t (let (org-use-speed-commands)
18184 (call-interactively 'org-self-insert-command)))))
18185 ((and
18186 (org-table-p)
18187 (progn
18188 ;; check if we blank the field, and if that triggers align
18189 (and (featurep 'org-table) org-table-auto-blank-field
18190 (member last-command
18191 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18192 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18193 ;; got extra space, this field does not determine column width
18194 (let (org-table-may-need-update) (org-table-blank-field))
18195 ;; no extra space, this field may determine column width
18196 (org-table-blank-field)))
18198 (eq N 1)
18199 (looking-at "[^|\n]* |"))
18200 (let (org-table-may-need-update)
18201 (goto-char (1- (match-end 0)))
18202 (backward-delete-char 1)
18203 (goto-char (match-beginning 0))
18204 (self-insert-command N)))
18206 (setq org-table-may-need-update t)
18207 (self-insert-command N)
18208 (org-fix-tags-on-the-fly)
18209 (if org-self-insert-cluster-for-undo
18210 (if (not (eq last-command 'org-self-insert-command))
18211 (setq org-self-insert-command-undo-counter 1)
18212 (if (>= org-self-insert-command-undo-counter 20)
18213 (setq org-self-insert-command-undo-counter 1)
18214 (and (> org-self-insert-command-undo-counter 0)
18215 buffer-undo-list (listp buffer-undo-list)
18216 (not (cadr buffer-undo-list)) ; remove nil entry
18217 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18218 (setq org-self-insert-command-undo-counter
18219 (1+ org-self-insert-command-undo-counter))))))))
18221 (defun org-check-before-invisible-edit (kind)
18222 "Check is editing if kind KIND would be dangerous with invisible text around.
18223 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18224 ;; First, try to get out of here as quickly as possible, to reduce overhead
18225 (if (and org-catch-invisible-edits
18226 (or (not (boundp 'visible-mode)) (not visible-mode))
18227 (or (get-char-property (point) 'invisible)
18228 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18229 ;; OK, we need to take a closer look
18230 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18231 (invisible-before-point (if (bobp) nil (get-char-property
18232 (1- (point)) 'invisible)))
18233 (border-and-ok-direction
18235 ;; Check if we are acting predictably before invisible text
18236 (and invisible-at-point (not invisible-before-point)
18237 (memq kind '(insert delete-backward)))
18238 ;; Check if we are acting predictably after invisible text
18239 ;; This works not well, and I have turned it off. It seems
18240 ;; better to always show and stop after invisible text.
18241 ;; (and (not invisible-at-point) invisible-before-point
18242 ;; (memq kind '(insert delete)))
18245 (when (or (memq invisible-at-point '(outline org-hide-block))
18246 (memq invisible-before-point '(outline org-hide-block)))
18247 (if (eq org-catch-invisible-edits 'error)
18248 (error "Editing in invisible areas is prohibited - make visible first"))
18249 ;; Make the area visible
18250 (save-excursion
18251 (if invisible-before-point
18252 (goto-char (previous-single-char-property-change
18253 (point) 'invisible)))
18254 (org-cycle))
18255 (cond
18256 ((eq org-catch-invisible-edits 'show)
18257 ;; That's it, we do the edit after showing
18258 (message
18259 "Unfolding invisible region around point before editing")
18260 (sit-for 1))
18261 ((and (eq org-catch-invisible-edits 'smart)
18262 border-and-ok-direction)
18263 (message "Unfolding invisible region around point before editing"))
18265 ;; Don't do the edit, make the user repeat it in full visibility
18266 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18268 (defun org-fix-tags-on-the-fly ()
18269 (when (and (equal (char-after (point-at-bol)) ?*)
18270 (org-at-heading-p))
18271 (org-align-tags-here org-tags-column)))
18273 (defun org-delete-backward-char (N)
18274 "Like `delete-backward-char', insert whitespace at field end in tables.
18275 When deleting backwards, in tables this function will insert whitespace in
18276 front of the next \"|\" separator, to keep the table aligned. The table will
18277 still be marked for re-alignment if the field did fill the entire column,
18278 because, in this case the deletion might narrow the column."
18279 (interactive "p")
18280 (org-check-before-invisible-edit 'delete-backward)
18281 (if (and (org-table-p)
18282 (eq N 1)
18283 (string-match "|" (buffer-substring (point-at-bol) (point)))
18284 (looking-at ".*?|"))
18285 (let ((pos (point))
18286 (noalign (looking-at "[^|\n\r]* |"))
18287 (c org-table-may-need-update))
18288 (backward-delete-char N)
18289 (if (not overwrite-mode)
18290 (progn
18291 (skip-chars-forward "^|")
18292 (insert " ")
18293 (goto-char (1- pos))))
18294 ;; noalign: if there were two spaces at the end, this field
18295 ;; does not determine the width of the column.
18296 (if noalign (setq org-table-may-need-update c)))
18297 (backward-delete-char N)
18298 (org-fix-tags-on-the-fly)))
18300 (defun org-delete-char (N)
18301 "Like `delete-char', but insert whitespace at field end in tables.
18302 When deleting characters, in tables this function will insert whitespace in
18303 front of the next \"|\" separator, to keep the table aligned. The table will
18304 still be marked for re-alignment if the field did fill the entire column,
18305 because, in this case the deletion might narrow the column."
18306 (interactive "p")
18307 (org-check-before-invisible-edit 'delete)
18308 (if (and (org-table-p)
18309 (not (bolp))
18310 (not (= (char-after) ?|))
18311 (eq N 1))
18312 (if (looking-at ".*?|")
18313 (let ((pos (point))
18314 (noalign (looking-at "[^|\n\r]* |"))
18315 (c org-table-may-need-update))
18316 (replace-match (concat
18317 (substring (match-string 0) 1 -1)
18318 " |"))
18319 (goto-char pos)
18320 ;; noalign: if there were two spaces at the end, this field
18321 ;; does not determine the width of the column.
18322 (if noalign (setq org-table-may-need-update c)))
18323 (delete-char N))
18324 (delete-char N)
18325 (org-fix-tags-on-the-fly)))
18327 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18328 (put 'org-self-insert-command 'delete-selection t)
18329 (put 'orgtbl-self-insert-command 'delete-selection t)
18330 (put 'org-delete-char 'delete-selection 'supersede)
18331 (put 'org-delete-backward-char 'delete-selection 'supersede)
18332 (put 'org-yank 'delete-selection 'yank)
18334 ;; Make `flyspell-mode' delay after some commands
18335 (put 'org-self-insert-command 'flyspell-delayed t)
18336 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18337 (put 'org-delete-char 'flyspell-delayed t)
18338 (put 'org-delete-backward-char 'flyspell-delayed t)
18340 ;; Make pabbrev-mode expand after org-mode commands
18341 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18342 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18344 ;; How to do this: Measure non-white length of current string
18345 ;; If equal to column width, we should realign.
18347 (defun org-remap (map &rest commands)
18348 "In MAP, remap the functions given in COMMANDS.
18349 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18350 (let (new old)
18351 (while commands
18352 (setq old (pop commands) new (pop commands))
18353 (if (fboundp 'command-remapping)
18354 (org-defkey map (vector 'remap old) new)
18355 (substitute-key-definition old new map global-map)))))
18357 (when (eq org-enable-table-editor 'optimized)
18358 ;; If the user wants maximum table support, we need to hijack
18359 ;; some standard editing functions
18360 (org-remap org-mode-map
18361 'self-insert-command 'org-self-insert-command
18362 'delete-char 'org-delete-char
18363 'delete-backward-char 'org-delete-backward-char)
18364 (org-defkey org-mode-map "|" 'org-force-self-insert))
18366 (defvar org-ctrl-c-ctrl-c-hook nil
18367 "Hook for functions attaching themselves to `C-c C-c'.
18369 This can be used to add additional functionality to the C-c C-c
18370 key which executes context-dependent commands. This hook is run
18371 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18372 run after the last test.
18374 Each function will be called with no arguments. The function
18375 must check if the context is appropriate for it to act. If yes,
18376 it should do its thing and then return a non-nil value. If the
18377 context is wrong, just do nothing and return nil.")
18379 (defvar org-ctrl-c-ctrl-c-final-hook nil
18380 "Hook for functions attaching themselves to `C-c C-c'.
18382 This can be used to add additional functionality to the C-c C-c
18383 key which executes context-dependent commands. This hook is run
18384 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18385 before the first test.
18387 Each function will be called with no arguments. The function
18388 must check if the context is appropriate for it to act. If yes,
18389 it should do its thing and then return a non-nil value. If the
18390 context is wrong, just do nothing and return nil.")
18392 (defvar org-tab-first-hook nil
18393 "Hook for functions to attach themselves to TAB.
18394 See `org-ctrl-c-ctrl-c-hook' for more information.
18395 This hook runs as the first action when TAB is pressed, even before
18396 `org-cycle' messes around with the `outline-regexp' to cater for
18397 inline tasks and plain list item folding.
18398 If any function in this hook returns t, any other actions that
18399 would have been caused by TAB (such as table field motion or visibility
18400 cycling) will not occur.")
18402 (defvar org-tab-after-check-for-table-hook nil
18403 "Hook for functions to attach themselves to TAB.
18404 See `org-ctrl-c-ctrl-c-hook' for more information.
18405 This hook runs after it has been established that the cursor is not in a
18406 table, but before checking if the cursor is in a headline or if global cycling
18407 should be done.
18408 If any function in this hook returns t, not other actions like visibility
18409 cycling will be done.")
18411 (defvar org-tab-after-check-for-cycling-hook nil
18412 "Hook for functions to attach themselves to TAB.
18413 See `org-ctrl-c-ctrl-c-hook' for more information.
18414 This hook runs after it has been established that not table field motion and
18415 not visibility should be done because of current context. This is probably
18416 the place where a package like yasnippets can hook in.")
18418 (defvar org-tab-before-tab-emulation-hook nil
18419 "Hook for functions to attach themselves to TAB.
18420 See `org-ctrl-c-ctrl-c-hook' for more information.
18421 This hook runs after every other options for TAB have been exhausted, but
18422 before indentation and \t insertion takes place.")
18424 (defvar org-metaleft-hook nil
18425 "Hook for functions attaching themselves to `M-left'.
18426 See `org-ctrl-c-ctrl-c-hook' for more information.")
18427 (defvar org-metaright-hook nil
18428 "Hook for functions attaching themselves to `M-right'.
18429 See `org-ctrl-c-ctrl-c-hook' for more information.")
18430 (defvar org-metaup-hook nil
18431 "Hook for functions attaching themselves to `M-up'.
18432 See `org-ctrl-c-ctrl-c-hook' for more information.")
18433 (defvar org-metadown-hook nil
18434 "Hook for functions attaching themselves to `M-down'.
18435 See `org-ctrl-c-ctrl-c-hook' for more information.")
18436 (defvar org-shiftmetaleft-hook nil
18437 "Hook for functions attaching themselves to `M-S-left'.
18438 See `org-ctrl-c-ctrl-c-hook' for more information.")
18439 (defvar org-shiftmetaright-hook nil
18440 "Hook for functions attaching themselves to `M-S-right'.
18441 See `org-ctrl-c-ctrl-c-hook' for more information.")
18442 (defvar org-shiftmetaup-hook nil
18443 "Hook for functions attaching themselves to `M-S-up'.
18444 See `org-ctrl-c-ctrl-c-hook' for more information.")
18445 (defvar org-shiftmetadown-hook nil
18446 "Hook for functions attaching themselves to `M-S-down'.
18447 See `org-ctrl-c-ctrl-c-hook' for more information.")
18448 (defvar org-metareturn-hook nil
18449 "Hook for functions attaching themselves to `M-RET'.
18450 See `org-ctrl-c-ctrl-c-hook' for more information.")
18451 (defvar org-shiftup-hook nil
18452 "Hook for functions attaching themselves to `S-up'.
18453 See `org-ctrl-c-ctrl-c-hook' for more information.")
18454 (defvar org-shiftup-final-hook nil
18455 "Hook for functions attaching themselves to `S-up'.
18456 This one runs after all other options except shift-select have been excluded.
18457 See `org-ctrl-c-ctrl-c-hook' for more information.")
18458 (defvar org-shiftdown-hook nil
18459 "Hook for functions attaching themselves to `S-down'.
18460 See `org-ctrl-c-ctrl-c-hook' for more information.")
18461 (defvar org-shiftdown-final-hook nil
18462 "Hook for functions attaching themselves to `S-down'.
18463 This one runs after all other options except shift-select have been excluded.
18464 See `org-ctrl-c-ctrl-c-hook' for more information.")
18465 (defvar org-shiftleft-hook nil
18466 "Hook for functions attaching themselves to `S-left'.
18467 See `org-ctrl-c-ctrl-c-hook' for more information.")
18468 (defvar org-shiftleft-final-hook nil
18469 "Hook for functions attaching themselves to `S-left'.
18470 This one runs after all other options except shift-select have been excluded.
18471 See `org-ctrl-c-ctrl-c-hook' for more information.")
18472 (defvar org-shiftright-hook nil
18473 "Hook for functions attaching themselves to `S-right'.
18474 See `org-ctrl-c-ctrl-c-hook' for more information.")
18475 (defvar org-shiftright-final-hook nil
18476 "Hook for functions attaching themselves to `S-right'.
18477 This one runs after all other options except shift-select have been excluded.
18478 See `org-ctrl-c-ctrl-c-hook' for more information.")
18480 (defun org-modifier-cursor-error ()
18481 "Throw an error, a modified cursor command was applied in wrong context."
18482 (error "This command is active in special context like tables, headlines or items"))
18484 (defun org-shiftselect-error ()
18485 "Throw an error because Shift-Cursor command was applied in wrong context."
18486 (if (and (boundp 'shift-select-mode) shift-select-mode)
18487 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18488 (error "This command works only in special context like headlines or timestamps")))
18490 (defun org-call-for-shift-select (cmd)
18491 (let ((this-command-keys-shift-translated t))
18492 (call-interactively cmd)))
18494 (defun org-shifttab (&optional arg)
18495 "Global visibility cycling or move to previous table field.
18496 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18497 on context.
18498 See the individual commands for more information."
18499 (interactive "P")
18500 (cond
18501 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18502 ((integerp arg)
18503 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18504 (message "Content view to level: %d" arg)
18505 (org-content (prefix-numeric-value arg2))
18506 (setq org-cycle-global-status 'overview)))
18507 (t (call-interactively 'org-global-cycle))))
18509 (defun org-shiftmetaleft ()
18510 "Promote subtree or delete table column.
18511 Calls `org-promote-subtree', `org-outdent-item-tree', or
18512 `org-table-delete-column', depending on context. See the
18513 individual commands for more information."
18514 (interactive)
18515 (cond
18516 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18517 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18518 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18519 ((if (not (org-region-active-p)) (org-at-item-p)
18520 (save-excursion (goto-char (region-beginning))
18521 (org-at-item-p)))
18522 (call-interactively 'org-outdent-item-tree))
18523 (t (org-modifier-cursor-error))))
18525 (defun org-shiftmetaright ()
18526 "Demote subtree or insert table column.
18527 Calls `org-demote-subtree', `org-indent-item-tree', or
18528 `org-table-insert-column', depending on context. See the
18529 individual commands for more information."
18530 (interactive)
18531 (cond
18532 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18533 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18534 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18535 ((if (not (org-region-active-p)) (org-at-item-p)
18536 (save-excursion (goto-char (region-beginning))
18537 (org-at-item-p)))
18538 (call-interactively 'org-indent-item-tree))
18539 (t (org-modifier-cursor-error))))
18541 (defun org-shiftmetaup (&optional arg)
18542 "Move subtree up or kill table row.
18543 Calls `org-move-subtree-up' or `org-table-kill-row' or
18544 `org-move-item-up' or `org-timestamp-up', depending on context.
18545 See the individual commands for more information."
18546 (interactive "P")
18547 (cond
18548 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18549 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18550 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18551 ((org-at-item-p) (call-interactively 'org-move-item-up))
18552 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18553 (call-interactively 'org-timestamp-up)))
18554 (t (org-modifier-cursor-error))))
18556 (defun org-shiftmetadown (&optional arg)
18557 "Move subtree down or insert table row.
18558 Calls `org-move-subtree-down' or `org-table-insert-row' or
18559 `org-move-item-down' or `org-timestamp-up', depending on context.
18560 See the individual commands for more information."
18561 (interactive "P")
18562 (cond
18563 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18564 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18565 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18566 ((org-at-item-p) (call-interactively 'org-move-item-down))
18567 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18568 (call-interactively 'org-timestamp-down)))
18569 (t (org-modifier-cursor-error))))
18571 (defsubst org-hidden-tree-error ()
18572 (error
18573 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18575 (defun org-metaleft (&optional arg)
18576 "Promote heading or move table column to left.
18577 Calls `org-do-promote' or `org-table-move-column', depending on context.
18578 With no specific context, calls the Emacs default `backward-word'.
18579 See the individual commands for more information."
18580 (interactive "P")
18581 (cond
18582 ((run-hook-with-args-until-success 'org-metaleft-hook))
18583 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18584 ((org-with-limited-levels
18585 (or (org-at-heading-p)
18586 (and (org-region-active-p)
18587 (save-excursion
18588 (goto-char (region-beginning))
18589 (org-at-heading-p)))))
18590 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18591 (call-interactively 'org-do-promote))
18592 ;; At an inline task.
18593 ((org-at-heading-p)
18594 (call-interactively 'org-inlinetask-promote))
18595 ((or (org-at-item-p)
18596 (and (org-region-active-p)
18597 (save-excursion
18598 (goto-char (region-beginning))
18599 (org-at-item-p))))
18600 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18601 (call-interactively 'org-outdent-item))
18602 (t (call-interactively 'backward-word))))
18604 (defun org-metaright (&optional arg)
18605 "Demote a subtree, a list item or move table column to right.
18606 In front of a drawer or a block keyword, indent it correctly.
18607 With no specific context, calls the Emacs default `forward-word'.
18608 See the individual commands for more information."
18609 (interactive "P")
18610 (cond
18611 ((run-hook-with-args-until-success 'org-metaright-hook))
18612 ((org-at-table-p) (call-interactively 'org-table-move-column))
18613 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18614 ((org-at-block-p) (call-interactively 'org-indent-block))
18615 ((org-with-limited-levels
18616 (or (org-at-heading-p)
18617 (and (org-region-active-p)
18618 (save-excursion
18619 (goto-char (region-beginning))
18620 (org-at-heading-p)))))
18621 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18622 (call-interactively 'org-do-demote))
18623 ;; At an inline task.
18624 ((org-at-heading-p)
18625 (call-interactively 'org-inlinetask-demote))
18626 ((or (org-at-item-p)
18627 (and (org-region-active-p)
18628 (save-excursion
18629 (goto-char (region-beginning))
18630 (org-at-item-p))))
18631 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18632 (call-interactively 'org-indent-item))
18633 (t (call-interactively 'forward-word))))
18635 (defun org-check-for-hidden (what)
18636 "Check if there are hidden headlines/items in the current visual line.
18637 WHAT can be either `headlines' or `items'. If the current line is
18638 an outline or item heading and it has a folded subtree below it,
18639 this function returns t, nil otherwise."
18640 (let ((re (cond
18641 ((eq what 'headlines) org-outline-regexp-bol)
18642 ((eq what 'items) (org-item-beginning-re))
18643 (t (error "This should not happen"))))
18644 beg end)
18645 (save-excursion
18646 (catch 'exit
18647 (unless (org-region-active-p)
18648 (setq beg (point-at-bol))
18649 (beginning-of-line 2)
18650 (while (and (not (eobp)) ;; this is like `next-line'
18651 (get-char-property (1- (point)) 'invisible))
18652 (beginning-of-line 2))
18653 (setq end (point))
18654 (goto-char beg)
18655 (goto-char (point-at-eol))
18656 (setq end (max end (point)))
18657 (while (re-search-forward re end t)
18658 (if (get-char-property (match-beginning 0) 'invisible)
18659 (throw 'exit t))))
18660 nil))))
18662 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18663 (declare-function org-element-type "org-element" (element))
18664 (declare-function org-element-contents "org-element" (element))
18665 (declare-function org-element-property "org-element" (property element))
18666 (declare-function org-element-paragraph-parser "org-element" (limit))
18667 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18668 (declare-function org-element-up "org-element" ())
18669 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18670 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18671 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18672 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18674 (defun org-metaup (&optional arg)
18675 "Move subtree up or move table row up.
18676 Calls `org-move-subtree-up' or `org-table-move-row' or
18677 `org-move-item-up', depending on context. See the individual commands
18678 for more information."
18679 (interactive "P")
18680 (cond
18681 ((run-hook-with-args-until-success 'org-metaup-hook))
18682 ((org-region-active-p)
18683 (let* ((a (min (region-beginning) (region-end)))
18684 (b (1- (max (region-beginning) (region-end))))
18685 (c (save-excursion (goto-char a)
18686 (move-beginning-of-line 0)))
18687 (d (save-excursion (goto-char a)
18688 (move-end-of-line 0) (point))))
18689 (transpose-regions a b c d)
18690 (goto-char c)))
18691 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18692 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18693 ((org-at-item-p) (call-interactively 'org-move-item-up))
18694 (t (org-drag-element-backward))))
18696 (defun org-metadown (&optional arg)
18697 "Move subtree down or move table row down.
18698 Calls `org-move-subtree-down' or `org-table-move-row' or
18699 `org-move-item-down', depending on context. See the individual
18700 commands for more information."
18701 (interactive "P")
18702 (cond
18703 ((run-hook-with-args-until-success 'org-metadown-hook))
18704 ((org-region-active-p)
18705 (let* ((a (min (region-beginning) (region-end)))
18706 (b (max (region-beginning) (region-end)))
18707 (c (save-excursion (goto-char b)
18708 (move-beginning-of-line 1)))
18709 (d (save-excursion (goto-char b)
18710 (move-end-of-line 1) (1+ (point)))))
18711 (transpose-regions a b c d)
18712 (goto-char d)))
18713 ((org-at-table-p) (call-interactively 'org-table-move-row))
18714 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18715 ((org-at-item-p) (call-interactively 'org-move-item-down))
18716 (t (org-drag-element-forward))))
18718 (defun org-shiftup (&optional arg)
18719 "Increase item in timestamp or increase priority of current headline.
18720 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18721 depending on context. See the individual commands for more information."
18722 (interactive "P")
18723 (cond
18724 ((run-hook-with-args-until-success 'org-shiftup-hook))
18725 ((and org-support-shift-select (org-region-active-p))
18726 (org-call-for-shift-select 'previous-line))
18727 ((org-at-timestamp-p t)
18728 (call-interactively (if org-edit-timestamp-down-means-later
18729 'org-timestamp-down 'org-timestamp-up)))
18730 ((and (not (eq org-support-shift-select 'always))
18731 org-enable-priority-commands
18732 (org-at-heading-p))
18733 (call-interactively 'org-priority-up))
18734 ((and (not org-support-shift-select) (org-at-item-p))
18735 (call-interactively 'org-previous-item))
18736 ((org-clocktable-try-shift 'up arg))
18737 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18738 (org-support-shift-select
18739 (org-call-for-shift-select 'previous-line))
18740 (t (org-shiftselect-error))))
18742 (defun org-shiftdown (&optional arg)
18743 "Decrease item in timestamp or decrease priority of current headline.
18744 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18745 depending on context. See the individual commands for more information."
18746 (interactive "P")
18747 (cond
18748 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18749 ((and org-support-shift-select (org-region-active-p))
18750 (org-call-for-shift-select 'next-line))
18751 ((org-at-timestamp-p t)
18752 (call-interactively (if org-edit-timestamp-down-means-later
18753 'org-timestamp-up 'org-timestamp-down)))
18754 ((and (not (eq org-support-shift-select 'always))
18755 org-enable-priority-commands
18756 (org-at-heading-p))
18757 (call-interactively 'org-priority-down))
18758 ((and (not org-support-shift-select) (org-at-item-p))
18759 (call-interactively 'org-next-item))
18760 ((org-clocktable-try-shift 'down arg))
18761 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18762 (org-support-shift-select
18763 (org-call-for-shift-select 'next-line))
18764 (t (org-shiftselect-error))))
18766 (defun org-shiftright (&optional arg)
18767 "Cycle the thing at point or in the current line, depending on context.
18768 Depending on context, this does one of the following:
18770 - switch a timestamp at point one day into the future
18771 - on a headline, switch to the next TODO keyword.
18772 - on an item, switch entire list to the next bullet type
18773 - on a property line, switch to the next allowed value
18774 - on a clocktable definition line, move time block into the future"
18775 (interactive "P")
18776 (cond
18777 ((run-hook-with-args-until-success 'org-shiftright-hook))
18778 ((and org-support-shift-select (org-region-active-p))
18779 (org-call-for-shift-select 'forward-char))
18780 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18781 ((and (not (eq org-support-shift-select 'always))
18782 (org-at-heading-p))
18783 (let ((org-inhibit-logging
18784 (not org-treat-S-cursor-todo-selection-as-state-change))
18785 (org-inhibit-blocking
18786 (not org-treat-S-cursor-todo-selection-as-state-change)))
18787 (org-call-with-arg 'org-todo 'right)))
18788 ((or (and org-support-shift-select
18789 (not (eq org-support-shift-select 'always))
18790 (org-at-item-bullet-p))
18791 (and (not org-support-shift-select) (org-at-item-p)))
18792 (org-call-with-arg 'org-cycle-list-bullet nil))
18793 ((and (not (eq org-support-shift-select 'always))
18794 (org-at-property-p))
18795 (call-interactively 'org-property-next-allowed-value))
18796 ((org-clocktable-try-shift 'right arg))
18797 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18798 (org-support-shift-select
18799 (org-call-for-shift-select 'forward-char))
18800 (t (org-shiftselect-error))))
18802 (defun org-shiftleft (&optional arg)
18803 "Cycle the thing at point or in the current line, depending on context.
18804 Depending on context, this does one of the following:
18806 - switch a timestamp at point one day into the past
18807 - on a headline, switch to the previous TODO keyword.
18808 - on an item, switch entire list to the previous bullet type
18809 - on a property line, switch to the previous allowed value
18810 - on a clocktable definition line, move time block into the past"
18811 (interactive "P")
18812 (cond
18813 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18814 ((and org-support-shift-select (org-region-active-p))
18815 (org-call-for-shift-select 'backward-char))
18816 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18817 ((and (not (eq org-support-shift-select 'always))
18818 (org-at-heading-p))
18819 (let ((org-inhibit-logging
18820 (not org-treat-S-cursor-todo-selection-as-state-change))
18821 (org-inhibit-blocking
18822 (not org-treat-S-cursor-todo-selection-as-state-change)))
18823 (org-call-with-arg 'org-todo 'left)))
18824 ((or (and org-support-shift-select
18825 (not (eq org-support-shift-select 'always))
18826 (org-at-item-bullet-p))
18827 (and (not org-support-shift-select) (org-at-item-p)))
18828 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18829 ((and (not (eq org-support-shift-select 'always))
18830 (org-at-property-p))
18831 (call-interactively 'org-property-previous-allowed-value))
18832 ((org-clocktable-try-shift 'left arg))
18833 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18834 (org-support-shift-select
18835 (org-call-for-shift-select 'backward-char))
18836 (t (org-shiftselect-error))))
18838 (defun org-shiftcontrolright ()
18839 "Switch to next TODO set."
18840 (interactive)
18841 (cond
18842 ((and org-support-shift-select (org-region-active-p))
18843 (org-call-for-shift-select 'forward-word))
18844 ((and (not (eq org-support-shift-select 'always))
18845 (org-at-heading-p))
18846 (org-call-with-arg 'org-todo 'nextset))
18847 (org-support-shift-select
18848 (org-call-for-shift-select 'forward-word))
18849 (t (org-shiftselect-error))))
18851 (defun org-shiftcontrolleft ()
18852 "Switch to previous TODO set."
18853 (interactive)
18854 (cond
18855 ((and org-support-shift-select (org-region-active-p))
18856 (org-call-for-shift-select 'backward-word))
18857 ((and (not (eq org-support-shift-select 'always))
18858 (org-at-heading-p))
18859 (org-call-with-arg 'org-todo 'previousset))
18860 (org-support-shift-select
18861 (org-call-for-shift-select 'backward-word))
18862 (t (org-shiftselect-error))))
18864 (defun org-shiftcontrolup ()
18865 "Change timestamps synchronously up in CLOCK log lines."
18866 (interactive)
18867 (cond ((and (not org-support-shift-select)
18868 (org-at-clock-log-p)
18869 (org-at-timestamp-p t))
18870 (org-clock-timestamps-up))
18871 (t (org-shiftselect-error))))
18873 (defun org-shiftcontroldown ()
18874 "Change timestamps synchronously down in CLOCK log lines."
18875 (interactive)
18876 (cond ((and (not org-support-shift-select)
18877 (org-at-clock-log-p)
18878 (org-at-timestamp-p t))
18879 (org-clock-timestamps-down))
18880 (t (org-shiftselect-error))))
18882 (defun org-ctrl-c-ret ()
18883 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18884 (interactive)
18885 (cond
18886 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18887 (t (call-interactively 'org-insert-heading))))
18889 (defun org-find-visible ()
18890 (let ((s (point)))
18891 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18892 (get-char-property s 'invisible)))
18894 (defun org-find-invisible ()
18895 (let ((s (point)))
18896 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18897 (not (get-char-property s 'invisible))))
18900 (defun org-copy-visible (beg end)
18901 "Copy the visible parts of the region."
18902 (interactive "r")
18903 (let (snippets s)
18904 (save-excursion
18905 (save-restriction
18906 (narrow-to-region beg end)
18907 (setq s (goto-char (point-min)))
18908 (while (not (= (point) (point-max)))
18909 (goto-char (org-find-invisible))
18910 (push (buffer-substring s (point)) snippets)
18911 (setq s (goto-char (org-find-visible))))))
18912 (kill-new (apply 'concat (nreverse snippets)))))
18914 (defun org-copy-special ()
18915 "Copy region in table or copy current subtree.
18916 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18917 See the individual commands for more information."
18918 (interactive)
18919 (call-interactively
18920 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18922 (defun org-cut-special ()
18923 "Cut region in table or cut current subtree.
18924 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18925 See the individual commands for more information."
18926 (interactive)
18927 (call-interactively
18928 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18930 (defun org-paste-special (arg)
18931 "Paste rectangular region into table, or past subtree relative to level.
18932 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18933 See the individual commands for more information."
18934 (interactive "P")
18935 (if (org-at-table-p)
18936 (org-table-paste-rectangle)
18937 (org-paste-subtree arg)))
18939 (defun org-edit-special (&optional arg)
18940 "Call a special editor for the stuff at point.
18941 When at a table, call the formula editor with `org-table-edit-formulas'.
18942 When at the first line of an src example, call `org-edit-src-code'.
18943 When in an #+include line, visit the include file. Otherwise call
18944 `ffap' to visit the file at point."
18945 (interactive)
18946 ;; possibly prep session before editing source
18947 (when arg
18948 (let* ((info (org-babel-get-src-block-info))
18949 (lang (nth 0 info))
18950 (params (nth 2 info))
18951 (session (cdr (assoc :session params))))
18952 (when (and info session) ;; we are in a source-code block with a session
18953 (funcall
18954 (intern (concat "org-babel-prep-session:" lang)) session params))))
18955 (cond ;; proceed with `org-edit-special'
18956 ((save-excursion
18957 (beginning-of-line 1)
18958 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18959 (find-file (org-trim (match-string 1))))
18960 ((org-edit-src-code))
18961 ((org-edit-fixed-width-region))
18962 ((org-at-table.el-p)
18963 (org-edit-src-code))
18964 ((or (org-at-table-p)
18965 (save-excursion
18966 (beginning-of-line 1)
18967 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18968 (call-interactively 'org-table-edit-formulas))
18969 (t (call-interactively 'ffap))))
18971 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18972 (defun org-ctrl-c-ctrl-c (&optional arg)
18973 "Set tags in headline, or update according to changed information at point.
18975 This command does many different things, depending on context:
18977 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18978 this is what we do.
18980 - If the cursor is on a statistics cookie, update it.
18982 - If the cursor is in a headline, prompt for tags and insert them
18983 into the current line, aligned to `org-tags-column'. When called
18984 with prefix arg, realign all tags in the current buffer.
18986 - If the cursor is in one of the special #+KEYWORD lines, this
18987 triggers scanning the buffer for these lines and updating the
18988 information.
18990 - If the cursor is inside a table, realign the table. This command
18991 works even if the automatic table editor has been turned off.
18993 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18994 the entire table.
18996 - If the cursor is at a footnote reference or definition, jump to
18997 the corresponding definition or references, respectively.
18999 - If the cursor is a the beginning of a dynamic block, update it.
19001 - If the current buffer is a capture buffer, close note and file it.
19003 - If the cursor is on a <<<target>>>, update radio targets and
19004 corresponding links in this buffer.
19006 - If the cursor is on a numbered item in a plain list, renumber the
19007 ordered list.
19009 - If the cursor is on a checkbox, toggle it.
19011 - If the cursor is on a code block, evaluate it. The variable
19012 `org-confirm-babel-evaluate' can be used to control prompting
19013 before code block evaluation, by default every code block
19014 evaluation requires confirmation. Code block evaluation can be
19015 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19016 (interactive "P")
19017 (let ((org-enable-table-editor t))
19018 (cond
19019 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19020 org-occur-highlights
19021 org-latex-fragment-image-overlays)
19022 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19023 (org-remove-occur-highlights)
19024 (org-remove-latex-fragment-image-overlays)
19025 (message "Temporary highlights/overlays removed from current buffer"))
19026 ((and (local-variable-p 'org-finish-function (current-buffer))
19027 (fboundp org-finish-function))
19028 (funcall org-finish-function))
19029 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19030 ((org-in-regexp org-ts-regexp-both)
19031 (org-timestamp-change 0 'day))
19032 ((or (looking-at org-property-start-re)
19033 (org-at-property-p))
19034 (call-interactively 'org-property-action))
19035 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19036 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19037 (or (org-at-heading-p) (org-at-item-p)))
19038 (call-interactively 'org-update-statistics-cookies))
19039 ((org-at-heading-p) (call-interactively 'org-set-tags))
19040 ((org-at-table.el-p)
19041 (message "Use C-c ' to edit table.el tables"))
19042 ((org-at-table-p)
19043 (org-table-maybe-eval-formula)
19044 (if arg
19045 (call-interactively 'org-table-recalculate)
19046 (org-table-maybe-recalculate-line))
19047 (call-interactively 'org-table-align)
19048 (orgtbl-send-table 'maybe))
19049 ((or (org-footnote-at-reference-p)
19050 (org-footnote-at-definition-p))
19051 (call-interactively 'org-footnote-action))
19052 ((org-at-item-checkbox-p)
19053 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19054 ;; list only if at top item.
19055 (let* ((cbox (match-string 1))
19056 (struct (org-list-struct))
19057 (old-struct (copy-tree struct))
19058 (parents (org-list-parents-alist struct))
19059 (orderedp (org-entry-get nil "ORDERED"))
19060 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19061 block-item)
19062 ;; Use a light version of `org-toggle-checkbox' to avoid
19063 ;; computing list structure twice.
19064 (let ((new-box (cond
19065 ((equal arg '(16)) "[-]")
19066 ((equal arg '(4)) nil)
19067 ((equal "[X]" cbox) "[ ]")
19068 (t "[X]"))))
19069 (if (and firstp arg)
19070 ;; If at first item of sub-list, remove check-box from
19071 ;; every item at the same level.
19072 (mapc
19073 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19074 (org-list-get-all-items
19075 (point-at-bol) struct (org-list-prevs-alist struct)))
19076 (org-list-set-checkbox (point-at-bol) struct new-box)))
19077 ;; Replicate `org-list-write-struct', while grabbing a return
19078 ;; value from `org-list-struct-fix-box'.
19079 (org-list-struct-fix-ind struct parents 2)
19080 (org-list-struct-fix-item-end struct)
19081 (let ((prevs (org-list-prevs-alist struct)))
19082 (org-list-struct-fix-bul struct prevs)
19083 (org-list-struct-fix-ind struct parents)
19084 (setq block-item
19085 (org-list-struct-fix-box struct parents prevs orderedp)))
19086 (org-list-struct-apply-struct struct old-struct)
19087 (org-update-checkbox-count-maybe)
19088 (when block-item
19089 (message
19090 "Checkboxes were removed due to unchecked box at line %d"
19091 (org-current-line block-item)))
19092 (when firstp (org-list-send-list 'maybe))))
19093 ((org-at-item-p)
19094 ;; Cursor at an item: repair list. Do checkbox related actions
19095 ;; only if function was called with an argument. Send list only
19096 ;; if at top item.
19097 (let* ((struct (org-list-struct))
19098 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19099 old-struct)
19100 (when arg
19101 (setq old-struct (copy-tree struct))
19102 (if firstp
19103 ;; If at first item of sub-list, add check-box to every
19104 ;; item at the same level.
19105 (mapc
19106 (lambda (pos)
19107 (unless (org-list-get-checkbox pos struct)
19108 (org-list-set-checkbox pos struct "[ ]")))
19109 (org-list-get-all-items
19110 (point-at-bol) struct (org-list-prevs-alist struct)))
19111 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19112 (org-list-write-struct
19113 struct (org-list-parents-alist struct) old-struct)
19114 (when arg (org-update-checkbox-count-maybe))
19115 (when firstp (org-list-send-list 'maybe))))
19116 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19117 ;; Dynamic block
19118 (beginning-of-line 1)
19119 (save-excursion (org-update-dblock)))
19120 ((save-excursion
19121 (let ((case-fold-search t))
19122 (beginning-of-line 1)
19123 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19124 (cond
19125 ((or (equal (match-string 1) "TBLFM")
19126 (equal (match-string 1) "tblfm"))
19127 ;; Recalculate the table before this line
19128 (save-excursion
19129 (beginning-of-line 1)
19130 (skip-chars-backward " \r\n\t")
19131 (if (org-at-table-p)
19132 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19134 (let ((org-inhibit-startup-visibility-stuff t)
19135 (org-startup-align-all-tables nil))
19136 (when (boundp 'org-table-coordinate-overlays)
19137 (mapc 'delete-overlay org-table-coordinate-overlays)
19138 (setq org-table-coordinate-overlays nil))
19139 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19140 (message "Local setup has been refreshed"))))
19141 ((org-clock-update-time-maybe))
19143 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19144 (error "C-c C-c can do nothing useful at this location"))))))
19146 (defun org-mode-restart ()
19147 "Restart Org-mode, to scan again for special lines.
19148 Also updates the keyword regular expressions."
19149 (interactive)
19150 (org-mode)
19151 (message "Org-mode restarted"))
19153 (defun org-kill-note-or-show-branches ()
19154 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19155 (interactive)
19156 (if (not org-finish-function)
19157 (progn
19158 (hide-subtree)
19159 (call-interactively 'show-branches))
19160 (let ((org-note-abort t))
19161 (funcall org-finish-function))))
19163 (defun org-return (&optional indent)
19164 "Goto next table row or insert a newline.
19165 Calls `org-table-next-row' or `newline', depending on context.
19166 See the individual commands for more information."
19167 (interactive)
19168 (let (org-ts-what)
19169 (cond
19170 ((or (bobp) (org-in-src-block-p))
19171 (if indent (newline-and-indent) (newline)))
19172 ((org-at-table-p)
19173 (org-table-justify-field-maybe)
19174 (call-interactively 'org-table-next-row))
19175 ;; when `newline-and-indent' is called within a list, make sure
19176 ;; text moved stays inside the item.
19177 ((and (org-in-item-p) indent)
19178 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19179 (progn
19180 (save-match-data (newline))
19181 (org-indent-line-to (length (match-string 0))))
19182 (let ((ind (org-get-indentation)))
19183 (newline)
19184 (if (org-looking-back org-list-end-re)
19185 (org-indent-line)
19186 (org-indent-line-to ind)))))
19187 ((and org-return-follows-link
19188 (org-at-timestamp-p t)
19189 (not (eq org-ts-what 'after)))
19190 (org-follow-timestamp-link))
19191 ((and org-return-follows-link
19192 (let ((tprop (get-text-property (point) 'face)))
19193 (or (eq tprop 'org-link)
19194 (and (listp tprop) (memq 'org-link tprop)))))
19195 (call-interactively 'org-open-at-point))
19196 ((and (org-at-heading-p)
19197 (looking-at
19198 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19199 (org-show-entry)
19200 (end-of-line 1)
19201 (newline))
19202 (t (if indent (newline-and-indent) (newline))))))
19204 (defun org-return-indent ()
19205 "Goto next table row or insert a newline and indent.
19206 Calls `org-table-next-row' or `newline-and-indent', depending on
19207 context. See the individual commands for more information."
19208 (interactive)
19209 (org-return t))
19211 (defun org-ctrl-c-star ()
19212 "Compute table, or change heading status of lines.
19213 Calls `org-table-recalculate' or `org-toggle-heading',
19214 depending on context."
19215 (interactive)
19216 (cond
19217 ((org-at-table-p)
19218 (call-interactively 'org-table-recalculate))
19220 ;; Convert all lines in region to list items
19221 (call-interactively 'org-toggle-heading))))
19223 (defun org-ctrl-c-minus ()
19224 "Insert separator line in table or modify bullet status of line.
19225 Also turns a plain line or a region of lines into list items.
19226 Calls `org-table-insert-hline', `org-toggle-item', or
19227 `org-cycle-list-bullet', depending on context."
19228 (interactive)
19229 (cond
19230 ((org-at-table-p)
19231 (call-interactively 'org-table-insert-hline))
19232 ((org-region-active-p)
19233 (call-interactively 'org-toggle-item))
19234 ((org-in-item-p)
19235 (call-interactively 'org-cycle-list-bullet))
19237 (call-interactively 'org-toggle-item))))
19239 (defun org-toggle-item (arg)
19240 "Convert headings or normal lines to items, items to normal lines.
19241 If there is no active region, only the current line is considered.
19243 If the first non blank line in the region is an headline, convert
19244 all headlines to items, shifting text accordingly.
19246 If it is an item, convert all items to normal lines.
19248 If it is normal text, change region into an item. With a prefix
19249 argument ARG, change each line in region into an item."
19250 (interactive "P")
19251 (let ((shift-text
19252 (function
19253 ;; Shift text in current section to IND, from point to END.
19254 ;; The function leaves point to END line.
19255 (lambda (ind end)
19256 (let ((min-i 1000) (end (copy-marker end)))
19257 ;; First determine the minimum indentation (MIN-I) of
19258 ;; the text.
19259 (save-excursion
19260 (catch 'exit
19261 (while (< (point) end)
19262 (let ((i (org-get-indentation)))
19263 (cond
19264 ;; Skip blank lines and inline tasks.
19265 ((looking-at "^[ \t]*$"))
19266 ((looking-at org-outline-regexp-bol))
19267 ;; We can't find less than 0 indentation.
19268 ((zerop i) (throw 'exit (setq min-i 0)))
19269 ((< i min-i) (setq min-i i))))
19270 (forward-line))))
19271 ;; Then indent each line so that a line indented to
19272 ;; MIN-I becomes indented to IND. Ignore blank lines
19273 ;; and inline tasks in the process.
19274 (let ((delta (- ind min-i)))
19275 (while (< (point) end)
19276 (unless (or (looking-at "^[ \t]*$")
19277 (looking-at org-outline-regexp-bol))
19278 (org-indent-line-to (+ (org-get-indentation) delta)))
19279 (forward-line)))))))
19280 (skip-blanks
19281 (function
19282 ;; Return beginning of first non-blank line, starting from
19283 ;; line at POS.
19284 (lambda (pos)
19285 (save-excursion
19286 (goto-char pos)
19287 (skip-chars-forward " \r\t\n")
19288 (point-at-bol)))))
19289 beg end)
19290 ;; Determine boundaries of changes.
19291 (if (org-region-active-p)
19292 (setq beg (funcall skip-blanks (region-beginning))
19293 end (copy-marker (region-end)))
19294 (setq beg (funcall skip-blanks (point-at-bol))
19295 end (copy-marker (point-at-eol))))
19296 ;; Depending on the starting line, choose an action on the text
19297 ;; between BEG and END.
19298 (org-with-limited-levels
19299 (save-excursion
19300 (goto-char beg)
19301 (cond
19302 ;; Case 1. Start at an item: de-itemize. Note that it only
19303 ;; happens when a region is active: `org-ctrl-c-minus'
19304 ;; would call `org-cycle-list-bullet' otherwise.
19305 ((org-at-item-p)
19306 (while (< (point) end)
19307 (when (org-at-item-p)
19308 (skip-chars-forward " \t")
19309 (delete-region (point) (match-end 0)))
19310 (forward-line)))
19311 ;; Case 2. Start at an heading: convert to items.
19312 ((org-at-heading-p)
19313 (let* ((bul (org-list-bullet-string "-"))
19314 (bul-len (length bul))
19315 ;; Indentation of the first heading. It should be
19316 ;; relative to the indentation of its parent, if any.
19317 (start-ind (save-excursion
19318 (cond
19319 ((not org-adapt-indentation) 0)
19320 ((not (outline-previous-heading)) 0)
19321 (t (length (match-string 0))))))
19322 ;; Level of first heading. Further headings will be
19323 ;; compared to it to determine hierarchy in the list.
19324 (ref-level (org-reduced-level (org-outline-level))))
19325 (while (< (point) end)
19326 (let* ((level (org-reduced-level (org-outline-level)))
19327 (delta (max 0 (- level ref-level))))
19328 ;; If current headline is less indented than the first
19329 ;; one, set it as reference, in order to preserve
19330 ;; subtrees.
19331 (when (< level ref-level) (setq ref-level level))
19332 (replace-match bul t t)
19333 (org-indent-line-to (+ start-ind (* delta bul-len)))
19334 ;; Ensure all text down to END (or SECTION-END) belongs
19335 ;; to the newly created item.
19336 (let ((section-end (save-excursion
19337 (or (outline-next-heading) (point)))))
19338 (forward-line)
19339 (funcall shift-text
19340 (+ start-ind (* (1+ delta) bul-len))
19341 (min end section-end)))))))
19342 ;; Case 3. Normal line with ARG: turn each non-item line into
19343 ;; an item.
19344 (arg
19345 (while (< (point) end)
19346 (unless (or (org-at-heading-p) (org-at-item-p))
19347 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19348 (replace-match
19349 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19350 (forward-line)))
19351 ;; Case 4. Normal line without ARG: make the first line of
19352 ;; region an item, and shift indentation of others
19353 ;; lines to set them as item's body.
19354 (t (let* ((bul (org-list-bullet-string "-"))
19355 (bul-len (length bul))
19356 (ref-ind (org-get-indentation)))
19357 (skip-chars-forward " \t")
19358 (insert bul)
19359 (forward-line)
19360 (while (< (point) end)
19361 ;; Ensure that lines less indented than first one
19362 ;; still get included in item body.
19363 (funcall shift-text
19364 (+ ref-ind bul-len)
19365 (min end (save-excursion (or (outline-next-heading)
19366 (point)))))
19367 (forward-line)))))))))
19369 (defun org-toggle-heading (&optional nstars)
19370 "Convert headings to normal text, or items or text to headings.
19371 If there is no active region, only the current line is considered.
19373 With a \\[universal-argument] prefix, convert the whole list at
19374 point into heading.
19376 In a region:
19378 - If the first non blank line is an headline, remove the stars
19379 from all headlines in the region.
19381 - If it is a normal line turn each and every normal line (i.e. not an
19382 heading or an item) in the region into a heading.
19384 - If it is a plain list item, turn all plain list items into headings.
19386 When converting a line into a heading, the number of stars is chosen
19387 such that the lines become children of the current entry. However,
19388 when a prefix argument is given, its value determines the number of
19389 stars to add."
19390 (interactive "P")
19391 (let ((skip-blanks
19392 (function
19393 ;; Return beginning of first non-blank line, starting from
19394 ;; line at POS.
19395 (lambda (pos)
19396 (save-excursion
19397 (goto-char pos)
19398 (while (org-at-comment-p) (forward-line))
19399 (skip-chars-forward " \r\t\n")
19400 (point-at-bol)))))
19401 beg end toggled)
19402 ;; Determine boundaries of changes. If a universal prefix has
19403 ;; been given, put the list in a region. If region ends at a bol,
19404 ;; do not consider the last line to be in the region.
19406 (when (and current-prefix-arg (org-at-item-p))
19407 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19408 (org-mark-element))
19410 (if (org-region-active-p)
19411 (setq beg (funcall skip-blanks (region-beginning))
19412 end (copy-marker (save-excursion
19413 (goto-char (region-end))
19414 (if (bolp) (point) (point-at-eol)))))
19415 (setq beg (funcall skip-blanks (point-at-bol))
19416 end (copy-marker (point-at-eol))))
19417 ;; Ensure inline tasks don't count as headings.
19418 (org-with-limited-levels
19419 (save-excursion
19420 (goto-char beg)
19421 (cond
19422 ;; Case 1. Started at an heading: de-star headings.
19423 ((org-at-heading-p)
19424 (while (< (point) end)
19425 (when (org-at-heading-p t)
19426 (looking-at org-outline-regexp) (replace-match "")
19427 (setq toggled t))
19428 (forward-line)))
19429 ;; Case 2. Started at an item: change items into headlines.
19430 ;; One star will be added by `org-list-to-subtree'.
19431 ((org-at-item-p)
19432 (let* ((stars (make-string
19433 (if nstars
19434 ;; subtract the star that will be added again by
19435 ;; `org-list-to-subtree'
19436 (1- (prefix-numeric-value current-prefix-arg))
19437 (or (org-current-level) 0))
19438 ?*))
19439 (add-stars
19440 (cond (nstars "") ; stars from prefix only
19441 ((equal stars "") "") ; before first heading
19442 (org-odd-levels-only "*") ; inside heading, odd
19443 (t "")))) ; inside heading, oddeven
19444 (while (< (point) end)
19445 (when (org-at-item-p)
19446 ;; Pay attention to cases when region ends before list.
19447 (let* ((struct (org-list-struct))
19448 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19449 (save-restriction
19450 (narrow-to-region (point) list-end)
19451 (insert
19452 (org-list-to-subtree
19453 (org-list-parse-list t)
19454 '(:istart (concat stars add-stars (funcall get-stars depth))
19455 :icount (concat stars add-stars (funcall get-stars depth)))))))
19456 (setq toggled t))
19457 (forward-line))))
19458 ;; Case 3. Started at normal text: make every line an heading,
19459 ;; skipping headlines and items.
19460 (t (let* ((stars (make-string
19461 (if nstars
19462 (prefix-numeric-value current-prefix-arg)
19463 (or (org-current-level) 0))
19464 ?*))
19465 (add-stars
19466 (cond (nstars "") ; stars from prefix only
19467 ((equal stars "") "*") ; before first heading
19468 (org-odd-levels-only "**") ; inside heading, odd
19469 (t "*"))) ; inside heading, oddeven
19470 (rpl (concat stars add-stars " ")))
19471 (while (< (point) end)
19472 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19473 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19474 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19475 (forward-line)))))))
19476 (unless toggled (message "Cannot toggle heading from here"))))
19478 (defun org-meta-return (&optional arg)
19479 "Insert a new heading or wrap a region in a table.
19480 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19481 See the individual commands for more information."
19482 (interactive "P")
19483 (cond
19484 ((run-hook-with-args-until-success 'org-metareturn-hook))
19485 ((or (org-at-drawer-p) (org-at-property-p))
19486 (newline-and-indent))
19487 ((org-at-table-p)
19488 (call-interactively 'org-table-wrap-region))
19489 (t (call-interactively 'org-insert-heading))))
19491 ;;; Menu entries
19493 ;; Define the Org-mode menus
19494 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19495 '("Tbl"
19496 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19497 ["Next Field" org-cycle (org-at-table-p)]
19498 ["Previous Field" org-shifttab (org-at-table-p)]
19499 ["Next Row" org-return (org-at-table-p)]
19500 "--"
19501 ["Blank Field" org-table-blank-field (org-at-table-p)]
19502 ["Edit Field" org-table-edit-field (org-at-table-p)]
19503 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19504 "--"
19505 ("Column"
19506 ["Move Column Left" org-metaleft (org-at-table-p)]
19507 ["Move Column Right" org-metaright (org-at-table-p)]
19508 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19509 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19510 ("Row"
19511 ["Move Row Up" org-metaup (org-at-table-p)]
19512 ["Move Row Down" org-metadown (org-at-table-p)]
19513 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19514 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19515 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19516 "--"
19517 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19518 ("Rectangle"
19519 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19520 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19521 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19522 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19523 "--"
19524 ("Calculate"
19525 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19526 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19527 ["Edit Formulas" org-edit-special (org-at-table-p)]
19528 "--"
19529 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19530 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19531 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19532 "--"
19533 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19534 "--"
19535 ["Sum Column/Rectangle" org-table-sum
19536 (or (org-at-table-p) (org-region-active-p))]
19537 ["Which Column?" org-table-current-column (org-at-table-p)])
19538 ["Debug Formulas"
19539 org-table-toggle-formula-debugger
19540 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19541 ["Show Col/Row Numbers"
19542 org-table-toggle-coordinate-overlays
19543 :style toggle
19544 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19545 "--"
19546 ["Create" org-table-create (and (not (org-at-table-p))
19547 org-enable-table-editor)]
19548 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19549 ["Import from File" org-table-import (not (org-at-table-p))]
19550 ["Export to File" org-table-export (org-at-table-p)]
19551 "--"
19552 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19554 (easy-menu-define org-org-menu org-mode-map "Org menu"
19555 '("Org"
19556 ("Show/Hide"
19557 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19558 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19559 ["Sparse Tree..." org-sparse-tree t]
19560 ["Reveal Context" org-reveal t]
19561 ["Show All" show-all t]
19562 "--"
19563 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19564 "--"
19565 ["New Heading" org-insert-heading t]
19566 ("Navigate Headings"
19567 ["Up" outline-up-heading t]
19568 ["Next" outline-next-visible-heading t]
19569 ["Previous" outline-previous-visible-heading t]
19570 ["Next Same Level" outline-forward-same-level t]
19571 ["Previous Same Level" outline-backward-same-level t]
19572 "--"
19573 ["Jump" org-goto t])
19574 ("Edit Structure"
19575 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19576 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19577 "--"
19578 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19579 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19580 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19581 "--"
19582 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19583 "--"
19584 ["Copy visible text" org-copy-visible t]
19585 "--"
19586 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19587 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19588 ["Demote Heading" org-metaright (not (org-at-table-p))]
19589 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19590 "--"
19591 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19592 "--"
19593 ["Convert to odd levels" org-convert-to-odd-levels t]
19594 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19595 ("Editing"
19596 ["Emphasis..." org-emphasize t]
19597 ["Edit Source Example" org-edit-special t]
19598 "--"
19599 ["Footnote new/jump" org-footnote-action t]
19600 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19601 ("Archive"
19602 ["Archive (default method)" org-archive-subtree-default t]
19603 "--"
19604 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19605 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19606 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19608 "--"
19609 ("Hyperlinks"
19610 ["Store Link (Global)" org-store-link t]
19611 ["Find existing link to here" org-occur-link-in-agenda-files t]
19612 ["Insert Link" org-insert-link t]
19613 ["Follow Link" org-open-at-point t]
19614 "--"
19615 ["Next link" org-next-link t]
19616 ["Previous link" org-previous-link t]
19617 "--"
19618 ["Descriptive Links"
19619 org-toggle-link-display
19620 :style radio
19621 :selected org-descriptive-links
19623 ["Literal Links"
19624 org-toggle-link-display
19625 :style radio
19626 :selected (not org-descriptive-links)])
19627 "--"
19628 ("TODO Lists"
19629 ["TODO/DONE/-" org-todo t]
19630 ("Select keyword"
19631 ["Next keyword" org-shiftright (org-at-heading-p)]
19632 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19633 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19634 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19635 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19636 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19637 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19638 "--"
19639 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19640 :selected org-enforce-todo-dependencies :style toggle :active t]
19641 "Settings for tree at point"
19642 ["Do Children sequentially" org-toggle-ordered-property :style radio
19643 :selected (org-entry-get nil "ORDERED")
19644 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19645 ["Do Children parallel" org-toggle-ordered-property :style radio
19646 :selected (not (org-entry-get nil "ORDERED"))
19647 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19648 "--"
19649 ["Set Priority" org-priority t]
19650 ["Priority Up" org-shiftup t]
19651 ["Priority Down" org-shiftdown t]
19652 "--"
19653 ["Get news from all feeds" org-feed-update-all t]
19654 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19655 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19656 ("TAGS and Properties"
19657 ["Set Tags" org-set-tags-command t]
19658 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19659 "--"
19660 ["Set property" org-set-property t]
19661 ["Column view of properties" org-columns t]
19662 ["Insert Column View DBlock" org-insert-columns-dblock t])
19663 ("Dates and Scheduling"
19664 ["Timestamp" org-time-stamp t]
19665 ["Timestamp (inactive)" org-time-stamp-inactive t]
19666 ("Change Date"
19667 ["1 Day Later" org-shiftright t]
19668 ["1 Day Earlier" org-shiftleft t]
19669 ["1 ... Later" org-shiftup t]
19670 ["1 ... Earlier" org-shiftdown t])
19671 ["Compute Time Range" org-evaluate-time-range t]
19672 ["Schedule Item" org-schedule t]
19673 ["Deadline" org-deadline t]
19674 "--"
19675 ["Custom time format" org-toggle-time-stamp-overlays
19676 :style radio :selected org-display-custom-times]
19677 "--"
19678 ["Goto Calendar" org-goto-calendar t]
19679 ["Date from Calendar" org-date-from-calendar t]
19680 "--"
19681 ["Start/Restart Timer" org-timer-start t]
19682 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19683 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19684 ["Insert Timer String" org-timer t]
19685 ["Insert Timer Item" org-timer-item t])
19686 ("Logging work"
19687 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19688 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19689 ["Clock out" org-clock-out t]
19690 ["Clock cancel" org-clock-cancel t]
19691 "--"
19692 ["Mark as default task" org-clock-mark-default-task t]
19693 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19694 ["Goto running clock" org-clock-goto t]
19695 "--"
19696 ["Display times" org-clock-display t]
19697 ["Create clock table" org-clock-report t]
19698 "--"
19699 ["Record DONE time"
19700 (progn (setq org-log-done (not org-log-done))
19701 (message "Switching to %s will %s record a timestamp"
19702 (car org-done-keywords)
19703 (if org-log-done "automatically" "not")))
19704 :style toggle :selected org-log-done])
19705 "--"
19706 ["Agenda Command..." org-agenda t]
19707 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19708 ("File List for Agenda")
19709 ("Special views current file"
19710 ["TODO Tree" org-show-todo-tree t]
19711 ["Check Deadlines" org-check-deadlines t]
19712 ["Timeline" org-timeline t]
19713 ["Tags/Property tree" org-match-sparse-tree t])
19714 "--"
19715 ["Export/Publish..." org-export t]
19716 ("LaTeX"
19717 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19718 :selected org-cdlatex-mode]
19719 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19720 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19721 ["Modify math symbol" org-cdlatex-math-modify
19722 (org-inside-LaTeX-fragment-p)]
19723 ["Insert citation" org-reftex-citation t]
19724 "--"
19725 ["Template for BEAMER" (progn (require 'org-beamer)
19726 (org-insert-beamer-options-template)) t])
19727 "--"
19728 ("MobileOrg"
19729 ["Push Files and Views" org-mobile-push t]
19730 ["Get Captured and Flagged" org-mobile-pull t]
19731 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19732 "--"
19733 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19734 "--"
19735 ("Documentation"
19736 ["Show Version" org-version t]
19737 ["Info Documentation" org-info t])
19738 ("Customize"
19739 ["Browse Org Group" org-customize t]
19740 "--"
19741 ["Expand This Menu" org-create-customize-menu
19742 (fboundp 'customize-menu-create)])
19743 ["Send bug report" org-submit-bug-report t]
19744 "--"
19745 ("Refresh/Reload"
19746 ["Refresh setup current buffer" org-mode-restart t]
19747 ["Reload Org (after update)" org-reload t]
19748 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19751 (defun org-info (&optional node)
19752 "Read documentation for Org-mode in the info system.
19753 With optional NODE, go directly to that node."
19754 (interactive)
19755 (info (format "(org)%s" (or node ""))))
19757 ;;;###autoload
19758 (defun org-submit-bug-report ()
19759 "Submit a bug report on Org-mode via mail.
19761 Don't hesitate to report any problems or inaccurate documentation.
19763 If you don't have setup sending mail from (X)Emacs, please copy the
19764 output buffer into your mail program, as it gives us important
19765 information about your Org-mode version and configuration."
19766 (interactive)
19767 (require 'reporter)
19768 (org-load-modules-maybe)
19769 (org-require-autoloaded-modules)
19770 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19771 (reporter-submit-bug-report
19772 "emacs-orgmode@gnu.org"
19773 (org-version nil 'full)
19774 (let (list)
19775 (save-window-excursion
19776 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19777 (delete-other-windows)
19778 (erase-buffer)
19779 (insert "You are about to submit a bug report to the Org-mode mailing list.
19781 We would like to add your full Org-mode and Outline configuration to the
19782 bug report. This greatly simplifies the work of the maintainer and
19783 other experts on the mailing list.
19785 HOWEVER, some variables you have customized may contain private
19786 information. The names of customers, colleagues, or friends, might
19787 appear in the form of file names, tags, todo states, or search strings.
19788 If you answer yes to the prompt, you might want to check and remove
19789 such private information before sending the email.")
19790 (add-text-properties (point-min) (point-max) '(face org-warning))
19791 (when (yes-or-no-p "Include your Org-mode configuration ")
19792 (mapatoms
19793 (lambda (v)
19794 (and (boundp v)
19795 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19796 (or (and (symbol-value v)
19797 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19798 (and
19799 (get v 'custom-type) (get v 'standard-value)
19800 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19801 (push v list)))))
19802 (kill-buffer (get-buffer "*Warn about privacy*"))
19803 list))
19804 nil nil
19805 "Remember to cover the basics, that is, what you expected to happen and
19806 what in fact did happen. You don't know how to make a good report? See
19808 http://orgmode.org/manual/Feedback.html#Feedback
19810 Your bug report will be posted to the Org-mode mailing list.
19811 ------------------------------------------------------------------------")
19812 (save-excursion
19813 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19814 (replace-match "\\1Bug: \\3 [\\2]")))))
19817 (defun org-install-agenda-files-menu ()
19818 (let ((bl (buffer-list)))
19819 (save-excursion
19820 (while bl
19821 (set-buffer (pop bl))
19822 (if (derived-mode-p 'org-mode) (setq bl nil)))
19823 (when (derived-mode-p 'org-mode)
19824 (easy-menu-change
19825 '("Org") "File List for Agenda"
19826 (append
19827 (list
19828 ["Edit File List" (org-edit-agenda-file-list) t]
19829 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19830 ["Remove Current File from List" org-remove-file t]
19831 ["Cycle through agenda files" org-cycle-agenda-files t]
19832 ["Occur in all agenda files" org-occur-in-agenda-files t]
19833 "--")
19834 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19836 ;;;; Documentation
19838 ;;;###autoload
19839 (defun org-require-autoloaded-modules ()
19840 (interactive)
19841 (mapc 'require
19842 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19843 org-docbook org-exp org-html org-icalendar
19844 org-id org-latex
19845 org-publish org-remember org-table
19846 org-timer org-xoxo)))
19848 ;;;###autoload
19849 (defun org-reload (&optional uncompiled)
19850 "Reload all org lisp files.
19851 With prefix arg UNCOMPILED, load the uncompiled versions."
19852 (interactive "P")
19853 (require 'find-func)
19854 (let* ((file-re "^org\\(-.*\\)?\\.el")
19855 (dir-org (file-name-directory (org-find-library-dir "org")))
19856 (dir-org-contrib (ignore-errors
19857 (file-name-directory
19858 (org-find-library-dir "org-contribdir"))))
19859 (babel-files
19860 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19861 (append (list nil "comint" "eval" "exp" "keys"
19862 "lob" "ref" "table" "tangle")
19863 (delq nil
19864 (mapcar
19865 (lambda (lang)
19866 (when (cdr lang) (symbol-name (car lang))))
19867 org-babel-load-languages)))))
19868 (files
19869 (append babel-files
19870 (and dir-org-contrib
19871 (directory-files dir-org-contrib t file-re))
19872 (directory-files dir-org t file-re)))
19873 (remove-re (concat (if (featurep 'xemacs)
19874 "org-colview" "org-colview-xemacs")
19875 "\\'")))
19876 (setq files (mapcar 'file-name-sans-extension files))
19877 (setq files (mapcar
19878 (lambda (x) (if (string-match remove-re x) nil x))
19879 files))
19880 (setq files (delq nil files))
19881 (mapc
19882 (lambda (f)
19883 (when (featurep (intern (file-name-nondirectory f)))
19884 (if (and (not uncompiled)
19885 (file-exists-p (concat f ".elc")))
19886 (load (concat f ".elc") nil nil 'nosuffix)
19887 (load (concat f ".el") nil nil 'nosuffix))))
19888 files)
19889 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19890 (org-version nil 'full 'message))
19892 ;;;###autoload
19893 (defun org-customize ()
19894 "Call the customize function with org as argument."
19895 (interactive)
19896 (org-load-modules-maybe)
19897 (org-require-autoloaded-modules)
19898 (customize-browse 'org))
19900 (defun org-create-customize-menu ()
19901 "Create a full customization menu for Org-mode, insert it into the menu."
19902 (interactive)
19903 (org-load-modules-maybe)
19904 (org-require-autoloaded-modules)
19905 (if (fboundp 'customize-menu-create)
19906 (progn
19907 (easy-menu-change
19908 '("Org") "Customize"
19909 `(["Browse Org group" org-customize t]
19910 "--"
19911 ,(customize-menu-create 'org)
19912 ["Set" Custom-set t]
19913 ["Save" Custom-save t]
19914 ["Reset to Current" Custom-reset-current t]
19915 ["Reset to Saved" Custom-reset-saved t]
19916 ["Reset to Standard Settings" Custom-reset-standard t]))
19917 (message "\"Org\"-menu now contains full customization menu"))
19918 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19920 ;;;; Miscellaneous stuff
19922 ;;; Generally useful functions
19924 (defun org-get-at-bol (property)
19925 "Get text property PROPERTY at beginning of line."
19926 (get-text-property (point-at-bol) property))
19928 (defun org-find-text-property-in-string (prop s)
19929 "Return the first non-nil value of property PROP in string S."
19930 (or (get-text-property 0 prop s)
19931 (get-text-property (or (next-single-property-change 0 prop s) 0)
19932 prop s)))
19934 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19935 "Display the given MESSAGE as a warning."
19936 (if (fboundp 'display-warning)
19937 (display-warning 'org message
19938 (if (featurep 'xemacs) 'warning :warning))
19939 (let ((buf (get-buffer-create "*Org warnings*")))
19940 (with-current-buffer buf
19941 (goto-char (point-max))
19942 (insert "Warning (Org): " message)
19943 (unless (bolp)
19944 (newline)))
19945 (display-buffer buf)
19946 (sit-for 0))))
19948 (defun org-eval (form)
19949 "Eval FORM and return result."
19950 (condition-case error
19951 (eval form)
19952 (error (format "%%![Error: %s]" error))))
19954 (defun org-in-clocktable-p ()
19955 "Check if the cursor is in a clocktable."
19956 (let ((pos (point)) start)
19957 (save-excursion
19958 (end-of-line 1)
19959 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19960 (setq start (match-beginning 0))
19961 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19962 (>= (match-end 0) pos)
19963 start))))
19965 (defun org-in-commented-line ()
19966 "Is point in a line starting with `#'?"
19967 (equal (char-after (point-at-bol)) ?#))
19969 (defun org-in-indented-comment-line ()
19970 "Is point in a line starting with `#' after some white space?"
19971 (save-excursion
19972 (save-match-data
19973 (goto-char (point-at-bol))
19974 (looking-at "[ \t]*#"))))
19976 (defun org-in-verbatim-emphasis ()
19977 (save-match-data
19978 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19980 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19981 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19982 (if (and marker (marker-buffer marker)
19983 (buffer-live-p (marker-buffer marker)))
19984 (progn
19985 (org-pop-to-buffer-same-window (marker-buffer marker))
19986 (if (or (> marker (point-max)) (< marker (point-min)))
19987 (widen))
19988 (goto-char marker)
19989 (org-show-context 'org-goto))
19990 (if bookmark
19991 (bookmark-jump bookmark)
19992 (error "Cannot find location"))))
19994 (defun org-quote-csv-field (s)
19995 "Quote field for inclusion in CSV material."
19996 (if (string-match "[\",]" s)
19997 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20000 (defun org-force-self-insert (N)
20001 "Needed to enforce self-insert under remapping."
20002 (interactive "p")
20003 (self-insert-command N))
20005 (defun org-string-width (s)
20006 "Compute width of string, ignoring invisible characters.
20007 This ignores character with invisibility property `org-link', and also
20008 characters with property `org-cwidth', because these will become invisible
20009 upon the next fontification round."
20010 (let (b l)
20011 (when (or (eq t buffer-invisibility-spec)
20012 (assq 'org-link buffer-invisibility-spec))
20013 (while (setq b (text-property-any 0 (length s)
20014 'invisible 'org-link s))
20015 (setq s (concat (substring s 0 b)
20016 (substring s (or (next-single-property-change
20017 b 'invisible s) (length s)))))))
20018 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20019 (setq s (concat (substring s 0 b)
20020 (substring s (or (next-single-property-change
20021 b 'org-cwidth s) (length s))))))
20022 (setq l (string-width s) b -1)
20023 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20024 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20027 (defun org-shorten-string (s maxlength)
20028 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20029 If the string is shorter or has length MAXLENGTH, just return the
20030 original string. If it is longer, the functions finds a space in the
20031 string, breaks this string off at that locations and adds three dots
20032 as ellipsis. Including the ellipsis, the string will not be longer
20033 than MAXLENGTH. If finding a good breaking point in the string does
20034 not work, the string is just chopped off in the middle of a word
20035 if necessary."
20036 (if (<= (length s) maxlength)
20038 (let* ((n (max (- maxlength 4) 1))
20039 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20040 (if (string-match re s)
20041 (concat (match-string 1 s) "...")
20042 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20044 (defun org-get-indentation (&optional line)
20045 "Get the indentation of the current line, interpreting tabs.
20046 When LINE is given, assume it represents a line and compute its indentation."
20047 (if line
20048 (if (string-match "^ *" (org-remove-tabs line))
20049 (match-end 0))
20050 (save-excursion
20051 (beginning-of-line 1)
20052 (skip-chars-forward " \t")
20053 (current-column))))
20055 (defun org-get-string-indentation (s)
20056 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20057 (let ((n -1) (i 0) (w tab-width) c)
20058 (catch 'exit
20059 (while (< (setq n (1+ n)) (length s))
20060 (setq c (aref s n))
20061 (cond ((= c ?\ ) (setq i (1+ i)))
20062 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20063 (t (throw 'exit t)))))
20066 (defun org-remove-tabs (s &optional width)
20067 "Replace tabulators in S with spaces.
20068 Assumes that s is a single line, starting in column 0."
20069 (setq width (or width tab-width))
20070 (while (string-match "\t" s)
20071 (setq s (replace-match
20072 (make-string
20073 (- (* width (/ (+ (match-beginning 0) width) width))
20074 (match-beginning 0)) ?\ )
20075 t t s)))
20078 (defun org-fix-indentation (line ind)
20079 "Fix indentation in LINE.
20080 IND is a cons cell with target and minimum indentation.
20081 If the current indentation in LINE is smaller than the minimum,
20082 leave it alone. If it is larger than ind, set it to the target."
20083 (let* ((l (org-remove-tabs line))
20084 (i (org-get-indentation l))
20085 (i1 (car ind)) (i2 (cdr ind)))
20086 (if (>= i i2) (setq l (substring line i2)))
20087 (if (> i1 0)
20088 (concat (make-string i1 ?\ ) l)
20089 l)))
20091 (defun org-remove-indentation (code &optional n)
20092 "Remove the maximum common indentation from the lines in CODE.
20093 N may optionally be the number of spaces to remove."
20094 (with-temp-buffer
20095 (insert code)
20096 (org-do-remove-indentation n)
20097 (buffer-string)))
20099 (defun org-do-remove-indentation (&optional n)
20100 "Remove the maximum common indentation from the buffer."
20101 (untabify (point-min) (point-max))
20102 (let ((min 10000) re)
20103 (if n
20104 (setq min n)
20105 (goto-char (point-min))
20106 (while (re-search-forward "^ *[^ \n]" nil t)
20107 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20108 (unless (or (= min 0) (= min 10000))
20109 (setq re (format "^ \\{%d\\}" min))
20110 (goto-char (point-min))
20111 (while (re-search-forward re nil t)
20112 (replace-match "")
20113 (end-of-line 1))
20114 min)))
20116 (defun org-fill-template (template alist)
20117 "Find each %key of ALIST in TEMPLATE and replace it."
20118 (let ((case-fold-search nil)
20119 entry key value)
20120 (setq alist (sort (copy-sequence alist)
20121 (lambda (a b) (< (length (car a)) (length (car b))))))
20122 (while (setq entry (pop alist))
20123 (setq template
20124 (replace-regexp-in-string
20125 (concat "%" (regexp-quote (car entry)))
20126 (cdr entry) template t t)))
20127 template))
20129 (defun org-base-buffer (buffer)
20130 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20131 (if (not buffer)
20132 buffer
20133 (or (buffer-base-buffer buffer)
20134 buffer)))
20136 (defun org-trim (s)
20137 "Remove whitespace at beginning and end of string."
20138 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20139 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20142 (defun org-wrap (string &optional width lines)
20143 "Wrap string to either a number of lines, or a width in characters.
20144 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20145 that costs. If there is a word longer than WIDTH, the text is actually
20146 wrapped to the length of that word.
20147 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20148 many lines, whatever width that takes.
20149 The return value is a list of lines, without newlines at the end."
20150 (let* ((words (org-split-string string "[ \t\n]+"))
20151 (maxword (apply 'max (mapcar 'org-string-width words)))
20152 w ll)
20153 (cond (width
20154 (org-do-wrap words (max maxword width)))
20155 (lines
20156 (setq w maxword)
20157 (setq ll (org-do-wrap words maxword))
20158 (if (<= (length ll) lines)
20160 (setq ll words)
20161 (while (> (length ll) lines)
20162 (setq w (1+ w))
20163 (setq ll (org-do-wrap words w)))
20164 ll))
20165 (t (error "Cannot wrap this")))))
20167 (defun org-do-wrap (words width)
20168 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20169 (let (lines line)
20170 (while words
20171 (setq line (pop words))
20172 (while (and words (< (+ (length line) (length (car words))) width))
20173 (setq line (concat line " " (pop words))))
20174 (setq lines (push line lines)))
20175 (nreverse lines)))
20177 (defun org-split-string (string &optional separators)
20178 "Splits STRING into substrings at SEPARATORS.
20179 No empty strings are returned if there are matches at the beginning
20180 and end of string."
20181 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20182 (start 0)
20183 notfirst
20184 (list nil))
20185 (while (and (string-match rexp string
20186 (if (and notfirst
20187 (= start (match-beginning 0))
20188 (< start (length string)))
20189 (1+ start) start))
20190 (< (match-beginning 0) (length string)))
20191 (setq notfirst t)
20192 (or (eq (match-beginning 0) 0)
20193 (and (eq (match-beginning 0) (match-end 0))
20194 (eq (match-beginning 0) start))
20195 (setq list
20196 (cons (substring string start (match-beginning 0))
20197 list)))
20198 (setq start (match-end 0)))
20199 (or (eq start (length string))
20200 (setq list
20201 (cons (substring string start)
20202 list)))
20203 (nreverse list)))
20205 (defun org-quote-vert (s)
20206 "Replace \"|\" with \"\\vert\"."
20207 (while (string-match "|" s)
20208 (setq s (replace-match "\\vert" t t s)))
20211 (defun org-uuidgen-p (s)
20212 "Is S an ID created by UUIDGEN?"
20213 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20215 (defun org-in-src-block-p nil
20216 "Whether point is in a code source block."
20217 (let (ov)
20218 (when (setq ov (overlays-at (point)))
20219 (memq 'org-block-background
20220 (overlay-properties
20221 (car ov))))))
20223 (defun org-context ()
20224 "Return a list of contexts of the current cursor position.
20225 If several contexts apply, all are returned.
20226 Each context entry is a list with a symbol naming the context, and
20227 two positions indicating start and end of the context. Possible
20228 contexts are:
20230 :headline anywhere in a headline
20231 :headline-stars on the leading stars in a headline
20232 :todo-keyword on a TODO keyword (including DONE) in a headline
20233 :tags on the TAGS in a headline
20234 :priority on the priority cookie in a headline
20235 :item on the first line of a plain list item
20236 :item-bullet on the bullet/number of a plain list item
20237 :checkbox on the checkbox in a plain list item
20238 :table in an org-mode table
20239 :table-special on a special filed in a table
20240 :table-table in a table.el table
20241 :clocktable in a clocktable
20242 :src-block in a source block
20243 :link on a hyperlink
20244 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20245 :target on a <<target>>
20246 :radio-target on a <<<radio-target>>>
20247 :latex-fragment on a LaTeX fragment
20248 :latex-preview on a LaTeX fragment with overlaid preview image
20250 This function expects the position to be visible because it uses font-lock
20251 faces as a help to recognize the following contexts: :table-special, :link,
20252 and :keyword."
20253 (let* ((f (get-text-property (point) 'face))
20254 (faces (if (listp f) f (list f)))
20255 (case-fold-search t)
20256 (p (point)) clist o)
20257 ;; First the large context
20258 (cond
20259 ((org-at-heading-p t)
20260 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20261 (when (progn
20262 (beginning-of-line 1)
20263 (looking-at org-todo-line-tags-regexp))
20264 (push (org-point-in-group p 1 :headline-stars) clist)
20265 (push (org-point-in-group p 2 :todo-keyword) clist)
20266 (push (org-point-in-group p 4 :tags) clist))
20267 (goto-char p)
20268 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20269 (if (looking-at "\\[#[A-Z0-9]\\]")
20270 (push (org-point-in-group p 0 :priority) clist)))
20272 ((org-at-item-p)
20273 (push (org-point-in-group p 2 :item-bullet) clist)
20274 (push (list :item (point-at-bol)
20275 (save-excursion (org-end-of-item) (point)))
20276 clist)
20277 (and (org-at-item-checkbox-p)
20278 (push (org-point-in-group p 0 :checkbox) clist)))
20280 ((org-at-table-p)
20281 (push (list :table (org-table-begin) (org-table-end)) clist)
20282 (if (memq 'org-formula faces)
20283 (push (list :table-special
20284 (previous-single-property-change p 'face)
20285 (next-single-property-change p 'face)) clist)))
20286 ((org-at-table-p 'any)
20287 (push (list :table-table) clist)))
20288 (goto-char p)
20290 ;; New the "medium" contexts: clocktables, source blocks
20291 (cond ((org-in-clocktable-p)
20292 (push (list :clocktable
20293 (and (or (looking-at "#\\+BEGIN: clocktable")
20294 (search-backward "#+BEGIN: clocktable" nil t))
20295 (match-beginning 0))
20296 (and (re-search-forward "#\\+END:?" nil t)
20297 (match-end 0))) clist))
20298 ((org-in-src-block-p)
20299 (push (list :src-block
20300 (and (or (looking-at "#\\+BEGIN_SRC")
20301 (search-backward "#+BEGIN_SRC" nil t))
20302 (match-beginning 0))
20303 (and (search-forward "#+END_SRC" nil t)
20304 (match-beginning 0))) clist)))
20305 (goto-char p)
20307 ;; Now the small context
20308 (cond
20309 ((org-at-timestamp-p)
20310 (push (org-point-in-group p 0 :timestamp) clist))
20311 ((memq 'org-link faces)
20312 (push (list :link
20313 (previous-single-property-change p 'face)
20314 (next-single-property-change p 'face)) clist))
20315 ((memq 'org-special-keyword faces)
20316 (push (list :keyword
20317 (previous-single-property-change p 'face)
20318 (next-single-property-change p 'face)) clist))
20319 ((org-at-target-p)
20320 (push (org-point-in-group p 0 :target) clist)
20321 (goto-char (1- (match-beginning 0)))
20322 (if (looking-at org-radio-target-regexp)
20323 (push (org-point-in-group p 0 :radio-target) clist))
20324 (goto-char p))
20325 ((setq o (car (delq nil
20326 (mapcar
20327 (lambda (x)
20328 (if (memq x org-latex-fragment-image-overlays) x))
20329 (overlays-at (point))))))
20330 (push (list :latex-fragment
20331 (overlay-start o) (overlay-end o)) clist)
20332 (push (list :latex-preview
20333 (overlay-start o) (overlay-end o)) clist))
20334 ((org-inside-LaTeX-fragment-p)
20335 ;; FIXME: positions wrong.
20336 (push (list :latex-fragment (point) (point)) clist)))
20338 (setq clist (nreverse (delq nil clist)))
20339 clist))
20341 ;; FIXME: Compare with at-regexp-p Do we need both?
20342 (defun org-in-regexp (re &optional nlines visually)
20343 "Check if point is inside a match of regexp.
20344 Normally only the current line is checked, but you can include NLINES extra
20345 lines both before and after point into the search.
20346 If VISUALLY is set, require that the cursor is not after the match but
20347 really on, so that the block visually is on the match."
20348 (catch 'exit
20349 (let ((pos (point))
20350 (eol (point-at-eol (+ 1 (or nlines 0))))
20351 (inc (if visually 1 0)))
20352 (save-excursion
20353 (beginning-of-line (- 1 (or nlines 0)))
20354 (while (re-search-forward re eol t)
20355 (if (and (<= (match-beginning 0) pos)
20356 (>= (+ inc (match-end 0)) pos))
20357 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20359 (defun org-at-regexp-p (regexp)
20360 "Is point inside a match of REGEXP in the current line?"
20361 (catch 'exit
20362 (save-excursion
20363 (let ((pos (point)) (end (point-at-eol)))
20364 (beginning-of-line 1)
20365 (while (re-search-forward regexp end t)
20366 (if (and (<= (match-beginning 0) pos)
20367 (>= (match-end 0) pos))
20368 (throw 'exit t)))
20369 nil))))
20371 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20372 "Non-nil when point is between matches of START-RE and END-RE.
20374 Also return a non-nil value when point is on one of the matches.
20376 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20377 buffer positions. Default values are the positions of headlines
20378 surrounding the point.
20380 The functions returns a cons cell whose car (resp. cdr) is the
20381 position before START-RE (resp. after END-RE)."
20382 (save-match-data
20383 (let ((pos (point))
20384 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20385 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20386 beg end)
20387 (save-excursion
20388 ;; Point is on a block when on START-RE or if START-RE can be
20389 ;; found before it...
20390 (and (or (org-at-regexp-p start-re)
20391 (re-search-backward start-re limit-up t))
20392 (setq beg (match-beginning 0))
20393 ;; ... and END-RE after it...
20394 (goto-char (match-end 0))
20395 (re-search-forward end-re limit-down t)
20396 (> (setq end (match-end 0)) pos)
20397 ;; ... without another START-RE in-between.
20398 (goto-char (match-beginning 0))
20399 (not (re-search-backward start-re (1+ beg) t))
20400 ;; Return value.
20401 (cons beg end))))))
20403 (defun org-in-block-p (names)
20404 "Non-nil when point belongs to a block whose name belongs to NAMES.
20406 NAMES is a list of strings containing names of blocks.
20408 Return first block name matched, or nil. Beware that in case of
20409 nested blocks, the returned name may not belong to the closest
20410 block from point."
20411 (save-match-data
20412 (catch 'exit
20413 (let ((case-fold-search t)
20414 (lim-up (save-excursion (outline-previous-heading)))
20415 (lim-down (save-excursion (outline-next-heading))))
20416 (mapc (lambda (name)
20417 (let ((n (regexp-quote name)))
20418 (when (org-between-regexps-p
20419 (concat "^[ \t]*#\\+begin_" n)
20420 (concat "^[ \t]*#\\+end_" n)
20421 lim-up lim-down)
20422 (throw 'exit n))))
20423 names))
20424 nil)))
20426 (defun org-occur-in-agenda-files (regexp &optional nlines)
20427 "Call `multi-occur' with buffers for all agenda files."
20428 (interactive "sOrg-files matching: \np")
20429 (let* ((files (org-agenda-files))
20430 (tnames (mapcar 'file-truename files))
20431 (extra org-agenda-text-search-extra-files)
20433 (when (eq (car extra) 'agenda-archives)
20434 (setq extra (cdr extra))
20435 (setq files (org-add-archive-files files)))
20436 (while (setq f (pop extra))
20437 (unless (member (file-truename f) tnames)
20438 (add-to-list 'files f 'append)
20439 (add-to-list 'tnames (file-truename f) 'append)))
20440 (multi-occur
20441 (mapcar (lambda (x)
20442 (with-current-buffer
20443 (or (get-file-buffer x) (find-file-noselect x))
20444 (widen)
20445 (current-buffer)))
20446 files)
20447 regexp)))
20449 (if (boundp 'occur-mode-find-occurrence-hook)
20450 ;; Emacs 23
20451 (add-hook 'occur-mode-find-occurrence-hook
20452 (lambda ()
20453 (when (derived-mode-p 'org-mode)
20454 (org-reveal))))
20455 ;; Emacs 22
20456 (defadvice occur-mode-goto-occurrence
20457 (after org-occur-reveal activate)
20458 (and (derived-mode-p 'org-mode) (org-reveal)))
20459 (defadvice occur-mode-goto-occurrence-other-window
20460 (after org-occur-reveal activate)
20461 (and (derived-mode-p 'org-mode) (org-reveal)))
20462 (defadvice occur-mode-display-occurrence
20463 (after org-occur-reveal activate)
20464 (when (derived-mode-p 'org-mode)
20465 (let ((pos (occur-mode-find-occurrence)))
20466 (with-current-buffer (marker-buffer pos)
20467 (save-excursion
20468 (goto-char pos)
20469 (org-reveal)))))))
20471 (defun org-occur-link-in-agenda-files ()
20472 "Create a link and search for it in the agendas.
20473 The link is not stored in `org-stored-links', it is just created
20474 for the search purpose."
20475 (interactive)
20476 (let ((link (condition-case nil
20477 (org-store-link nil)
20478 (error "Unable to create a link to here"))))
20479 (org-occur-in-agenda-files (regexp-quote link))))
20481 (defun org-uniquify (list)
20482 "Remove duplicate elements from LIST."
20483 (let (res)
20484 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20485 res))
20487 (defun org-delete-all (elts list)
20488 "Remove all elements in ELTS from LIST."
20489 (while elts
20490 (setq list (delete (pop elts) list)))
20491 list)
20493 (defun org-count (cl-item cl-seq)
20494 "Count the number of occurrences of ITEM in SEQ.
20495 Taken from `count' in cl-seq.el with all keyword arguments removed."
20496 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20497 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20498 (while (< cl-start cl-end)
20499 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20500 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20501 (setq cl-start (1+ cl-start)))
20502 cl-count))
20504 (defun org-remove-if (predicate seq)
20505 "Remove everything from SEQ that fulfills PREDICATE."
20506 (let (res e)
20507 (while seq
20508 (setq e (pop seq))
20509 (if (not (funcall predicate e)) (push e res)))
20510 (nreverse res)))
20512 (defun org-remove-if-not (predicate seq)
20513 "Remove everything from SEQ that does not fulfill PREDICATE."
20514 (let (res e)
20515 (while seq
20516 (setq e (pop seq))
20517 (if (funcall predicate e) (push e res)))
20518 (nreverse res)))
20520 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20521 "Reduce two-argument FUNCTION across SEQ.
20522 Taken from `reduce' in cl-seq.el with all keyword arguments but
20523 \":initial-value\" removed."
20524 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20525 (cadr (memq :initial-value cl-keys)))
20526 (cl-seq (pop cl-seq))
20527 (t (funcall cl-func)))))
20528 (while cl-seq
20529 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20530 cl-accum))
20532 (defun org-back-over-empty-lines ()
20533 "Move backwards over whitespace, to the beginning of the first empty line.
20534 Returns the number of empty lines passed."
20535 (let ((pos (point)))
20536 (if (cdr (assoc 'heading org-blank-before-new-entry))
20537 (skip-chars-backward " \t\n\r")
20538 (unless (eobp)
20539 (forward-line -1)))
20540 (beginning-of-line 2)
20541 (goto-char (min (point) pos))
20542 (count-lines (point) pos)))
20544 (defun org-skip-whitespace ()
20545 (skip-chars-forward " \t\n\r"))
20547 (defun org-point-in-group (point group &optional context)
20548 "Check if POINT is in match-group GROUP.
20549 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20550 match. If the match group does not exist or point is not inside it,
20551 return nil."
20552 (and (match-beginning group)
20553 (>= point (match-beginning group))
20554 (<= point (match-end group))
20555 (if context
20556 (list context (match-beginning group) (match-end group))
20557 t)))
20559 (defun org-switch-to-buffer-other-window (&rest args)
20560 "Switch to buffer in a second window on the current frame.
20561 In particular, do not allow pop-up frames.
20562 Returns the newly created buffer."
20563 (let (pop-up-frames special-display-buffer-names special-display-regexps
20564 special-display-function)
20565 (apply 'switch-to-buffer-other-window args)))
20567 (defun org-combine-plists (&rest plists)
20568 "Create a single property list from all plists in PLISTS.
20569 The process starts by copying the first list, and then setting properties
20570 from the other lists. Settings in the last list are the most significant
20571 ones and overrule settings in the other lists."
20572 (let ((rtn (copy-sequence (pop plists)))
20573 p v ls)
20574 (while plists
20575 (setq ls (pop plists))
20576 (while ls
20577 (setq p (pop ls) v (pop ls))
20578 (setq rtn (plist-put rtn p v))))
20579 rtn))
20581 (defun org-replace-escapes (string table)
20582 "Replace %-escapes in STRING with values in TABLE.
20583 TABLE is an association list with keys like \"%a\" and string values.
20584 The sequences in STRING may contain normal field width and padding information,
20585 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20586 so values can contain further %-escapes if they are define later in TABLE."
20587 (let ((tbl (copy-alist table))
20588 (case-fold-search nil)
20589 (pchg 0)
20590 e re rpl)
20591 (while (setq e (pop tbl))
20592 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20593 (when (and (cdr e) (string-match re (cdr e)))
20594 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20595 (safe "SREF"))
20596 (add-text-properties 0 3 (list 'sref sref) safe)
20597 (setcdr e (replace-match safe t t (cdr e)))))
20598 (while (string-match re string)
20599 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20600 (cdr e)))
20601 (setq string (replace-match rpl t t string))))
20602 (while (setq pchg (next-property-change pchg string))
20603 (let ((sref (get-text-property pchg 'sref string)))
20604 (when (and sref (string-match "SREF" string pchg))
20605 (setq string (replace-match sref t t string)))))
20606 string))
20608 (defun org-sublist (list start end)
20609 "Return a section of LIST, from START to END.
20610 Counting starts at 1."
20611 (let (rtn (c start))
20612 (setq list (nthcdr (1- start) list))
20613 (while (and list (<= c end))
20614 (push (pop list) rtn)
20615 (setq c (1+ c)))
20616 (nreverse rtn)))
20618 (defun org-find-base-buffer-visiting (file)
20619 "Like `find-buffer-visiting' but always return the base buffer and
20620 not an indirect buffer."
20621 (let ((buf (or (get-file-buffer file)
20622 (find-buffer-visiting file))))
20623 (if buf
20624 (or (buffer-base-buffer buf) buf)
20625 nil)))
20627 (defun org-image-file-name-regexp (&optional extensions)
20628 "Return regexp matching the file names of images.
20629 If EXTENSIONS is given, only match these."
20630 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20631 (image-file-name-regexp)
20632 (let ((image-file-name-extensions
20633 (or extensions
20634 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20635 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20636 (concat "\\."
20637 (regexp-opt (nconc (mapcar 'upcase
20638 image-file-name-extensions)
20639 image-file-name-extensions)
20641 "\\'"))))
20643 (defun org-file-image-p (file &optional extensions)
20644 "Return non-nil if FILE is an image."
20645 (save-match-data
20646 (string-match (org-image-file-name-regexp extensions) file)))
20648 (defun org-get-cursor-date ()
20649 "Return the date at cursor in as a time.
20650 This works in the calendar and in the agenda, anywhere else it just
20651 returns the current time."
20652 (let (date day defd)
20653 (cond
20654 ((eq major-mode 'calendar-mode)
20655 (setq date (calendar-cursor-to-date)
20656 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20657 ((eq major-mode 'org-agenda-mode)
20658 (setq day (get-text-property (point) 'day))
20659 (if day
20660 (setq date (calendar-gregorian-from-absolute day)
20661 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20662 (nth 2 date))))))
20663 (or defd (current-time))))
20665 (defvar org-agenda-action-marker (make-marker)
20666 "Marker pointing to the entry for the next agenda action.")
20668 (defun org-mark-entry-for-agenda-action ()
20669 "Mark the current entry as target of an agenda action.
20670 Agenda actions are actions executed from the agenda with the key `k',
20671 which make use of the date at the cursor."
20672 (interactive)
20673 (move-marker org-agenda-action-marker
20674 (save-excursion (org-back-to-heading t) (point))
20675 (current-buffer))
20676 (message
20677 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20679 (defun org-mark-subtree (&optional up)
20680 "Mark the current subtree.
20681 This puts point at the start of the current subtree, and mark at
20682 the end. If a numeric prefix UP is given, move up into the
20683 hierarchy of headlines by UP levels before marking the subtree."
20684 (interactive "P")
20685 (org-with-limited-levels
20686 (cond ((org-at-heading-p) (beginning-of-line))
20687 ((org-before-first-heading-p) (error "Not in a subtree"))
20688 (t (outline-previous-visible-heading 1))))
20689 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20690 (org-mark-element))
20692 ;;; Indentation
20694 (defun org-indent-line ()
20695 "Indent line depending on context."
20696 (interactive)
20697 (let* ((pos (point))
20698 (itemp (org-at-item-p))
20699 (case-fold-search t)
20700 (org-drawer-regexp (or org-drawer-regexp "\000"))
20701 (inline-task-p (and (featurep 'org-inlinetask)
20702 (org-inlinetask-in-task-p)))
20703 (inline-re (and inline-task-p
20704 (org-inlinetask-outline-regexp)))
20705 column)
20706 (beginning-of-line 1)
20707 (cond
20708 ;; Headings
20709 ((looking-at org-outline-regexp) (setq column 0))
20710 ;; Included files
20711 ((looking-at "#\\+include:") (setq column 0))
20712 ;; Footnote definition
20713 ((looking-at org-footnote-definition-re) (setq column 0))
20714 ;; Literal examples
20715 ((looking-at "[ \t]*:\\( \\|$\\)")
20716 (setq column (org-get-indentation))) ; do nothing
20717 ;; Lists
20718 ((ignore-errors (goto-char (org-in-item-p)))
20719 (setq column (if itemp
20720 (org-get-indentation)
20721 (org-list-item-body-column (point))))
20722 (goto-char pos))
20723 ;; Drawers
20724 ((and (looking-at "[ \t]*:END:")
20725 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20726 (save-excursion
20727 (goto-char (1- (match-beginning 1)))
20728 (setq column (current-column))))
20729 ;; Special blocks
20730 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20731 (save-excursion
20732 (re-search-backward
20733 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20734 (setq column (org-get-indentation (match-string 0))))
20735 ((and (not (looking-at "[ \t]*#\\+begin_"))
20736 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20737 (save-excursion
20738 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20739 (setq column
20740 (cond ((equal (downcase (match-string 1)) "src")
20741 ;; src blocks: let `org-edit-src-exit' handle them
20742 (org-get-indentation))
20743 ((equal (downcase (match-string 1)) "example")
20744 (max (org-get-indentation)
20745 (org-get-indentation (match-string 0))))
20747 (org-get-indentation (match-string 0))))))
20748 ;; This line has nothing special, look at the previous relevant
20749 ;; line to compute indentation
20751 (beginning-of-line 0)
20752 (while (and (not (bobp))
20753 (not (looking-at org-drawer-regexp))
20754 ;; When point started in an inline task, do not move
20755 ;; above task starting line.
20756 (not (and inline-task-p (looking-at inline-re)))
20757 ;; Skip drawers, blocks, empty lines, verbatim,
20758 ;; comments, tables, footnotes definitions, lists,
20759 ;; inline tasks.
20760 (or (and (looking-at "[ \t]*:END:")
20761 (re-search-backward org-drawer-regexp nil t))
20762 (and (looking-at "[ \t]*#\\+end_")
20763 (re-search-backward "[ \t]*#\\+begin_"nil t))
20764 (looking-at "[ \t]*[\n:#|]")
20765 (looking-at org-footnote-definition-re)
20766 (and (ignore-errors (goto-char (org-in-item-p)))
20767 (goto-char
20768 (org-list-get-top-point (org-list-struct))))
20769 (and (not inline-task-p)
20770 (featurep 'org-inlinetask)
20771 (org-inlinetask-in-task-p)
20772 (or (org-inlinetask-goto-beginning) t))))
20773 (beginning-of-line 0))
20774 (cond
20775 ;; There was an heading above.
20776 ((looking-at "\\*+[ \t]+")
20777 (if (not org-adapt-indentation)
20778 (setq column 0)
20779 (goto-char (match-end 0))
20780 (setq column (current-column))))
20781 ;; A drawer had started and is unfinished
20782 ((looking-at org-drawer-regexp)
20783 (goto-char (1- (match-beginning 1)))
20784 (setq column (current-column)))
20785 ;; Else, nothing noticeable found: get indentation and go on.
20786 (t (setq column (org-get-indentation))))))
20787 ;; Now apply indentation and move cursor accordingly
20788 (goto-char pos)
20789 (if (<= (current-column) (current-indentation))
20790 (org-indent-line-to column)
20791 (save-excursion (org-indent-line-to column)))
20792 ;; Special polishing for properties, see `org-property-format'
20793 (setq column (current-column))
20794 (beginning-of-line 1)
20795 (if (looking-at
20796 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20797 (replace-match (concat (match-string 1)
20798 (format org-property-format
20799 (match-string 2) (match-string 3)))
20800 t t))
20801 (org-move-to-column column)
20802 (when (and orgstruct-is-++ (eq pos (point)))
20803 (org-let org-fb-vars
20804 '(indent-according-to-mode)))))
20806 (defun org-indent-drawer ()
20807 "Indent the drawer at point."
20808 (interactive)
20809 (let ((p (point))
20810 (e (and (save-excursion (re-search-forward ":END:" nil t))
20811 (match-end 0)))
20812 (folded
20813 (save-excursion
20814 (end-of-line)
20815 (when (overlays-at (point))
20816 (member 'invisible (overlay-properties
20817 (car (overlays-at (point)))))))))
20818 (when folded (org-cycle))
20819 (indent-for-tab-command)
20820 (while (and (move-beginning-of-line 2) (< (point) e))
20821 (indent-for-tab-command))
20822 (goto-char p)
20823 (when folded (org-cycle)))
20824 (message "Drawer at point indented"))
20826 (defun org-indent-block ()
20827 "Indent the block at point."
20828 (interactive)
20829 (let ((p (point))
20830 (case-fold-search t)
20831 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20832 (match-end 0)))
20833 (folded
20834 (save-excursion
20835 (end-of-line)
20836 (when (overlays-at (point))
20837 (member 'invisible (overlay-properties
20838 (car (overlays-at (point)))))))))
20839 (when folded (org-cycle))
20840 (indent-for-tab-command)
20841 (while (and (move-beginning-of-line 2) (< (point) e))
20842 (indent-for-tab-command))
20843 (goto-char p)
20844 (when folded (org-cycle)))
20845 (message "Block at point indented"))
20847 (defun org-indent-region (start end)
20848 "Indent region."
20849 (interactive "r")
20850 (save-excursion
20851 (let ((line-end (org-current-line end)))
20852 (goto-char start)
20853 (while (< (org-current-line) line-end)
20854 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20855 (t (call-interactively 'org-indent-line)))
20856 (move-beginning-of-line 2)))))
20859 ;;; Filling
20861 ;; We use our own fill-paragraph and auto-fill functions. These
20862 ;; functions will shadow `fill-prefix' (computed internally with
20863 ;; `org-fill-context-prefix') and pass through to
20864 ;; `fill-region-as-paragraph' and `do-auto-fill' as appropriate.
20866 (defun org-set-autofill-regexps ()
20867 (interactive)
20868 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20869 ;; Prevent auto-fill from inserting unwanted new items.
20870 (when (boundp 'fill-nobreak-predicate)
20871 (org-set-local
20872 'fill-nobreak-predicate
20873 (org-uniquify
20874 (append fill-nobreak-predicate
20875 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20876 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20877 (org-set-local 'align-mode-rules-list
20878 '((org-in-buffer-settings
20879 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20880 (modes . '(org-mode))))))
20882 (defun org-fill-item-nobreak-p ()
20883 "Non-nil when a line break at point would insert a new item."
20884 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20886 (defun org-fill-line-break-nobreak-p ()
20887 "Non-nil when a line break at point would create an Org line break."
20888 (save-excursion
20889 (skip-chars-backward "[ \t]")
20890 (skip-chars-backward "\\\\")
20891 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20893 (defvar org-element--affiliated-re) ; From org-element.el
20894 (defun org-fill-context-prefix (p)
20895 "Compute a fill prefix for the line at point P.
20896 Return fill prefix, as a string, or nil if current line isn't
20897 meant to be filled."
20898 (save-excursion
20899 (goto-char p)
20900 (beginning-of-line)
20901 (let* ((element (org-element-at-point))
20902 (type (org-element-type element))
20903 (post-affiliated
20904 (progn
20905 (goto-char (org-element-property :begin element))
20906 (while (looking-at org-element--affiliated-re) (forward-line))
20907 (point))))
20908 (unless (< p post-affiliated)
20909 (case type
20910 (comment (looking-at "[ \t]*# ?") (match-string 0))
20911 (footnote-definition "")
20912 ((item plain-list)
20913 (make-string (org-list-item-body-column
20914 (org-element-property :begin element))
20915 ? ))
20916 (paragraph
20917 ;; Fill prefix is usually the same as the current line,
20918 ;; except if the paragraph is at the beginning of an item.
20919 (let ((parent (org-element-property :parent element)))
20920 (cond ((eq (org-element-type parent) 'item)
20921 (make-string (org-list-item-body-column
20922 (org-element-property :begin parent))
20923 ? ))
20924 ((looking-at "\\s-+") (match-string 0))
20925 (t ""))))
20926 ((comment-block verse-block)
20927 ;; Only fill contents if P is within block boundaries.
20928 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20929 (forward-line)
20930 (point)))
20931 (cend (save-excursion
20932 (goto-char (org-element-property :end element))
20933 (skip-chars-backward " \r\t\n")
20934 (line-beginning-position))))
20935 (when (and (>= p cbeg) (< p cend))
20936 (if (looking-at "\\s-+") (match-string 0) "")))))))))
20938 (declare-function message-in-body-p "message" ())
20939 (defvar org-element-paragraph-separate) ; From org-element.el
20940 (defvar org-element-all-objects) ; From org-element.el
20941 (defun org-fill-paragraph (&optional justify)
20942 "Fill element at point, when applicable.
20944 This function only applies to comment blocks, comments, example
20945 blocks, paragraphs and verse blocks. Also, as a special case,
20946 re-align table when point is at one.
20948 If JUSTIFY is non-nil (interactively, with prefix argument),
20949 justify as well. If `sentence-end-double-space' is non-nil, then
20950 period followed by one space does not end a sentence, so don't
20951 break a line there. The variable `fill-column' controls the
20952 width for filling.
20954 For convenience, when point is at a plain list, an item or
20955 a footnote definition, try to fill the first paragraph within."
20956 ;; Falls back on message-fill-paragraph when necessary
20957 (if (and (derived-mode-p 'message-mode)
20958 (or (not (message-in-body-p))
20959 (save-excursion (move-beginning-of-line 1)
20960 (looking-at "> "))))
20961 (message-fill-paragraph)
20962 (save-excursion
20963 ;; Move to end of line in order to get the first paragraph within
20964 ;; a plain list or a footnote definition.
20965 (end-of-line)
20966 (let ((element (org-element-at-point)))
20967 ;; First check if point is in a blank line at the beginning of the
20968 ;; buffer. In that case, ignore filling.
20969 (if (< (point) (org-element-property :begin element)) t
20970 (case (org-element-type element)
20971 ;; Align Org tables, leave table.el tables as-is.
20972 (table-row (org-table-align) t)
20973 (table
20974 (when (eq (org-element-property :type element) 'org)
20975 (org-table-align))
20977 ;; Elements that may contain `line-break' type objects.
20978 ((paragraph verse-block)
20979 (let ((beg (org-element-property :contents-begin element))
20980 (end (org-element-property :contents-end element))
20981 (type (org-element-type element)))
20982 ;; Do nothing if point is at an affiliated keyword or at
20983 ;; verse block markers.
20984 (if (or (< (point) beg)
20985 (and (eq type 'verse-block) (>= (point) end)))
20987 ;; At a verse block, first narrow to current "paragraph"
20988 ;; and set current element to that paragraph.
20989 (save-restriction
20990 (when (eq type 'verse-block)
20991 (narrow-to-region beg end)
20992 (save-excursion
20993 (let ((bol-pos (point-at-bol)))
20994 (re-search-backward
20995 org-element-paragraph-separate nil 'm)
20996 (unless (or (bobp) (= (point-at-bol) bol-pos))
20997 (forward-line))
20998 (setq element (org-element-paragraph-parser end)
20999 beg (org-element-property :contents-begin element)
21000 end (org-element-property
21001 :contents-end element)))))
21002 ;; Fill paragraph, taking line breaks into consideration.
21003 ;; For that, slice the paragraph using line breaks as
21004 ;; separators, and fill the parts in reverse order to
21005 ;; avoid messing with markers.
21006 (save-excursion
21007 (goto-char end)
21008 (mapc
21009 (lambda (pos)
21010 (let ((fill-prefix (org-fill-context-prefix pos)))
21011 (fill-region-as-paragraph pos (point) justify))
21012 (goto-char pos))
21013 ;; Find the list of ending positions for line breaks
21014 ;; in the current paragraph. Add paragraph beginning
21015 ;; to include first slice.
21016 (nreverse
21017 (cons beg
21018 (org-element-map
21019 (org-element--parse-objects
21020 beg end nil org-element-all-objects)
21021 'line-break
21022 (lambda (lb) (org-element-property :end lb))))))))
21023 t)))
21024 ;; Contents of `comment-block' type elements should be filled as
21025 ;; plain text.
21026 (comment-block
21027 (let ((fill-prefix (org-fill-context-prefix (point))))
21028 (save-excursion
21029 (fill-region-as-paragraph
21030 (progn
21031 (goto-char (org-element-property :begin element))
21032 (while (looking-at org-element--affiliated-re) (forward-line))
21033 (forward-line)
21034 (point))
21035 (progn
21036 (goto-char (org-element-property :end element))
21037 (skip-chars-backward " \r\t\n")
21038 (line-beginning-position))
21039 justify))) t)
21040 ;; Fill comments, indented or not.
21041 (comment
21042 (let ((fill-prefix (org-fill-context-prefix (point))))
21043 (save-excursion
21044 (fill-region-as-paragraph
21045 (progn
21046 (goto-char (org-element-property :begin element))
21047 (while (looking-at org-element--affiliated-re) (forward-line))
21048 (point))
21049 (progn
21050 (goto-char (org-element-property :end element))
21051 (skip-chars-backward " \r\t\n")
21052 (line-end-position))))))
21053 ;; Ignore every other element.
21054 (otherwise t)))))))
21056 (defun org-auto-fill-function ()
21057 "Auto-fill function."
21058 ;; Check if auto-filling is meaningful before computing fill prefix.
21059 (let ((fc (current-fill-column)))
21060 (when (and fc (> (current-column) fc))
21061 (let ((fill-prefix (org-fill-context-prefix (point))))
21062 (when fill-prefix (do-auto-fill))))))
21065 ;;; Comments
21067 ;; Since difference between comments and keywords is subtle, we cannot
21068 ;; trust `comment-only-p' when applying `comment-dwim'. Hence, both
21069 ;; `comment-region-function' and `uncomment-region-function' point to
21070 ;; `org-comment-or-uncomment-region', which can tell when region only
21071 ;; contains comments or not.
21073 (defun org-insert-comment ()
21074 "Insert an empty comment above current line.
21075 If the line is empty, insert comment at its beginning."
21076 (beginning-of-line)
21077 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21078 (org-indent-line)
21079 (insert "# "))
21081 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21082 "Comment or uncomment each non-blank line in the region.
21083 Uncomment each non-blank line between BEG and END if it only
21084 contains commented lines. Otherwise, comment them."
21085 (save-excursion
21086 (goto-char beg)
21087 (skip-chars-forward " \r\t\n" end)
21088 (beginning-of-line)
21089 (let ((uncommentp
21090 ;; UNCOMMENTP is non-nil when every non blank line between
21091 ;; BEG and END is a comment.
21092 (save-excursion
21093 (while (progn (and (not (eobp))
21094 (let ((element (org-element-at-point)))
21095 (and (eq (org-element-type element) 'comment)
21096 (goto-char (org-element-property
21097 :end element)))))))
21098 (>= (point) end)))
21099 ;; Remove or adding comment markers is going to change end
21100 ;; position so make it a marker.
21101 (end (copy-marker end)))
21102 (while (< (point) end)
21103 (unless (looking-at "\\s-*$")
21104 (if (not uncommentp) (progn (back-to-indentation) (insert "# "))
21105 ;; Only comments and blank lines in region: uncomment it.
21106 (looking-at "[ \t]*\\(# ?\\)")
21107 (replace-match "" nil nil nil 1)))
21108 (forward-line))
21109 (set-marker end nil))))
21112 ;;; Other stuff.
21114 (defun org-toggle-fixed-width-section (arg)
21115 "Toggle the fixed-width export.
21116 If there is no active region, the QUOTE keyword at the current headline is
21117 inserted or removed. When present, it causes the text between this headline
21118 and the next to be exported as fixed-width text, and unmodified.
21119 If there is an active region, this command adds or removes a colon as the
21120 first character of this line. If the first character of a line is a colon,
21121 this line is also exported in fixed-width font."
21122 (interactive "P")
21123 (let* ((cc 0)
21124 (regionp (org-region-active-p))
21125 (beg (if regionp (region-beginning) (point)))
21126 (end (if regionp (region-end)))
21127 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21128 (case-fold-search nil)
21129 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21130 off)
21131 (if regionp
21132 (save-excursion
21133 (goto-char beg)
21134 (setq cc (current-column))
21135 (beginning-of-line 1)
21136 (setq off (looking-at re))
21137 (while (> nlines 0)
21138 (setq nlines (1- nlines))
21139 (beginning-of-line 1)
21140 (cond
21141 (arg
21142 (org-move-to-column cc t)
21143 (insert ": \n")
21144 (forward-line -1))
21145 ((and off (looking-at re))
21146 (replace-match "" t t nil 1))
21147 ((not off) (org-move-to-column cc t) (insert ": ")))
21148 (forward-line 1)))
21149 (save-excursion
21150 (org-back-to-heading)
21151 (cond
21152 ((looking-at (format org-heading-keyword-regexp-format
21153 org-quote-string))
21154 (goto-char (match-end 1))
21155 (looking-at (concat " +" org-quote-string))
21156 (replace-match "" t t)
21157 (when (eolp) (insert " ")))
21158 ((looking-at org-outline-regexp)
21159 (goto-char (match-end 0))
21160 (insert org-quote-string " ")))))))
21162 (defun org-reftex-citation ()
21163 "Use reftex-citation to insert a citation into the buffer.
21164 This looks for a line like
21166 #+BIBLIOGRAPHY: foo plain option:-d
21168 and derives from it that foo.bib is the bibliography file relevant
21169 for this document. It then installs the necessary environment for RefTeX
21170 to work in this buffer and calls `reftex-citation' to insert a citation
21171 into the buffer.
21173 Export of such citations to both LaTeX and HTML is handled by the contributed
21174 package org-exp-bibtex by Taru Karttunen."
21175 (interactive)
21176 (let ((reftex-docstruct-symbol 'rds)
21177 (reftex-cite-format "\\cite{%l}")
21178 rds bib)
21179 (save-excursion
21180 (save-restriction
21181 (widen)
21182 (let ((case-fold-search t)
21183 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21184 (if (not (save-excursion
21185 (or (re-search-forward re nil t)
21186 (re-search-backward re nil t))))
21187 (error "No bibliography defined in file")
21188 (setq bib (concat (match-string 1) ".bib")
21189 rds (list (list 'bib bib)))))))
21190 (call-interactively 'reftex-citation)))
21192 ;;;; Functions extending outline functionality
21194 (defun org-beginning-of-line (&optional arg)
21195 "Go to the beginning of the current line. If that is invisible, continue
21196 to a visible line beginning. This makes the function of C-a more intuitive.
21197 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21198 first attempt, and only move to after the tags when the cursor is already
21199 beyond the end of the headline."
21200 (interactive "P")
21201 (let ((pos (point))
21202 (special (if (consp org-special-ctrl-a/e)
21203 (car org-special-ctrl-a/e)
21204 org-special-ctrl-a/e))
21205 refpos)
21206 (if (org-bound-and-true-p line-move-visual)
21207 (beginning-of-visual-line 1)
21208 (beginning-of-line 1))
21209 (if (and arg (fboundp 'move-beginning-of-line))
21210 (call-interactively 'move-beginning-of-line)
21211 (if (bobp)
21213 (backward-char 1)
21214 (if (org-truely-invisible-p)
21215 (while (and (not (bobp)) (org-truely-invisible-p))
21216 (backward-char 1)
21217 (beginning-of-line 1))
21218 (forward-char 1))))
21219 (when special
21220 (cond
21221 ((and (looking-at org-complex-heading-regexp)
21222 (= (char-after (match-end 1)) ?\ ))
21223 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21224 (point-at-eol)))
21225 (goto-char
21226 (if (eq special t)
21227 (cond ((> pos refpos) refpos)
21228 ((= pos (point)) refpos)
21229 (t (point)))
21230 (cond ((> pos (point)) (point))
21231 ((not (eq last-command this-command)) (point))
21232 (t refpos)))))
21233 ((org-at-item-p)
21234 ;; Being at an item and not looking at an the item means point
21235 ;; was previously moved to beginning of a visual line, which
21236 ;; doesn't contain the item. Therefore, do nothing special,
21237 ;; just stay here.
21238 (when (looking-at org-list-full-item-re)
21239 ;; Set special position at first white space character after
21240 ;; bullet, and check-box, if any.
21241 (let ((after-bullet
21242 (let ((box (match-end 3)))
21243 (if (not box) (match-end 1)
21244 (let ((after (char-after box)))
21245 (if (and after (= after ? )) (1+ box) box))))))
21246 ;; Special case: Move point to special position when
21247 ;; currently after it or at beginning of line.
21248 (if (eq special t)
21249 (when (or (> pos after-bullet) (= (point) pos))
21250 (goto-char after-bullet))
21251 ;; Reversed case: Move point to special position when
21252 ;; point was already at beginning of line and command is
21253 ;; repeated.
21254 (when (and (= (point) pos) (eq last-command this-command))
21255 (goto-char after-bullet))))))))
21256 (org-no-warnings
21257 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21259 (defun org-end-of-line (&optional arg)
21260 "Go to the end of the line.
21261 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21262 first attempt, and only move to after the tags when the cursor is already
21263 beyond the end of the headline."
21264 (interactive "P")
21265 (let ((special (if (consp org-special-ctrl-a/e)
21266 (cdr org-special-ctrl-a/e)
21267 org-special-ctrl-a/e)))
21268 (cond
21269 ((or (not special) arg
21270 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21271 (call-interactively
21272 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21273 ((fboundp 'move-end-of-line) 'move-end-of-line)
21274 (t 'end-of-line))))
21275 ((org-at-heading-p)
21276 (let ((pos (point)))
21277 (beginning-of-line 1)
21278 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21279 (if (eq special t)
21280 (if (or (< pos (match-beginning 1))
21281 (= pos (match-end 0)))
21282 (goto-char (match-beginning 1))
21283 (goto-char (match-end 0)))
21284 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21285 (goto-char (match-end 0))
21286 (goto-char (match-beginning 1))))
21287 (call-interactively (if (fboundp 'move-end-of-line)
21288 'move-end-of-line
21289 'end-of-line)))))
21290 ((org-at-drawer-p)
21291 (move-end-of-line 1)
21292 (when (overlays-at (1- (point))) (backward-char 1)))
21293 ;; At an item: Move before any hidden text.
21294 (t (call-interactively
21295 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21296 ((fboundp 'move-end-of-line) 'move-end-of-line)
21297 (t 'end-of-line)))))
21298 (org-no-warnings
21299 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21301 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21302 (define-key org-mode-map "\C-e" 'org-end-of-line)
21304 (defun org-backward-sentence (&optional arg)
21305 "Go to beginning of sentence, or beginning of table field.
21306 This will call `backward-sentence' or `org-table-beginning-of-field',
21307 depending on context."
21308 (interactive "P")
21309 (cond
21310 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21311 (t (call-interactively 'backward-sentence))))
21313 (defun org-forward-sentence (&optional arg)
21314 "Go to end of sentence, or end of table field.
21315 This will call `forward-sentence' or `org-table-end-of-field',
21316 depending on context."
21317 (interactive "P")
21318 (cond
21319 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21320 (t (call-interactively 'forward-sentence))))
21322 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21323 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21325 (defun org-kill-line (&optional arg)
21326 "Kill line, to tags or end of line."
21327 (interactive "P")
21328 (cond
21329 ((or (not org-special-ctrl-k)
21330 (bolp)
21331 (not (org-at-heading-p)))
21332 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21333 org-ctrl-k-protect-subtree)
21334 (if (or (eq org-ctrl-k-protect-subtree 'error)
21335 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21336 (error "C-k aborted - would kill hidden subtree")))
21337 (call-interactively
21338 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21339 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21340 (kill-region (point) (match-beginning 1))
21341 (org-set-tags nil t))
21342 (t (kill-region (point) (point-at-eol)))))
21344 (define-key org-mode-map "\C-k" 'org-kill-line)
21346 (defun org-yank (&optional arg)
21347 "Yank. If the kill is a subtree, treat it specially.
21348 This command will look at the current kill and check if is a single
21349 subtree, or a series of subtrees[1]. If it passes the test, and if the
21350 cursor is at the beginning of a line or after the stars of a currently
21351 empty headline, then the yank is handled specially. How exactly depends
21352 on the value of the following variables, both set by default.
21354 org-yank-folded-subtrees
21355 When set, the subtree(s) will be folded after insertion, but only
21356 if doing so would now swallow text after the yanked text.
21358 org-yank-adjusted-subtrees
21359 When set, the subtree will be promoted or demoted in order to
21360 fit into the local outline tree structure, which means that the level
21361 will be adjusted so that it becomes the smaller one of the two
21362 *visible* surrounding headings.
21364 Any prefix to this command will cause `yank' to be called directly with
21365 no special treatment. In particular, a simple \\[universal-argument] prefix \
21366 will just
21367 plainly yank the text as it is.
21369 \[1] The test checks if the first non-white line is a heading
21370 and if there are no other headings with fewer stars."
21371 (interactive "P")
21372 (org-yank-generic 'yank arg))
21374 (defun org-yank-generic (command arg)
21375 "Perform some yank-like command.
21377 This function implements the behavior described in the `org-yank'
21378 documentation. However, it has been generalized to work for any
21379 interactive command with similar behavior."
21381 ;; pretend to be command COMMAND
21382 (setq this-command command)
21384 (if arg
21385 (call-interactively command)
21387 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21388 (and (org-kill-is-subtree-p)
21389 (or (bolp)
21390 (and (looking-at "[ \t]*$")
21391 (string-match
21392 "\\`\\*+\\'"
21393 (buffer-substring (point-at-bol) (point)))))))
21394 swallowp)
21395 (cond
21396 ((and subtreep org-yank-folded-subtrees)
21397 (let ((beg (point))
21398 end)
21399 (if (and subtreep org-yank-adjusted-subtrees)
21400 (org-paste-subtree nil nil 'for-yank)
21401 (call-interactively command))
21403 (setq end (point))
21404 (goto-char beg)
21405 (when (and (bolp) subtreep
21406 (not (setq swallowp
21407 (org-yank-folding-would-swallow-text beg end))))
21408 (org-with-limited-levels
21409 (or (looking-at org-outline-regexp)
21410 (re-search-forward org-outline-regexp-bol end t))
21411 (while (and (< (point) end) (looking-at org-outline-regexp))
21412 (hide-subtree)
21413 (org-cycle-show-empty-lines 'folded)
21414 (condition-case nil
21415 (outline-forward-same-level 1)
21416 (error (goto-char end))))))
21417 (when swallowp
21418 (message
21419 "Inserted text not folded because that would swallow text"))
21421 (goto-char end)
21422 (skip-chars-forward " \t\n\r")
21423 (beginning-of-line 1)
21424 (push-mark beg 'nomsg)))
21425 ((and subtreep org-yank-adjusted-subtrees)
21426 (let ((beg (point-at-bol)))
21427 (org-paste-subtree nil nil 'for-yank)
21428 (push-mark beg 'nomsg)))
21430 (call-interactively command))))))
21432 (defun org-yank-folding-would-swallow-text (beg end)
21433 "Would hide-subtree at BEG swallow any text after END?"
21434 (let (level)
21435 (org-with-limited-levels
21436 (save-excursion
21437 (goto-char beg)
21438 (when (or (looking-at org-outline-regexp)
21439 (re-search-forward org-outline-regexp-bol end t))
21440 (setq level (org-outline-level)))
21441 (goto-char end)
21442 (skip-chars-forward " \t\r\n\v\f")
21443 (if (or (eobp)
21444 (and (bolp) (looking-at org-outline-regexp)
21445 (<= (org-outline-level) level)))
21446 nil ; Nothing would be swallowed
21447 t))))) ; something would swallow
21449 (define-key org-mode-map "\C-y" 'org-yank)
21451 (defun org-truely-invisible-p ()
21452 "Check if point is at a character currently not visible.
21453 This version does not only check the character property, but also
21454 `visible-mode'."
21455 ;; Early versions of noutline don't have `outline-invisible-p'.
21456 (if (org-bound-and-true-p visible-mode)
21458 (outline-invisible-p)))
21460 (defun org-invisible-p2 ()
21461 "Check if point is at a character currently not visible."
21462 (save-excursion
21463 (if (and (eolp) (not (bobp))) (backward-char 1))
21464 ;; Early versions of noutline don't have `outline-invisible-p'.
21465 (outline-invisible-p)))
21467 (defun org-back-to-heading (&optional invisible-ok)
21468 "Call `outline-back-to-heading', but provide a better error message."
21469 (condition-case nil
21470 (outline-back-to-heading invisible-ok)
21471 (error (error "Before first headline at position %d in buffer %s"
21472 (point) (current-buffer)))))
21474 (defun org-beginning-of-defun ()
21475 "Go to the beginning of the subtree, i.e. back to the heading."
21476 (org-back-to-heading))
21477 (defun org-end-of-defun ()
21478 "Go to the end of the subtree."
21479 (org-end-of-subtree nil t))
21481 (defun org-before-first-heading-p ()
21482 "Before first heading?"
21483 (save-excursion
21484 (end-of-line)
21485 (null (re-search-backward org-outline-regexp-bol nil t))))
21487 (defun org-at-heading-p (&optional ignored)
21488 (outline-on-heading-p t))
21489 ;; Compatibility alias with Org versions < 7.8.03
21490 (defalias 'org-on-heading-p 'org-at-heading-p)
21492 (defun org-at-comment-p nil
21493 "Is cursor in a line starting with a # character?"
21494 (save-excursion
21495 (beginning-of-line)
21496 (looking-at "^#")))
21498 (defun org-at-drawer-p nil
21499 "Is cursor at a drawer keyword?"
21500 (save-excursion
21501 (move-beginning-of-line 1)
21502 (looking-at org-drawer-regexp)))
21504 (defun org-at-block-p nil
21505 "Is cursor at a block keyword?"
21506 (save-excursion
21507 (move-beginning-of-line 1)
21508 (looking-at org-block-regexp)))
21510 (defun org-point-at-end-of-empty-headline ()
21511 "If point is at the end of an empty headline, return t, else nil.
21512 If the heading only contains a TODO keyword, it is still still considered
21513 empty."
21514 (and (looking-at "[ \t]*$")
21515 (when org-todo-line-regexp
21516 (save-excursion
21517 (beginning-of-line 1)
21518 (let ((case-fold-search nil))
21519 (looking-at org-todo-line-regexp)
21520 (string= (match-string 3) ""))))))
21522 (defun org-at-heading-or-item-p ()
21523 (or (org-at-heading-p) (org-at-item-p)))
21525 (defun org-at-target-p ()
21526 (or (org-in-regexp org-radio-target-regexp)
21527 (org-in-regexp org-target-regexp)))
21528 ;; Compatibility alias with Org versions < 7.8.03
21529 (defalias 'org-on-target-p 'org-at-target-p)
21531 (defun org-up-heading-all (arg)
21532 "Move to the heading line of which the present line is a subheading.
21533 This function considers both visible and invisible heading lines.
21534 With argument, move up ARG levels."
21535 (if (fboundp 'outline-up-heading-all)
21536 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21537 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21539 (defun org-up-heading-safe ()
21540 "Move to the heading line of which the present line is a subheading.
21541 This version will not throw an error. It will return the level of the
21542 headline found, or nil if no higher level is found.
21544 Also, this function will be a lot faster than `outline-up-heading',
21545 because it relies on stars being the outline starters. This can really
21546 make a significant difference in outlines with very many siblings."
21547 (let (start-level re)
21548 (org-back-to-heading t)
21549 (setq start-level (funcall outline-level))
21550 (if (equal start-level 1)
21552 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21553 (if (re-search-backward re nil t)
21554 (funcall outline-level)))))
21556 (defun org-first-sibling-p ()
21557 "Is this heading the first child of its parents?"
21558 (interactive)
21559 (let ((re org-outline-regexp-bol)
21560 level l)
21561 (unless (org-at-heading-p t)
21562 (error "Not at a heading"))
21563 (setq level (funcall outline-level))
21564 (save-excursion
21565 (if (not (re-search-backward re nil t))
21567 (setq l (funcall outline-level))
21568 (< l level)))))
21570 (defun org-goto-sibling (&optional previous)
21571 "Goto the next sibling, even if it is invisible.
21572 When PREVIOUS is set, go to the previous sibling instead. Returns t
21573 when a sibling was found. When none is found, return nil and don't
21574 move point."
21575 (let ((fun (if previous 're-search-backward 're-search-forward))
21576 (pos (point))
21577 (re org-outline-regexp-bol)
21578 level l)
21579 (when (condition-case nil (org-back-to-heading t) (error nil))
21580 (setq level (funcall outline-level))
21581 (catch 'exit
21582 (or previous (forward-char 1))
21583 (while (funcall fun re nil t)
21584 (setq l (funcall outline-level))
21585 (when (< l level) (goto-char pos) (throw 'exit nil))
21586 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21587 (goto-char pos)
21588 nil))))
21590 (defun org-show-siblings ()
21591 "Show all siblings of the current headline."
21592 (save-excursion
21593 (while (org-goto-sibling) (org-flag-heading nil)))
21594 (save-excursion
21595 (while (org-goto-sibling 'previous)
21596 (org-flag-heading nil))))
21598 (defun org-goto-first-child ()
21599 "Goto the first child, even if it is invisible.
21600 Return t when a child was found. Otherwise don't move point and
21601 return nil."
21602 (let (level (pos (point)) (re org-outline-regexp-bol))
21603 (when (condition-case nil (org-back-to-heading t) (error nil))
21604 (setq level (outline-level))
21605 (forward-char 1)
21606 (if (and (re-search-forward re nil t) (> (outline-level) level))
21607 (progn (goto-char (match-beginning 0)) t)
21608 (goto-char pos) nil))))
21610 (defun org-show-hidden-entry ()
21611 "Show an entry where even the heading is hidden."
21612 (save-excursion
21613 (org-show-entry)))
21615 (defun org-flag-heading (flag &optional entry)
21616 "Flag the current heading. FLAG non-nil means make invisible.
21617 When ENTRY is non-nil, show the entire entry."
21618 (save-excursion
21619 (org-back-to-heading t)
21620 ;; Check if we should show the entire entry
21621 (if entry
21622 (progn
21623 (org-show-entry)
21624 (save-excursion
21625 (and (outline-next-heading)
21626 (org-flag-heading nil))))
21627 (outline-flag-region (max (point-min) (1- (point)))
21628 (save-excursion (outline-end-of-heading) (point))
21629 flag))))
21631 (defun org-get-next-sibling ()
21632 "Move to next heading of the same level, and return point.
21633 If there is no such heading, return nil.
21634 This is like outline-next-sibling, but invisible headings are ok."
21635 (let ((level (funcall outline-level)))
21636 (outline-next-heading)
21637 (while (and (not (eobp)) (> (funcall outline-level) level))
21638 (outline-next-heading))
21639 (if (or (eobp) (< (funcall outline-level) level))
21641 (point))))
21643 (defun org-get-last-sibling ()
21644 "Move to previous heading of the same level, and return point.
21645 If there is no such heading, return nil."
21646 (let ((opoint (point))
21647 (level (funcall outline-level)))
21648 (outline-previous-heading)
21649 (when (and (/= (point) opoint) (outline-on-heading-p t))
21650 (while (and (> (funcall outline-level) level)
21651 (not (bobp)))
21652 (outline-previous-heading))
21653 (if (< (funcall outline-level) level)
21655 (point)))))
21657 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21658 ;; This contains an exact copy of the original function, but it uses
21659 ;; `org-back-to-heading', to make it work also in invisible
21660 ;; trees. And is uses an invisible-OK argument.
21661 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21662 ;; Furthermore, when used inside Org, finding the end of a large subtree
21663 ;; with many children and grandchildren etc, this can be much faster
21664 ;; than the outline version.
21665 (org-back-to-heading invisible-OK)
21666 (let ((first t)
21667 (level (funcall outline-level)))
21668 (if (and (derived-mode-p 'org-mode) (< level 1000))
21669 ;; A true heading (not a plain list item), in Org-mode
21670 ;; This means we can easily find the end by looking
21671 ;; only for the right number of stars. Using a regexp to do
21672 ;; this is so much faster than using a Lisp loop.
21673 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21674 (forward-char 1)
21675 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21676 ;; something else, do it the slow way
21677 (while (and (not (eobp))
21678 (or first (> (funcall outline-level) level)))
21679 (setq first nil)
21680 (outline-next-heading)))
21681 (unless to-heading
21682 (if (memq (preceding-char) '(?\n ?\^M))
21683 (progn
21684 ;; Go to end of line before heading
21685 (forward-char -1)
21686 (if (memq (preceding-char) '(?\n ?\^M))
21687 ;; leave blank line before heading
21688 (forward-char -1))))))
21689 (point))
21691 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21692 "Use Org version in org-mode, for dramatic speed-up."
21693 (if (derived-mode-p 'org-mode)
21694 (progn
21695 (org-end-of-subtree nil t)
21696 (unless (eobp) (backward-char 1)))
21697 ad-do-it))
21699 (defun org-end-of-meta-data-and-drawers ()
21700 "Jump to the first text after meta data and drawers in the current entry.
21701 This will move over empty lines, lines with planning time stamps,
21702 clocking lines, and drawers."
21703 (org-back-to-heading t)
21704 (let ((end (save-excursion (outline-next-heading) (point)))
21705 (re (concat "\\(" org-drawer-regexp "\\)"
21706 "\\|" "[ \t]*" org-keyword-time-regexp)))
21707 (forward-line 1)
21708 (while (re-search-forward re end t)
21709 (if (not (match-end 1))
21710 ;; empty or planning line
21711 (forward-line 1)
21712 ;; a drawer, find the end
21713 (re-search-forward "^[ \t]*:END:" end 'move)
21714 (forward-line 1)))
21715 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21716 (point)))
21718 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21719 "Move forward to the arg'th subheading at same level as this one.
21720 Stop at the first and last subheadings of a superior heading.
21721 Normally this only looks at visible headings, but when INVISIBLE-OK is
21722 non-nil it will also look at invisible ones."
21723 (interactive "p")
21724 (org-back-to-heading invisible-ok)
21725 (org-at-heading-p)
21726 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21727 (re (format "^\\*\\{1,%d\\} " level))
21729 (forward-char 1)
21730 (while (> arg 0)
21731 (while (and (re-search-forward re nil 'move)
21732 (setq l (- (match-end 0) (match-beginning 0) 1))
21733 (= l level)
21734 (not invisible-ok)
21735 (progn (backward-char 1) (outline-invisible-p)))
21736 (if (< l level) (setq arg 1)))
21737 (setq arg (1- arg)))
21738 (beginning-of-line 1)))
21740 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21741 "Move backward to the arg'th subheading at same level as this one.
21742 Stop at the first and last subheadings of a superior heading."
21743 (interactive "p")
21744 (org-back-to-heading)
21745 (org-at-heading-p)
21746 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21747 (re (format "^\\*\\{1,%d\\} " level))
21749 (while (> arg 0)
21750 (while (and (re-search-backward re nil 'move)
21751 (setq l (- (match-end 0) (match-beginning 0) 1))
21752 (= l level)
21753 (not invisible-ok)
21754 (outline-invisible-p))
21755 (if (< l level) (setq arg 1)))
21756 (setq arg (1- arg)))))
21758 ;;;###autoload
21759 (defun org-forward-element ()
21760 "Move forward by one element.
21761 Move to the next element at the same level, when possible."
21762 (interactive)
21763 (cond ((eobp) (error "Cannot move further down"))
21764 ((org-with-limited-levels (org-at-heading-p))
21765 (let ((origin (point)))
21766 (org-forward-heading-same-level 1)
21767 (unless (org-with-limited-levels (org-at-heading-p))
21768 (goto-char origin)
21769 (error "Cannot move further down"))))
21771 (let* ((elem (org-element-at-point))
21772 (end (org-element-property :end elem))
21773 (parent (org-element-property :parent elem)))
21774 (if (and parent (= (org-element-property :contents-end parent) end))
21775 (goto-char (org-element-property :end parent))
21776 (goto-char end))))))
21778 ;;;###autoload
21779 (defun org-backward-element ()
21780 "Move backward by one element.
21781 Move to the previous element at the same level, when possible."
21782 (interactive)
21783 (if (org-with-limited-levels (org-at-heading-p))
21784 ;; At an headline, move to the previous one, if any, or stay
21785 ;; here.
21786 (let ((origin (point)))
21787 (org-backward-heading-same-level 1)
21788 (unless (org-with-limited-levels (org-at-heading-p))
21789 (goto-char origin)
21790 (error "Cannot move further up")))
21791 (let* ((trail (org-element-at-point 'keep-trail))
21792 (elem (car trail))
21793 (prev-elem (nth 1 trail))
21794 (beg (org-element-property :begin elem)))
21795 (cond
21796 ;; Move to beginning of current element if point isn't there
21797 ;; already.
21798 ((/= (point) beg) (goto-char beg))
21799 ((not prev-elem) (error "Cannot move further up"))
21800 (t (goto-char (org-element-property :begin prev-elem)))))))
21802 ;;;###autoload
21803 (defun org-up-element ()
21804 "Move to upper element."
21805 (interactive)
21806 (if (org-with-limited-levels (org-at-heading-p))
21807 (unless (org-up-heading-safe) (error "No surrounding element"))
21808 (let* ((elem (org-element-at-point))
21809 (parent (org-element-property :parent elem)))
21810 (if parent (goto-char (org-element-property :begin parent))
21811 (if (org-with-limited-levels (org-before-first-heading-p))
21812 (error "No surrounding element")
21813 (org-with-limited-levels (org-back-to-heading)))))))
21815 ;;;###autoload
21816 (defvar org-element-greater-elements)
21817 (defun org-down-element ()
21818 "Move to inner element."
21819 (interactive)
21820 (let ((element (org-element-at-point)))
21821 (cond
21822 ((memq (org-element-type element) '(plain-list table))
21823 (goto-char (org-element-property :contents-begin element))
21824 (forward-char))
21825 ((memq (org-element-type element) org-element-greater-elements)
21826 ;; If contents are hidden, first disclose them.
21827 (when (org-element-property :hiddenp element) (org-cycle))
21828 (goto-char (or (org-element-property :contents-begin element)
21829 (error "No content for this element"))))
21830 (t (error "No inner element")))))
21832 ;;;###autoload
21833 (defun org-drag-element-backward ()
21834 "Move backward element at point."
21835 (interactive)
21836 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21837 (let* ((trail (org-element-at-point 'keep-trail))
21838 (elem (car trail))
21839 (prev-elem (nth 1 trail)))
21840 ;; Error out if no previous element or previous element is
21841 ;; a parent of the current one.
21842 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21843 (error "Cannot drag element backward")
21844 (let ((pos (point)))
21845 (org-element-swap-A-B prev-elem elem)
21846 (goto-char (+ (org-element-property :begin prev-elem)
21847 (- pos (org-element-property :begin elem)))))))))
21849 ;;;###autoload
21850 (defun org-drag-element-forward ()
21851 "Move forward element at point."
21852 (interactive)
21853 (let* ((pos (point))
21854 (elem (org-element-at-point)))
21855 (when (= (point-max) (org-element-property :end elem))
21856 (error "Cannot drag element forward"))
21857 (goto-char (org-element-property :end elem))
21858 (let ((next-elem (org-element-at-point)))
21859 (when (or (org-element-nested-p elem next-elem)
21860 (and (eq (org-element-type next-elem) 'headline)
21861 (not (eq (org-element-type elem) 'headline))))
21862 (goto-char pos)
21863 (error "Cannot drag element forward"))
21864 ;; Compute new position of point: it's shifted by NEXT-ELEM
21865 ;; body's length (without final blanks) and by the length of
21866 ;; blanks between ELEM and NEXT-ELEM.
21867 (let ((size-next (- (save-excursion
21868 (goto-char (org-element-property :end next-elem))
21869 (skip-chars-backward " \r\t\n")
21870 (forward-line)
21871 ;; Small correction if buffer doesn't end
21872 ;; with a newline character.
21873 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21874 (org-element-property :begin next-elem)))
21875 (size-blank (- (org-element-property :end elem)
21876 (save-excursion
21877 (goto-char (org-element-property :end elem))
21878 (skip-chars-backward " \r\t\n")
21879 (forward-line)
21880 (point)))))
21881 (org-element-swap-A-B elem next-elem)
21882 (goto-char (+ pos size-next size-blank))))))
21884 ;;;###autoload
21885 (defun org-mark-element ()
21886 "Put point at beginning of this element, mark at end.
21888 Interactively, if this command is repeated or (in Transient Mark
21889 mode) if the mark is active, it marks the next element after the
21890 ones already marked."
21891 (interactive)
21892 (let (deactivate-mark)
21893 (if (or (and (eq last-command this-command) (mark t))
21894 (and transient-mark-mode mark-active))
21895 (set-mark
21896 (save-excursion
21897 (goto-char (mark))
21898 (goto-char (org-element-property :end (org-element-at-point)))))
21899 (let ((element (org-element-at-point)))
21900 (end-of-line)
21901 (push-mark (org-element-property :end element) t t)
21902 (goto-char (org-element-property :begin element))))))
21904 ;;;###autoload
21905 (defun org-narrow-to-element ()
21906 "Narrow buffer to current element."
21907 (interactive)
21908 (let ((elem (org-element-at-point)))
21909 (cond
21910 ((eq (car elem) 'headline)
21911 (narrow-to-region
21912 (org-element-property :begin elem)
21913 (org-element-property :end elem)))
21914 ((memq (car elem) org-element-greater-elements)
21915 (narrow-to-region
21916 (org-element-property :contents-begin elem)
21917 (org-element-property :contents-end elem)))
21919 (narrow-to-region
21920 (org-element-property :begin elem)
21921 (org-element-property :end elem))))))
21923 ;;;###autoload
21924 (defun org-transpose-element ()
21925 "Transpose current and previous elements, keeping blank lines between.
21926 Point is moved after both elements."
21927 (interactive)
21928 (org-skip-whitespace)
21929 (let ((end (org-element-property :end (org-element-at-point))))
21930 (org-drag-element-backward)
21931 (goto-char end)))
21933 ;;;###autoload
21934 (defun org-unindent-buffer ()
21935 "Un-indent the visible part of the buffer.
21936 Relative indentation (between items, inside blocks, etc.) isn't
21937 modified."
21938 (interactive)
21939 (unless (eq major-mode 'org-mode)
21940 (error "Cannot un-indent a buffer not in Org mode"))
21941 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
21942 unindent-tree ; For byte-compiler.
21943 (unindent-tree
21944 (function
21945 (lambda (contents)
21946 (mapc
21947 (lambda (element)
21948 (if (memq (org-element-type element) '(headline section))
21949 (funcall unindent-tree (org-element-contents element))
21950 (save-excursion
21951 (save-restriction
21952 (narrow-to-region
21953 (org-element-property :begin element)
21954 (org-element-property :end element))
21955 (org-do-remove-indentation)))))
21956 (reverse contents))))))
21957 (funcall unindent-tree (org-element-contents parse-tree))))
21959 (defun org-show-subtree ()
21960 "Show everything after this heading at deeper levels."
21961 (interactive)
21962 (outline-flag-region
21963 (point)
21964 (save-excursion
21965 (org-end-of-subtree t t))
21966 nil))
21968 (defun org-show-entry ()
21969 "Show the body directly following this heading.
21970 Show the heading too, if it is currently invisible."
21971 (interactive)
21972 (save-excursion
21973 (condition-case nil
21974 (progn
21975 (org-back-to-heading t)
21976 (outline-flag-region
21977 (max (point-min) (1- (point)))
21978 (save-excursion
21979 (if (re-search-forward
21980 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21981 (match-beginning 1)
21982 (point-max)))
21983 nil)
21984 (org-cycle-hide-drawers 'children))
21985 (error nil))))
21987 (defun org-make-options-regexp (kwds &optional extra)
21988 "Make a regular expression for keyword lines."
21989 (concat
21991 "#?[ \t]*\\+\\("
21992 (mapconcat 'regexp-quote kwds "\\|")
21993 (if extra (concat "\\|" extra))
21994 "\\):[ \t]*"
21995 "\\(.*\\)"))
21997 ;; Make isearch reveal the necessary context
21998 (defun org-isearch-end ()
21999 "Reveal context after isearch exits."
22000 (when isearch-success ; only if search was successful
22001 (if (featurep 'xemacs)
22002 ;; Under XEmacs, the hook is run in the correct place,
22003 ;; we directly show the context.
22004 (org-show-context 'isearch)
22005 ;; In Emacs the hook runs *before* restoring the overlays.
22006 ;; So we have to use a one-time post-command-hook to do this.
22007 ;; (Emacs 22 has a special variable, see function `org-mode')
22008 (unless (and (boundp 'isearch-mode-end-hook-quit)
22009 isearch-mode-end-hook-quit)
22010 ;; Only when the isearch was not quitted.
22011 (org-add-hook 'post-command-hook 'org-isearch-post-command
22012 'append 'local)))))
22014 (defun org-isearch-post-command ()
22015 "Remove self from hook, and show context."
22016 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22017 (org-show-context 'isearch))
22020 ;;;; Integration with and fixes for other packages
22022 ;;; Imenu support
22024 (defvar org-imenu-markers nil
22025 "All markers currently used by Imenu.")
22026 (make-variable-buffer-local 'org-imenu-markers)
22028 (defun org-imenu-new-marker (&optional pos)
22029 "Return a new marker for use by Imenu, and remember the marker."
22030 (let ((m (make-marker)))
22031 (move-marker m (or pos (point)))
22032 (push m org-imenu-markers)
22035 (defun org-imenu-get-tree ()
22036 "Produce the index for Imenu."
22037 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22038 (setq org-imenu-markers nil)
22039 (let* ((n org-imenu-depth)
22040 (re (concat "^" (org-get-limited-outline-regexp)))
22041 (subs (make-vector (1+ n) nil))
22042 (last-level 0)
22043 m level head)
22044 (save-excursion
22045 (save-restriction
22046 (widen)
22047 (goto-char (point-max))
22048 (while (re-search-backward re nil t)
22049 (setq level (org-reduced-level (funcall outline-level)))
22050 (when (and (<= level n)
22051 (looking-at org-complex-heading-regexp))
22052 (setq head (org-link-display-format
22053 (org-match-string-no-properties 4))
22054 m (org-imenu-new-marker))
22055 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22056 (if (>= level last-level)
22057 (push (cons head m) (aref subs level))
22058 (push (cons head (aref subs (1+ level))) (aref subs level))
22059 (loop for i from (1+ level) to n do (aset subs i nil)))
22060 (setq last-level level)))))
22061 (aref subs 1)))
22063 (eval-after-load "imenu"
22064 '(progn
22065 (add-hook 'imenu-after-jump-hook
22066 (lambda ()
22067 (if (derived-mode-p 'org-mode)
22068 (org-show-context 'org-goto))))))
22070 (defun org-link-display-format (link)
22071 "Replace a link with either the description, or the link target
22072 if no description is present"
22073 (save-match-data
22074 (if (string-match org-bracket-link-analytic-regexp link)
22075 (replace-match (if (match-end 5)
22076 (match-string 5 link)
22077 (concat (match-string 1 link)
22078 (match-string 3 link)))
22079 nil t link)
22080 link)))
22082 (defun org-toggle-link-display ()
22083 "Toggle the literal or descriptive display of links."
22084 (interactive)
22085 (if org-descriptive-links
22086 (progn (org-remove-from-invisibility-spec '(org-link))
22087 (org-restart-font-lock)
22088 (setq org-descriptive-links nil))
22089 (progn (add-to-invisibility-spec '(org-link))
22090 (org-restart-font-lock)
22091 (setq org-descriptive-links t))))
22093 ;; Speedbar support
22095 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22096 "Overlay marking the agenda restriction line in speedbar.")
22097 (overlay-put org-speedbar-restriction-lock-overlay
22098 'face 'org-agenda-restriction-lock)
22099 (overlay-put org-speedbar-restriction-lock-overlay
22100 'help-echo "Agendas are currently limited to this item.")
22101 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22103 (defun org-speedbar-set-agenda-restriction ()
22104 "Restrict future agenda commands to the location at point in speedbar.
22105 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22106 (interactive)
22107 (require 'org-agenda)
22108 (let (p m tp np dir txt)
22109 (cond
22110 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22111 'org-imenu t))
22112 (setq m (get-text-property p 'org-imenu-marker))
22113 (with-current-buffer (marker-buffer m)
22114 (goto-char m)
22115 (org-agenda-set-restriction-lock 'subtree)))
22116 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22117 'speedbar-function 'speedbar-find-file))
22118 (setq tp (previous-single-property-change
22119 (1+ p) 'speedbar-function)
22120 np (next-single-property-change
22121 tp 'speedbar-function)
22122 dir (speedbar-line-directory)
22123 txt (buffer-substring-no-properties (or tp (point-min))
22124 (or np (point-max))))
22125 (with-current-buffer (find-file-noselect
22126 (let ((default-directory dir))
22127 (expand-file-name txt)))
22128 (unless (derived-mode-p 'org-mode)
22129 (error "Cannot restrict to non-Org-mode file"))
22130 (org-agenda-set-restriction-lock 'file)))
22131 (t (error "Don't know how to restrict Org-mode's agenda")))
22132 (move-overlay org-speedbar-restriction-lock-overlay
22133 (point-at-bol) (point-at-eol))
22134 (setq current-prefix-arg nil)
22135 (org-agenda-maybe-redo)))
22137 (eval-after-load "speedbar"
22138 '(progn
22139 (speedbar-add-supported-extension ".org")
22140 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22141 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22142 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22143 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22144 (add-hook 'speedbar-visiting-tag-hook
22145 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22147 ;;; Fixes and Hacks for problems with other packages
22149 ;; Make flyspell not check words in links, to not mess up our keymap
22150 (defun org-mode-flyspell-verify ()
22151 "Don't let flyspell put overlays at active buttons, or on
22152 {todo,all-time,additional-option-like}-keywords."
22153 (let ((pos (max (1- (point)) (point-min)))
22154 (word (thing-at-point 'word)))
22155 (and (not (get-text-property pos 'keymap))
22156 (not (get-text-property pos 'org-no-flyspell))
22157 (not (member word org-todo-keywords-1))
22158 (not (member word org-all-time-keywords))
22159 (not (member word org-options-keywords))
22160 (not (member word (mapcar 'car org-startup-options)))
22161 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22163 (defun org-remove-flyspell-overlays-in (beg end)
22164 "Remove flyspell overlays in region."
22165 (and (org-bound-and-true-p flyspell-mode)
22166 (fboundp 'flyspell-delete-region-overlays)
22167 (flyspell-delete-region-overlays beg end))
22168 (add-text-properties beg end '(org-no-flyspell t)))
22170 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22171 (eval-after-load "bookmark"
22172 '(if (boundp 'bookmark-after-jump-hook)
22173 ;; We can use the hook
22174 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22175 ;; Hook not available, use advice
22176 (defadvice bookmark-jump (after org-make-visible activate)
22177 "Make the position visible."
22178 (org-bookmark-jump-unhide))))
22180 ;; Make sure saveplace shows the location if it was hidden
22181 (eval-after-load "saveplace"
22182 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22183 "Make the position visible."
22184 (org-bookmark-jump-unhide)))
22186 ;; Make sure ecb shows the location if it was hidden
22187 (eval-after-load "ecb"
22188 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22189 "Make hierarchy visible when jumping into location from ECB tree buffer."
22190 (if (derived-mode-p 'org-mode)
22191 (org-show-context))))
22193 (defun org-bookmark-jump-unhide ()
22194 "Unhide the current position, to show the bookmark location."
22195 (and (derived-mode-p 'org-mode)
22196 (or (outline-invisible-p)
22197 (save-excursion (goto-char (max (point-min) (1- (point))))
22198 (outline-invisible-p)))
22199 (org-show-context 'bookmark-jump)))
22201 ;; Make session.el ignore our circular variable
22202 (eval-after-load "session"
22203 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22205 ;;;; Experimental code
22207 (defun org-closed-in-range ()
22208 "Sparse tree of items closed in a certain time range.
22209 Still experimental, may disappear in the future."
22210 (interactive)
22211 ;; Get the time interval from the user.
22212 (let* ((time1 (org-float-time
22213 (org-read-date nil 'to-time nil "Starting date: ")))
22214 (time2 (org-float-time
22215 (org-read-date nil 'to-time nil "End date:")))
22216 ;; callback function
22217 (callback (lambda ()
22218 (let ((time
22219 (org-float-time
22220 (apply 'encode-time
22221 (org-parse-time-string
22222 (match-string 1))))))
22223 ;; check if time in interval
22224 (and (>= time time1) (<= time time2))))))
22225 ;; make tree, check each match with the callback
22226 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22228 ;;;; Finish up
22230 (provide 'org)
22232 (run-hooks 'org-load-hook)
22234 ;;; org.el ends here