org.el: Fix bug when adjusting another clock
[org-mode.git] / lisp / org.el
blob86ec7472d3888891d436dc8935a4c1bfd0324aa3
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-custom-properties nil
3609 "List of properties (as strings) with a special meaning.
3610 The default use of these custom properties is to let the user
3611 hide them with `org-toggle-custom-properties-visibility'."
3612 :group 'org-properties
3613 :group 'org-appearance
3614 :version "24.2"
3615 :type '(repeat (string :tag "Property Name")))
3617 (defcustom org-fontify-done-headline nil
3618 "Non-nil means change the face of a headline if it is marked DONE.
3619 Normally, only the TODO/DONE keyword indicates the state of a headline.
3620 When this is non-nil, the headline after the keyword is set to the
3621 `org-headline-done' as an additional indication."
3622 :group 'org-appearance
3623 :type 'boolean)
3625 (defcustom org-fontify-emphasized-text t
3626 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3627 Changing this variable requires a restart of Emacs to take effect."
3628 :group 'org-appearance
3629 :type 'boolean)
3631 (defcustom org-fontify-whole-heading-line nil
3632 "Non-nil means fontify the whole line for headings.
3633 This is useful when setting a background color for the
3634 org-level-* faces."
3635 :group 'org-appearance
3636 :type 'boolean)
3638 (defcustom org-highlight-latex-fragments-and-specials nil
3639 "Non-nil means fontify what is treated specially by the exporters."
3640 :group 'org-appearance
3641 :type 'boolean)
3643 (defcustom org-hide-emphasis-markers nil
3644 "Non-nil mean font-lock should hide the emphasis marker characters."
3645 :group 'org-appearance
3646 :type 'boolean)
3648 (defcustom org-pretty-entities nil
3649 "Non-nil means show entities as UTF8 characters.
3650 When nil, the \\name form remains in the buffer."
3651 :group 'org-appearance
3652 :version "24.1"
3653 :type 'boolean)
3655 (defcustom org-pretty-entities-include-sub-superscripts t
3656 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3657 :group 'org-appearance
3658 :version "24.1"
3659 :type 'boolean)
3661 (defvar org-emph-re nil
3662 "Regular expression for matching emphasis.
3663 After a match, the match groups contain these elements:
3664 0 The match of the full regular expression, including the characters
3665 before and after the proper match
3666 1 The character before the proper match, or empty at beginning of line
3667 2 The proper match, including the leading and trailing markers
3668 3 The leading marker like * or /, indicating the type of highlighting
3669 4 The text between the emphasis markers, not including the markers
3670 5 The character after the match, empty at the end of a line")
3671 (defvar org-verbatim-re nil
3672 "Regular expression for matching verbatim text.")
3673 (defvar org-emphasis-regexp-components) ; defined just below
3674 (defvar org-emphasis-alist) ; defined just below
3675 (defun org-set-emph-re (var val)
3676 "Set variable and compute the emphasis regular expression."
3677 (set var val)
3678 (when (and (boundp 'org-emphasis-alist)
3679 (boundp 'org-emphasis-regexp-components)
3680 org-emphasis-alist org-emphasis-regexp-components)
3681 (let* ((e org-emphasis-regexp-components)
3682 (pre (car e))
3683 (post (nth 1 e))
3684 (border (nth 2 e))
3685 (body (nth 3 e))
3686 (nl (nth 4 e))
3687 (body1 (concat body "*?"))
3688 (markers (mapconcat 'car org-emphasis-alist ""))
3689 (vmarkers (mapconcat
3690 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3691 org-emphasis-alist "")))
3692 ;; make sure special characters appear at the right position in the class
3693 (if (string-match "\\^" markers)
3694 (setq markers (concat (replace-match "" t t markers) "^")))
3695 (if (string-match "-" markers)
3696 (setq markers (concat (replace-match "" t t markers) "-")))
3697 (if (string-match "\\^" vmarkers)
3698 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3699 (if (string-match "-" vmarkers)
3700 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3701 (if (> nl 0)
3702 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3703 (int-to-string nl) "\\}")))
3704 ;; Make the regexp
3705 (setq org-emph-re
3706 (concat "\\([" pre "]\\|^\\)"
3707 "\\("
3708 "\\([" markers "]\\)"
3709 "\\("
3710 "[^" border "]\\|"
3711 "[^" border "]"
3712 body1
3713 "[^" border "]"
3714 "\\)"
3715 "\\3\\)"
3716 "\\([" post "]\\|$\\)"))
3717 (setq org-verbatim-re
3718 (concat "\\([" pre "]\\|^\\)"
3719 "\\("
3720 "\\([" vmarkers "]\\)"
3721 "\\("
3722 "[^" border "]\\|"
3723 "[^" border "]"
3724 body1
3725 "[^" border "]"
3726 "\\)"
3727 "\\3\\)"
3728 "\\([" post "]\\|$\\)")))))
3730 (defcustom org-emphasis-regexp-components
3731 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3732 "Components used to build the regular expression for emphasis.
3733 This is a list with five entries. Terminology: In an emphasis string
3734 like \" *strong word* \", we call the initial space PREMATCH, the final
3735 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3736 and \"trong wor\" is the body. The different components in this variable
3737 specify what is allowed/forbidden in each part:
3739 pre Chars allowed as prematch. Beginning of line will be allowed too.
3740 post Chars allowed as postmatch. End of line will be allowed too.
3741 border The chars *forbidden* as border characters.
3742 body-regexp A regexp like \".\" to match a body character. Don't use
3743 non-shy groups here, and don't allow newline here.
3744 newline The maximum number of newlines allowed in an emphasis exp.
3746 Use customize to modify this, or restart Emacs after changing it."
3747 :group 'org-appearance
3748 :set 'org-set-emph-re
3749 :type '(list
3750 (sexp :tag "Allowed chars in pre ")
3751 (sexp :tag "Allowed chars in post ")
3752 (sexp :tag "Forbidden chars in border ")
3753 (sexp :tag "Regexp for body ")
3754 (integer :tag "number of newlines allowed")
3755 (option (boolean :tag "Please ignore this button"))))
3757 (defcustom org-emphasis-alist
3758 `(("*" bold "<b>" "</b>")
3759 ("/" italic "<i>" "</i>")
3760 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3761 ("=" org-code "<code>" "</code>" verbatim)
3762 ("~" org-verbatim "<code>" "</code>" verbatim)
3763 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3764 "<del>" "</del>")
3766 "Special syntax for emphasized text.
3767 Text starting and ending with a special character will be emphasized, for
3768 example *bold*, _underlined_ and /italic/. This variable sets the marker
3769 characters, the face to be used by font-lock for highlighting in Org-mode
3770 Emacs buffers, and the HTML tags to be used for this.
3771 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3772 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3773 Use customize to modify this, or restart Emacs after changing it."
3774 :group 'org-appearance
3775 :set 'org-set-emph-re
3776 :type '(repeat
3777 (list
3778 (string :tag "Marker character")
3779 (choice
3780 (face :tag "Font-lock-face")
3781 (plist :tag "Face property list"))
3782 (string :tag "HTML start tag")
3783 (string :tag "HTML end tag")
3784 (option (const verbatim)))))
3786 (defvar org-protecting-blocks
3787 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3788 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3789 This is needed for font-lock setup.")
3791 ;;; Miscellaneous options
3793 (defgroup org-completion nil
3794 "Completion in Org-mode."
3795 :tag "Org Completion"
3796 :group 'org)
3798 (defcustom org-completion-use-ido nil
3799 "Non-nil means use ido completion wherever possible.
3800 Note that `ido-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 See also `org-completion-use-iswitchb'."
3804 :group 'org-completion
3805 :type 'boolean)
3807 (defcustom org-completion-use-iswitchb nil
3808 "Non-nil means use iswitchb completion wherever possible.
3809 Note that `iswitchb-mode' must be active for this variable to be relevant.
3810 If you decide to turn this variable on, you might well want to turn off
3811 `org-outline-path-complete-in-steps'.
3812 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3813 :group 'org-completion
3814 :type 'boolean)
3816 (defcustom org-completion-fallback-command 'hippie-expand
3817 "The expansion command called by \\[pcomplete] in normal context.
3818 Normal means, no org-mode-specific context."
3819 :group 'org-completion
3820 :type 'function)
3822 ;;; Functions and variables from their packages
3823 ;; Declared here to avoid compiler warnings
3825 ;; XEmacs only
3826 (defvar outline-mode-menu-heading)
3827 (defvar outline-mode-menu-show)
3828 (defvar outline-mode-menu-hide)
3829 (defvar zmacs-regions) ; XEmacs regions
3831 ;; Emacs only
3832 (defvar mark-active)
3834 ;; Various packages
3835 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3836 (declare-function calendar-forward-day "cal-move" (arg))
3837 (declare-function calendar-goto-date "cal-move" (date))
3838 (declare-function calendar-goto-today "cal-move" ())
3839 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3840 (defvar calc-embedded-close-formula)
3841 (defvar calc-embedded-open-formula)
3842 (declare-function cdlatex-tab "ext:cdlatex" ())
3843 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3844 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3845 (defvar font-lock-unfontify-region-function)
3846 (declare-function iswitchb-read-buffer "iswitchb"
3847 (prompt &optional default require-match start matches-set))
3848 (defvar iswitchb-temp-buflist)
3849 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3850 (defvar org-agenda-tags-todo-honor-ignore-options)
3851 (declare-function org-agenda-skip "org-agenda" ())
3852 (declare-function
3853 org-agenda-format-item "org-agenda"
3854 (extra txt &optional category tags dotime noprefix remove-re habitp))
3855 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3856 (declare-function org-agenda-change-all-lines "org-agenda"
3857 (newhead hdmarker &optional fixface just-this))
3858 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3859 (declare-function org-agenda-maybe-redo "org-agenda" ())
3860 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3861 (beg end))
3862 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3863 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3864 "org-agenda" (&optional end))
3865 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3866 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3867 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3868 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3869 (declare-function org-indent-mode "org-indent" (&optional arg))
3870 (declare-function parse-time-string "parse-time" (string))
3871 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3872 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3873 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3874 (defvar remember-data-file)
3875 (defvar texmathp-why)
3876 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3877 (declare-function table--at-cell-p "table" (position &optional object at-column))
3879 (defvar w3m-current-url)
3880 (defvar w3m-current-title)
3882 (defvar org-latex-regexps)
3884 ;;; Autoload and prepare some org modules
3886 ;; Some table stuff that needs to be defined here, because it is used
3887 ;; by the functions setting up org-mode or checking for table context.
3889 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3890 "Detect an org-type or table-type table.")
3891 (defconst org-table-line-regexp "^[ \t]*|"
3892 "Detect an org-type table line.")
3893 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3894 "Detect an org-type table line.")
3895 (defconst org-table-hline-regexp "^[ \t]*|-"
3896 "Detect an org-type table hline.")
3897 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3898 "Detect a table-type table hline.")
3899 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3900 "Detect the first line outside a table when searching from within it.
3901 This works for both table types.")
3903 ;; Autoload the functions in org-table.el that are needed by functions here.
3905 (eval-and-compile
3906 (org-autoload "org-table"
3907 '(org-table-align org-table-begin org-table-blank-field
3908 org-table-convert org-table-convert-region org-table-copy-down
3909 org-table-copy-region org-table-create
3910 org-table-create-or-convert-from-region
3911 org-table-create-with-table.el org-table-current-dline
3912 org-table-cut-region org-table-delete-column org-table-edit-field
3913 org-table-edit-formulas org-table-end org-table-eval-formula
3914 org-table-export org-table-field-info
3915 org-table-get-stored-formulas org-table-goto-column
3916 org-table-hline-and-move org-table-import org-table-insert-column
3917 org-table-insert-hline org-table-insert-row org-table-iterate
3918 org-table-justify-field-maybe org-table-kill-row
3919 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3920 org-table-move-column org-table-move-column-left
3921 org-table-move-column-right org-table-move-row
3922 org-table-move-row-down org-table-move-row-up
3923 org-table-next-field org-table-next-row org-table-paste-rectangle
3924 org-table-previous-field org-table-recalculate
3925 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3926 org-table-toggle-coordinate-overlays
3927 org-table-toggle-formula-debugger org-table-wrap-region
3928 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3929 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3930 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3932 (defun org-at-table-p (&optional table-type)
3933 "Return t if the cursor is inside an org-type table.
3934 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3935 (if org-enable-table-editor
3936 (save-excursion
3937 (beginning-of-line 1)
3938 (looking-at (if table-type org-table-any-line-regexp
3939 org-table-line-regexp)))
3940 nil))
3941 (defsubst org-table-p () (org-at-table-p))
3943 (defun org-at-table.el-p ()
3944 "Return t if and only if we are at a table.el table."
3945 (and (org-at-table-p 'any)
3946 (save-excursion
3947 (goto-char (org-table-begin 'any))
3948 (looking-at org-table1-hline-regexp))))
3949 (defun org-table-recognize-table.el ()
3950 "If there is a table.el table nearby, recognize it and move into it."
3951 (if org-table-tab-recognizes-table.el
3952 (if (org-at-table.el-p)
3953 (progn
3954 (beginning-of-line 1)
3955 (if (looking-at org-table-dataline-regexp)
3957 (if (looking-at org-table1-hline-regexp)
3958 (progn
3959 (beginning-of-line 2)
3960 (if (looking-at org-table-any-border-regexp)
3961 (beginning-of-line -1)))))
3962 (if (re-search-forward "|" (org-table-end t) t)
3963 (progn
3964 (require 'table)
3965 (if (table--at-cell-p (point))
3967 (message "recognizing table.el table...")
3968 (table-recognize-table)
3969 (message "recognizing table.el table...done")))
3970 (error "This should not happen"))
3972 nil)
3973 nil))
3975 (defun org-at-table-hline-p ()
3976 "Return t if the cursor is inside a hline in a table."
3977 (if org-enable-table-editor
3978 (save-excursion
3979 (beginning-of-line 1)
3980 (looking-at org-table-hline-regexp))
3981 nil))
3983 (defvar org-table-clean-did-remove-column nil)
3985 (defun org-table-map-tables (function &optional quietly)
3986 "Apply FUNCTION to the start of all tables in the buffer."
3987 (save-excursion
3988 (save-restriction
3989 (widen)
3990 (goto-char (point-min))
3991 (while (re-search-forward org-table-any-line-regexp nil t)
3992 (unless quietly
3993 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3994 (beginning-of-line 1)
3995 (when (and (looking-at org-table-line-regexp)
3996 ;; Exclude tables in src/example/verbatim/clocktable blocks
3997 (not (org-in-block-p '("src" "example"))))
3998 (save-excursion (funcall function))
3999 (or (looking-at org-table-line-regexp)
4000 (forward-char 1)))
4001 (re-search-forward org-table-any-border-regexp nil 1))))
4002 (unless quietly (message "Mapping tables: done")))
4004 ;; Declare and autoload functions from org-exp.el & Co
4006 (declare-function org-default-export-plist "org-exp")
4007 (declare-function org-infile-export-plist "org-exp")
4008 (declare-function org-get-current-options "org-exp")
4009 (eval-and-compile
4010 (org-autoload "org-exp"
4011 '(org-export org-export-visible
4012 org-insert-export-options-template
4013 org-table-clean-before-export))
4014 (org-autoload "org-ascii"
4015 '(org-export-as-ascii org-export-ascii-preprocess
4016 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4017 org-export-region-as-ascii))
4018 (org-autoload "org-latex"
4019 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4020 org-replace-region-by-latex org-export-region-as-latex
4021 org-export-as-latex org-export-as-pdf
4022 org-export-as-pdf-and-open))
4023 (org-autoload "org-html"
4024 '(org-export-as-html-and-open
4025 org-export-as-html-batch org-export-as-html-to-buffer
4026 org-replace-region-by-html org-export-region-as-html
4027 org-export-as-html))
4028 (org-autoload "org-docbook"
4029 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4030 org-replace-region-by-docbook org-export-region-as-docbook
4031 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4032 org-export-as-docbook))
4033 (org-autoload "org-icalendar"
4034 '(org-export-icalendar-this-file
4035 org-export-icalendar-all-agenda-files
4036 org-export-icalendar-combine-agenda-files))
4037 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4038 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4040 ;; Declare and autoload functions from org-agenda.el
4042 (eval-and-compile
4043 (org-autoload "org-agenda"
4044 '(org-agenda org-agenda-list org-search-view
4045 org-todo-list org-tags-view org-agenda-list-stuck-projects
4046 org-diary org-agenda-to-appt
4047 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4049 ;; Autoload org-remember
4051 (eval-and-compile
4052 (org-autoload "org-remember"
4053 '(org-remember-insinuate org-remember-annotation
4054 org-remember-apply-template org-remember org-remember-handler)))
4056 (eval-and-compile
4057 (org-autoload "org-capture"
4058 '(org-capture org-capture-insert-template-here
4059 org-capture-import-remember-templates)))
4061 ;; Autoload org-clock.el
4063 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4064 (beg end))
4065 (declare-function org-clock-update-mode-line "org-clock" ())
4066 (declare-function org-resolve-clocks "org-clock"
4067 (&optional also-non-dangling-p prompt last-valid))
4068 (defvar org-clock-start-time)
4069 (defvar org-clock-marker (make-marker)
4070 "Marker recording the last clock-in.")
4071 (defvar org-clock-hd-marker (make-marker)
4072 "Marker recording the last clock-in, but the headline position.")
4073 (defvar org-clock-heading ""
4074 "The heading of the current clock entry.")
4075 (defun org-clock-is-active ()
4076 "Return non-nil if clock is currently running.
4077 The return value is actually the clock marker."
4078 (marker-buffer org-clock-marker))
4080 (eval-and-compile
4081 (org-autoload
4082 "org-clock"
4083 '(org-clock-in org-clock-out org-clock-cancel
4084 org-clock-goto org-clock-sum org-clock-display
4085 org-clock-remove-overlays org-clock-report
4086 org-clocktable-shift org-dblock-write:clocktable
4087 org-get-clocktable org-resolve-clocks)))
4089 (defun org-clock-update-time-maybe ()
4090 "If this is a CLOCK line, update it and return t.
4091 Otherwise, return nil."
4092 (interactive)
4093 (save-excursion
4094 (beginning-of-line 1)
4095 (skip-chars-forward " \t")
4096 (when (looking-at org-clock-string)
4097 (let ((re (concat "[ \t]*" org-clock-string
4098 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4099 "\\([ \t]*=>.*\\)?\\)?"))
4100 ts te h m s neg)
4101 (cond
4102 ((not (looking-at re))
4103 nil)
4104 ((not (match-end 2))
4105 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4106 (> org-clock-marker (point))
4107 (<= org-clock-marker (point-at-eol)))
4108 ;; The clock is running here
4109 (setq org-clock-start-time
4110 (apply 'encode-time
4111 (org-parse-time-string (match-string 1))))
4112 (org-clock-update-mode-line)))
4114 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4115 (end-of-line 1)
4116 (setq ts (match-string 1)
4117 te (match-string 3))
4118 (setq s (- (org-float-time
4119 (apply 'encode-time (org-parse-time-string te)))
4120 (org-float-time
4121 (apply 'encode-time (org-parse-time-string ts))))
4122 neg (< s 0)
4123 s (abs s)
4124 h (floor (/ s 3600))
4125 s (- s (* 3600 h))
4126 m (floor (/ s 60))
4127 s (- s (* 60 s)))
4128 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4129 t))))))
4131 (defun org-check-running-clock ()
4132 "Check if the current buffer contains the running clock.
4133 If yes, offer to stop it and to save the buffer with the changes."
4134 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4135 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4136 (buffer-name))))
4137 (org-clock-out)
4138 (when (y-or-n-p "Save changed buffer?")
4139 (save-buffer))))
4141 (defun org-clocktable-try-shift (dir n)
4142 "Check if this line starts a clock table, if yes, shift the time block."
4143 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4144 (org-clocktable-shift dir n)))
4146 ;; Autoload org-timer.el
4148 (eval-and-compile
4149 (org-autoload
4150 "org-timer"
4151 '(org-timer-start org-timer org-timer-item
4152 org-timer-change-times-in-region
4153 org-timer-set-timer
4154 org-timer-reset-timers
4155 org-timer-show-remaining-time)))
4157 ;; Autoload org-feed.el
4159 (eval-and-compile
4160 (org-autoload
4161 "org-feed"
4162 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4165 ;; Autoload org-indent.el
4167 ;; Define the variable already here, to make sure we have it.
4168 (defvar org-indent-mode nil
4169 "Non-nil if Org-Indent mode is enabled.
4170 Use the command `org-indent-mode' to change this variable.")
4172 (eval-and-compile
4173 (org-autoload
4174 "org-indent"
4175 '(org-indent-mode)))
4177 ;; Autoload org-mobile.el
4179 (eval-and-compile
4180 (org-autoload
4181 "org-mobile"
4182 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4184 ;; Autoload archiving code
4185 ;; The stuff that is needed for cycling and tags has to be defined here.
4187 (defgroup org-archive nil
4188 "Options concerning archiving in Org-mode."
4189 :tag "Org Archive"
4190 :group 'org-structure)
4192 (defcustom org-archive-location "%s_archive::"
4193 "The location where subtrees should be archived.
4195 The value of this variable is a string, consisting of two parts,
4196 separated by a double-colon. The first part is a filename and
4197 the second part is a headline.
4199 When the filename is omitted, archiving happens in the same file.
4200 %s in the filename will be replaced by the current file
4201 name (without the directory part). Archiving to a different file
4202 is useful to keep archived entries from contributing to the
4203 Org-mode Agenda.
4205 The archived entries will be filed as subtrees of the specified
4206 headline. When the headline is omitted, the subtrees are simply
4207 filed away at the end of the file, as top-level entries. Also in
4208 the heading you can use %s to represent the file name, this can be
4209 useful when using the same archive for a number of different files.
4211 Here are a few examples:
4212 \"%s_archive::\"
4213 If the current file is Projects.org, archive in file
4214 Projects.org_archive, as top-level trees. This is the default.
4216 \"::* Archived Tasks\"
4217 Archive in the current file, under the top-level headline
4218 \"* Archived Tasks\".
4220 \"~/org/archive.org::\"
4221 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4223 \"~/org/archive.org::* From %s\"
4224 Archive in file ~/org/archive.org (absolute path), under headlines
4225 \"From FILENAME\" where file name is the current file name.
4227 \"~/org/datetree.org::datetree/* Finished Tasks\"
4228 The \"datetree/\" string is special, signifying to archive
4229 items to the datetree. Items are placed in either the CLOSED
4230 date of the item, or the current date if there is no CLOSED date.
4231 The heading will be a subentry to the current date. There doesn't
4232 need to be a heading, but there always needs to be a slash after
4233 datetree. For example, to store archived items directly in the
4234 datetree, use \"~/org/datetree.org::datetree/\".
4236 \"basement::** Finished Tasks\"
4237 Archive in file ./basement (relative path), as level 3 trees
4238 below the level 2 heading \"** Finished Tasks\".
4240 You may set this option on a per-file basis by adding to the buffer a
4241 line like
4243 #+ARCHIVE: basement::** Finished Tasks
4245 You may also define it locally for a subtree by setting an ARCHIVE property
4246 in the entry. If such a property is found in an entry, or anywhere up
4247 the hierarchy, it will be used."
4248 :group 'org-archive
4249 :type 'string)
4251 (defcustom org-archive-tag "ARCHIVE"
4252 "The tag that marks a subtree as archived.
4253 An archived subtree does not open during visibility cycling, and does
4254 not contribute to the agenda listings.
4255 After changing this, font-lock must be restarted in the relevant buffers to
4256 get the proper fontification."
4257 :group 'org-archive
4258 :group 'org-keywords
4259 :type 'string)
4261 (defcustom org-agenda-skip-archived-trees t
4262 "Non-nil means the agenda will skip any items located in archived trees.
4263 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4264 variable is no longer recommended, you should leave it at the value t.
4265 Instead, use the key `v' to cycle the archives-mode in the agenda."
4266 :group 'org-archive
4267 :group 'org-agenda-skip
4268 :type 'boolean)
4270 (defcustom org-columns-skip-archived-trees t
4271 "Non-nil means ignore archived trees when creating column view."
4272 :group 'org-archive
4273 :group 'org-properties
4274 :type 'boolean)
4276 (defcustom org-cycle-open-archived-trees nil
4277 "Non-nil means `org-cycle' will open archived trees.
4278 An archived tree is a tree marked with the tag ARCHIVE.
4279 When nil, archived trees will stay folded. You can still open them with
4280 normal outline commands like `show-all', but not with the cycling commands."
4281 :group 'org-archive
4282 :group 'org-cycle
4283 :type 'boolean)
4285 (defcustom org-sparse-tree-open-archived-trees nil
4286 "Non-nil means sparse tree construction shows matches in archived trees.
4287 When nil, matches in these trees are highlighted, but the trees are kept in
4288 collapsed state."
4289 :group 'org-archive
4290 :group 'org-sparse-trees
4291 :type 'boolean)
4293 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4294 "The default date type when building a sparse tree.
4295 When this is nil, a date is a scheduled or a deadline timestamp.
4296 Otherwise, these types are allowed:
4298 all: all timestamps
4299 active: only active timestamps (<...>)
4300 inactive: only inactive timestamps (<...)
4301 scheduled: only scheduled timestamps
4302 deadline: only deadline timestamps"
4303 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4304 (const :tag "All timestamps" all)
4305 (const :tag "Only active timestamps" active)
4306 (const :tag "Only inactive timestamps" inactive)
4307 (const :tag "Only scheduled timestamps" scheduled)
4308 (const :tag "Only deadline timestamps" deadline))
4309 :group 'org-sparse-trees
4310 :version "24.2")
4312 (defun org-cycle-hide-archived-subtrees (state)
4313 "Re-hide all archived subtrees after a visibility state change."
4314 (when (and (not org-cycle-open-archived-trees)
4315 (not (memq state '(overview folded))))
4316 (save-excursion
4317 (let* ((globalp (memq state '(contents all)))
4318 (beg (if globalp (point-min) (point)))
4319 (end (if globalp (point-max) (org-end-of-subtree t))))
4320 (org-hide-archived-subtrees beg end)
4321 (goto-char beg)
4322 (if (looking-at (concat ".*:" org-archive-tag ":"))
4323 (message "%s" (substitute-command-keys
4324 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4326 (defun org-force-cycle-archived ()
4327 "Cycle subtree even if it is archived."
4328 (interactive)
4329 (setq this-command 'org-cycle)
4330 (let ((org-cycle-open-archived-trees t))
4331 (call-interactively 'org-cycle)))
4333 (defun org-hide-archived-subtrees (beg end)
4334 "Re-hide all archived subtrees after a visibility state change."
4335 (save-excursion
4336 (let* ((re (concat ":" org-archive-tag ":")))
4337 (goto-char beg)
4338 (while (re-search-forward re end t)
4339 (when (org-at-heading-p)
4340 (org-flag-subtree t)
4341 (org-end-of-subtree t))))))
4343 (declare-function outline-end-of-heading "outline" ())
4344 (declare-function outline-flag-region "outline" (from to flag))
4345 (defun org-flag-subtree (flag)
4346 (save-excursion
4347 (org-back-to-heading t)
4348 (outline-end-of-heading)
4349 (outline-flag-region (point)
4350 (progn (org-end-of-subtree t) (point))
4351 flag)))
4353 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4355 (eval-and-compile
4356 (org-autoload "org-archive"
4357 '(org-add-archive-files org-archive-subtree
4358 org-archive-to-archive-sibling org-toggle-archive-tag
4359 org-archive-subtree-default
4360 org-archive-subtree-default-with-confirmation)))
4362 ;; Autoload Column View Code
4364 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4365 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4366 (declare-function org-columns-compute "org-colview" (property))
4368 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4369 '(org-columns-number-to-string org-columns-get-format-and-top-level
4370 org-columns-compute org-agenda-columns org-columns-remove-overlays
4371 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4373 ;; Autoload ID code
4375 (declare-function org-id-store-link "org-id")
4376 (declare-function org-id-locations-load "org-id")
4377 (declare-function org-id-locations-save "org-id")
4378 (defvar org-id-track-globally)
4379 (org-autoload "org-id"
4380 '(org-id-get-create org-id-new org-id-copy org-id-get
4381 org-id-get-with-outline-path-completion
4382 org-id-get-with-outline-drilling org-id-store-link
4383 org-id-goto org-id-find org-id-store-link))
4385 ;; Autoload Plotting Code
4387 (org-autoload "org-plot"
4388 '(org-plot/gnuplot))
4390 ;;; Variables for pre-computed regular expressions, all buffer local
4392 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4393 "Matches first line of a hidden block.")
4394 (make-variable-buffer-local 'org-drawer-regexp)
4395 (defvar org-todo-regexp nil
4396 "Matches any of the TODO state keywords.")
4397 (make-variable-buffer-local 'org-todo-regexp)
4398 (defvar org-not-done-regexp nil
4399 "Matches any of the TODO state keywords except the last one.")
4400 (make-variable-buffer-local 'org-not-done-regexp)
4401 (defvar org-not-done-heading-regexp nil
4402 "Matches a TODO headline that is not done.")
4403 (make-variable-buffer-local 'org-not-done-regexp)
4404 (defvar org-todo-line-regexp nil
4405 "Matches a headline and puts TODO state into group 2 if present.")
4406 (make-variable-buffer-local 'org-todo-line-regexp)
4407 (defvar org-complex-heading-regexp nil
4408 "Matches a headline and puts everything into groups:
4409 group 1: the stars
4410 group 2: The todo keyword, maybe
4411 group 3: Priority cookie
4412 group 4: True headline
4413 group 5: Tags")
4414 (make-variable-buffer-local 'org-complex-heading-regexp)
4415 (defvar org-complex-heading-regexp-format nil
4416 "Printf format to make regexp to match an exact headline.
4417 This regexp will match the headline of any node which has the
4418 exact headline text that is put into the format, but may have any
4419 TODO state, priority and tags.")
4420 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4421 (defvar org-todo-line-tags-regexp nil
4422 "Matches a headline and puts TODO state into group 2 if present.
4423 Also put tags into group 4 if tags are present.")
4424 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4425 (defvar org-ds-keyword-length 12
4426 "Maximum length of the Deadline and SCHEDULED keywords.")
4427 (make-variable-buffer-local 'org-ds-keyword-length)
4428 (defvar org-deadline-regexp nil
4429 "Matches the DEADLINE keyword.")
4430 (make-variable-buffer-local 'org-deadline-regexp)
4431 (defvar org-deadline-time-regexp nil
4432 "Matches the DEADLINE keyword together with a time stamp.")
4433 (make-variable-buffer-local 'org-deadline-time-regexp)
4434 (defvar org-deadline-line-regexp nil
4435 "Matches the DEADLINE keyword and the rest of the line.")
4436 (make-variable-buffer-local 'org-deadline-line-regexp)
4437 (defvar org-scheduled-regexp nil
4438 "Matches the SCHEDULED keyword.")
4439 (make-variable-buffer-local 'org-scheduled-regexp)
4440 (defvar org-scheduled-time-regexp nil
4441 "Matches the SCHEDULED keyword together with a time stamp.")
4442 (make-variable-buffer-local 'org-scheduled-time-regexp)
4443 (defvar org-closed-time-regexp nil
4444 "Matches the CLOSED keyword together with a time stamp.")
4445 (make-variable-buffer-local 'org-closed-time-regexp)
4447 (defvar org-keyword-time-regexp nil
4448 "Matches any of the 4 keywords, together with the time stamp.")
4449 (make-variable-buffer-local 'org-keyword-time-regexp)
4450 (defvar org-keyword-time-not-clock-regexp nil
4451 "Matches any of the 3 keywords, together with the time stamp.")
4452 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4453 (defvar org-maybe-keyword-time-regexp nil
4454 "Matches a timestamp, possibly preceded by a keyword.")
4455 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4456 (defvar org-all-time-keywords nil
4457 "List of time keywords.")
4458 (make-variable-buffer-local 'org-all-time-keywords)
4460 (defconst org-plain-time-of-day-regexp
4461 (concat
4462 "\\(\\<[012]?[0-9]"
4463 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4464 "\\(--?"
4465 "\\(\\<[012]?[0-9]"
4466 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4467 "\\)?")
4468 "Regular expression to match a plain time or time range.
4469 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4470 groups carry important information:
4471 0 the full match
4472 1 the first time, range or not
4473 8 the second time, if it is a range.")
4475 (defconst org-plain-time-extension-regexp
4476 (concat
4477 "\\(\\<[012]?[0-9]"
4478 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4479 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4480 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4481 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4482 groups carry important information:
4483 0 the full match
4484 7 hours of duration
4485 9 minutes of duration")
4487 (defconst org-stamp-time-of-day-regexp
4488 (concat
4489 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4490 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4491 "\\(--?"
4492 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4493 "Regular expression to match a timestamp time or time range.
4494 After a match, the following groups carry important information:
4495 0 the full match
4496 1 date plus weekday, for back referencing to make sure both times are on the same day
4497 2 the first time, range or not
4498 4 the second time, if it is a range.")
4500 (defconst org-startup-options
4501 '(("fold" org-startup-folded t)
4502 ("overview" org-startup-folded t)
4503 ("nofold" org-startup-folded nil)
4504 ("showall" org-startup-folded nil)
4505 ("showeverything" org-startup-folded showeverything)
4506 ("content" org-startup-folded content)
4507 ("indent" org-startup-indented t)
4508 ("noindent" org-startup-indented nil)
4509 ("hidestars" org-hide-leading-stars t)
4510 ("showstars" org-hide-leading-stars nil)
4511 ("odd" org-odd-levels-only t)
4512 ("oddeven" org-odd-levels-only nil)
4513 ("align" org-startup-align-all-tables t)
4514 ("noalign" org-startup-align-all-tables nil)
4515 ("inlineimages" org-startup-with-inline-images t)
4516 ("noinlineimages" org-startup-with-inline-images nil)
4517 ("customtime" org-display-custom-times t)
4518 ("logdone" org-log-done time)
4519 ("lognotedone" org-log-done note)
4520 ("nologdone" org-log-done nil)
4521 ("lognoteclock-out" org-log-note-clock-out t)
4522 ("nolognoteclock-out" org-log-note-clock-out nil)
4523 ("logrepeat" org-log-repeat state)
4524 ("lognoterepeat" org-log-repeat note)
4525 ("nologrepeat" org-log-repeat nil)
4526 ("logreschedule" org-log-reschedule time)
4527 ("lognotereschedule" org-log-reschedule note)
4528 ("nologreschedule" org-log-reschedule nil)
4529 ("logredeadline" org-log-redeadline time)
4530 ("lognoteredeadline" org-log-redeadline note)
4531 ("nologredeadline" org-log-redeadline nil)
4532 ("logrefile" org-log-refile time)
4533 ("lognoterefile" org-log-refile note)
4534 ("nologrefile" org-log-refile nil)
4535 ("fninline" org-footnote-define-inline t)
4536 ("nofninline" org-footnote-define-inline nil)
4537 ("fnlocal" org-footnote-section nil)
4538 ("fnauto" org-footnote-auto-label t)
4539 ("fnprompt" org-footnote-auto-label nil)
4540 ("fnconfirm" org-footnote-auto-label confirm)
4541 ("fnplain" org-footnote-auto-label plain)
4542 ("fnadjust" org-footnote-auto-adjust t)
4543 ("nofnadjust" org-footnote-auto-adjust nil)
4544 ("constcgs" constants-unit-system cgs)
4545 ("constSI" constants-unit-system SI)
4546 ("noptag" org-tag-persistent-alist nil)
4547 ("hideblocks" org-hide-block-startup t)
4548 ("nohideblocks" org-hide-block-startup nil)
4549 ("beamer" org-startup-with-beamer-mode t)
4550 ("entitiespretty" org-pretty-entities t)
4551 ("entitiesplain" org-pretty-entities nil))
4552 "Variable associated with STARTUP options for org-mode.
4553 Each element is a list of three items: the startup options (as written
4554 in the #+STARTUP line), the corresponding variable, and the value to set
4555 this variable to if the option is found. An optional forth element PUSH
4556 means to push this value onto the list in the variable.")
4558 (defun org-update-property-plist (key val props)
4559 "Update PROPS with KEY and VAL."
4560 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4561 (key (if appending (substring key 0 (- (length key) 1)) key))
4562 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4563 (previous (cdr (assoc key props))))
4564 (if appending
4565 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4566 (cons (cons key val) remainder))))
4568 (defconst org-block-regexp
4569 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4570 "Regular expression for hiding blocks.")
4571 (defconst org-heading-keyword-regexp-format
4572 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4573 "Printf format for a regexp matching an headline with some keyword.
4574 This regexp will match the headline of any node which has the
4575 exact keyword that is put into the format. The keyword isn't in
4576 any group by default, but the stars and the body are.")
4577 (defconst org-heading-keyword-maybe-regexp-format
4578 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4579 "Printf format for a regexp matching an headline, possibly with some keyword.
4580 This regexp can match any headline with the specified keyword, or
4581 without a keyword. The keyword isn't in any group by default,
4582 but the stars and the body are.")
4584 (defun org-set-regexps-and-options ()
4585 "Precompute regular expressions for current buffer."
4586 (when (derived-mode-p 'org-mode)
4587 (org-set-local 'org-todo-kwd-alist nil)
4588 (org-set-local 'org-todo-key-alist nil)
4589 (org-set-local 'org-todo-key-trigger nil)
4590 (org-set-local 'org-todo-keywords-1 nil)
4591 (org-set-local 'org-done-keywords nil)
4592 (org-set-local 'org-todo-heads nil)
4593 (org-set-local 'org-todo-sets nil)
4594 (org-set-local 'org-todo-log-states nil)
4595 (org-set-local 'org-file-properties nil)
4596 (org-set-local 'org-file-tags nil)
4597 (let ((re (org-make-options-regexp
4598 '("CATEGORY" "TODO" "COLUMNS"
4599 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4600 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4601 "OPTIONS")
4602 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4603 (splitre "[ \t]+")
4604 (scripts org-use-sub-superscripts)
4605 kwds kws0 kwsa key log value cat arch tags const links hw dws
4606 tail sep kws1 prio props ftags drawers beamer-p
4607 ext-setup-or-nil setup-contents (start 0))
4608 (save-excursion
4609 (save-restriction
4610 (widen)
4611 (goto-char (point-min))
4612 (while (or (and ext-setup-or-nil
4613 (string-match re ext-setup-or-nil start)
4614 (setq start (match-end 0)))
4615 (and (setq ext-setup-or-nil nil start 0)
4616 (re-search-forward re nil t)))
4617 (setq key (upcase (match-string 1 ext-setup-or-nil))
4618 value (org-match-string-no-properties 2 ext-setup-or-nil))
4619 (if (stringp value) (setq value (org-trim value)))
4620 (cond
4621 ((equal key "CATEGORY")
4622 (setq cat value))
4623 ((member key '("SEQ_TODO" "TODO"))
4624 (push (cons 'sequence (org-split-string value splitre)) kwds))
4625 ((equal key "TYP_TODO")
4626 (push (cons 'type (org-split-string value splitre)) kwds))
4627 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4628 ;; general TODO-like setup
4629 (push (cons (intern (downcase (match-string 1 key)))
4630 (org-split-string value splitre)) kwds))
4631 ((equal key "TAGS")
4632 (setq tags (append tags (if tags '("\\n") nil)
4633 (org-split-string value splitre))))
4634 ((equal key "COLUMNS")
4635 (org-set-local 'org-columns-default-format value))
4636 ((equal key "LINK")
4637 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4638 (push (cons (match-string 1 value)
4639 (org-trim (match-string 2 value)))
4640 links)))
4641 ((equal key "PRIORITIES")
4642 (setq prio (org-split-string value " +")))
4643 ((equal key "PROPERTY")
4644 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4645 (setq props (org-update-property-plist (match-string 1 value)
4646 (match-string 2 value)
4647 props))))
4648 ((equal key "FILETAGS")
4649 (when (string-match "\\S-" value)
4650 (setq ftags
4651 (append
4652 ftags
4653 (apply 'append
4654 (mapcar (lambda (x) (org-split-string x ":"))
4655 (org-split-string value)))))))
4656 ((equal key "DRAWERS")
4657 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4658 ((equal key "CONSTANTS")
4659 (setq const (append const (org-split-string value splitre))))
4660 ((equal key "STARTUP")
4661 (let ((opts (org-split-string value splitre))
4662 l var val)
4663 (while (setq l (pop opts))
4664 (when (setq l (assoc l org-startup-options))
4665 (setq var (nth 1 l) val (nth 2 l))
4666 (if (not (nth 3 l))
4667 (set (make-local-variable var) val)
4668 (if (not (listp (symbol-value var)))
4669 (set (make-local-variable var) nil))
4670 (set (make-local-variable var) (symbol-value var))
4671 (add-to-list var val))))))
4672 ((equal key "ARCHIVE")
4673 (setq arch value)
4674 (remove-text-properties 0 (length arch)
4675 '(face t fontified t) arch))
4676 ((equal key "LATEX_CLASS")
4677 (setq beamer-p (equal value "beamer")))
4678 ((equal key "OPTIONS")
4679 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4680 (setq scripts (read (match-string 2 value)))))
4681 ((equal key "SETUPFILE")
4682 (setq setup-contents (org-file-contents
4683 (expand-file-name
4684 (org-remove-double-quotes value))
4685 'noerror))
4686 (if (not ext-setup-or-nil)
4687 (setq ext-setup-or-nil setup-contents start 0)
4688 (setq ext-setup-or-nil
4689 (concat (substring ext-setup-or-nil 0 start)
4690 "\n" setup-contents "\n"
4691 (substring ext-setup-or-nil start)))))))
4692 ;; search for property blocks
4693 (goto-char (point-min))
4694 (while (re-search-forward org-block-regexp nil t)
4695 (when (equal "PROPERTY" (upcase (match-string 1)))
4696 (setq value (replace-regexp-in-string
4697 "[\n\r]" " " (match-string 4)))
4698 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4699 (setq props (org-update-property-plist (match-string 1 value)
4700 (match-string 2 value)
4701 props)))))))
4702 (org-set-local 'org-use-sub-superscripts scripts)
4703 (when cat
4704 (org-set-local 'org-category (intern cat))
4705 (push (cons "CATEGORY" cat) props))
4706 (when prio
4707 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4708 (setq prio (mapcar 'string-to-char prio))
4709 (org-set-local 'org-highest-priority (nth 0 prio))
4710 (org-set-local 'org-lowest-priority (nth 1 prio))
4711 (org-set-local 'org-default-priority (nth 2 prio)))
4712 (and props (org-set-local 'org-file-properties (nreverse props)))
4713 (and ftags (org-set-local 'org-file-tags
4714 (mapcar 'org-add-prop-inherited ftags)))
4715 (and drawers (org-set-local 'org-drawers drawers))
4716 (and arch (org-set-local 'org-archive-location arch))
4717 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4718 ;; Process the TODO keywords
4719 (unless kwds
4720 ;; Use the global values as if they had been given locally.
4721 (setq kwds (default-value 'org-todo-keywords))
4722 (if (stringp (car kwds))
4723 (setq kwds (list (cons org-todo-interpretation
4724 (default-value 'org-todo-keywords)))))
4725 (setq kwds (reverse kwds)))
4726 (setq kwds (nreverse kwds))
4727 (let (inter kws kw)
4728 (while (setq kws (pop kwds))
4729 (let ((kws (or
4730 (run-hook-with-args-until-success
4731 'org-todo-setup-filter-hook kws)
4732 kws)))
4733 (setq inter (pop kws) sep (member "|" kws)
4734 kws0 (delete "|" (copy-sequence kws))
4735 kwsa nil
4736 kws1 (mapcar
4737 (lambda (x)
4738 ;; 1 2
4739 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4740 (progn
4741 (setq kw (match-string 1 x)
4742 key (and (match-end 2) (match-string 2 x))
4743 log (org-extract-log-state-settings x))
4744 (push (cons kw (and key (string-to-char key))) kwsa)
4745 (and log (push log org-todo-log-states))
4747 (error "Invalid TODO keyword %s" x)))
4748 kws0)
4749 kwsa (if kwsa (append '((:startgroup))
4750 (nreverse kwsa)
4751 '((:endgroup))))
4752 hw (car kws1)
4753 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4754 tail (list inter hw (car dws) (org-last dws))))
4755 (add-to-list 'org-todo-heads hw 'append)
4756 (push kws1 org-todo-sets)
4757 (setq org-done-keywords (append org-done-keywords dws nil))
4758 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4759 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4760 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4761 (setq org-todo-sets (nreverse org-todo-sets)
4762 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4763 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4764 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4765 ;; Process the constants
4766 (when const
4767 (let (e cst)
4768 (while (setq e (pop const))
4769 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4770 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4771 (setq org-table-formula-constants-local cst)))
4773 ;; Process the tags.
4774 (when tags
4775 (let (e tgs)
4776 (while (setq e (pop tags))
4777 (cond
4778 ((equal e "{") (push '(:startgroup) tgs))
4779 ((equal e "}") (push '(:endgroup) tgs))
4780 ((equal e "\\n") (push '(:newline) tgs))
4781 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4782 (push (cons (match-string 1 e)
4783 (string-to-char (match-string 2 e)))
4784 tgs))
4785 (t (push (list e) tgs))))
4786 (org-set-local 'org-tag-alist nil)
4787 (while (setq e (pop tgs))
4788 (or (and (stringp (car e))
4789 (assoc (car e) org-tag-alist))
4790 (push e org-tag-alist)))))
4792 ;; Compute the regular expressions and other local variables.
4793 ;; Using `org-outline-regexp-bol' would complicate them much,
4794 ;; because of the fixed white space at the end of that string.
4795 (if (not org-done-keywords)
4796 (setq org-done-keywords (and org-todo-keywords-1
4797 (list (org-last org-todo-keywords-1)))))
4798 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4799 (length org-scheduled-string)
4800 (length org-clock-string)
4801 (length org-closed-string)))
4802 org-drawer-regexp
4803 (concat "^[ \t]*:\\("
4804 (mapconcat 'regexp-quote org-drawers "\\|")
4805 "\\):[ \t]*$")
4806 org-not-done-keywords
4807 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4808 org-todo-regexp
4809 (concat "\\("
4810 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4811 "\\)")
4812 org-not-done-regexp
4813 (concat "\\("
4814 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4815 "\\)")
4816 org-not-done-heading-regexp
4817 (format org-heading-keyword-regexp-format org-not-done-regexp)
4818 org-todo-line-regexp
4819 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4820 org-complex-heading-regexp
4821 (concat "^\\(\\*+\\)"
4822 "\\(?: +" org-todo-regexp "\\)?"
4823 "\\(?: +\\(\\[#.\\]\\)\\)?"
4824 "\\(?: +\\(.*?\\)\\)?"
4825 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4826 "[ \t]*$")
4827 org-complex-heading-regexp-format
4828 (concat "^\\(\\*+\\)"
4829 "\\(?: +" org-todo-regexp "\\)?"
4830 "\\(?: +\\(\\[#.\\]\\)\\)?"
4831 "\\(?: +"
4832 ;; Stats cookies can be stuck to body.
4833 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4834 "\\(%s\\)"
4835 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4836 "\\)"
4837 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4838 "[ \t]*$")
4839 org-todo-line-tags-regexp
4840 (concat "^\\(\\*+\\)"
4841 "\\(?: +" org-todo-regexp "\\)?"
4842 "\\(?: +\\(.*?\\)\\)?"
4843 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4844 "[ \t]*$")
4845 org-deadline-regexp (concat "\\<" org-deadline-string)
4846 org-deadline-time-regexp
4847 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4848 org-deadline-line-regexp
4849 (concat "\\<\\(" org-deadline-string "\\).*")
4850 org-scheduled-regexp
4851 (concat "\\<" org-scheduled-string)
4852 org-scheduled-time-regexp
4853 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4854 org-closed-time-regexp
4855 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4856 org-keyword-time-regexp
4857 (concat "\\<\\(" org-scheduled-string
4858 "\\|" org-deadline-string
4859 "\\|" org-closed-string
4860 "\\|" org-clock-string "\\)"
4861 " *[[<]\\([^]>]+\\)[]>]")
4862 org-keyword-time-not-clock-regexp
4863 (concat "\\<\\(" org-scheduled-string
4864 "\\|" org-deadline-string
4865 "\\|" org-closed-string
4866 "\\)"
4867 " *[[<]\\([^]>]+\\)[]>]")
4868 org-maybe-keyword-time-regexp
4869 (concat "\\(\\<\\(" org-scheduled-string
4870 "\\|" org-deadline-string
4871 "\\|" org-closed-string
4872 "\\|" org-clock-string "\\)\\)?"
4873 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4874 org-all-time-keywords
4875 (mapcar (lambda (w) (substring w 0 -1))
4876 (list org-scheduled-string org-deadline-string
4877 org-clock-string org-closed-string))
4879 (org-compute-latex-and-specials-regexp)
4880 (org-set-font-lock-defaults))))
4882 (defun org-file-contents (file &optional noerror)
4883 "Return the contents of FILE, as a string."
4884 (if (or (not file)
4885 (not (file-readable-p file)))
4886 (if noerror
4887 (progn
4888 (message "Cannot read file \"%s\"" file)
4889 (ding) (sit-for 2)
4891 (error "Cannot read file \"%s\"" file))
4892 (with-temp-buffer
4893 (insert-file-contents file)
4894 (buffer-string))))
4896 (defun org-extract-log-state-settings (x)
4897 "Extract the log state setting from a TODO keyword string.
4898 This will extract info from a string like \"WAIT(w@/!)\"."
4899 (let (kw key log1 log2)
4900 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4901 (setq kw (match-string 1 x)
4902 key (and (match-end 2) (match-string 2 x))
4903 log1 (and (match-end 3) (match-string 3 x))
4904 log2 (and (match-end 4) (match-string 4 x)))
4905 (and (or log1 log2)
4906 (list kw
4907 (and log1 (if (equal log1 "!") 'time 'note))
4908 (and log2 (if (equal log2 "!") 'time 'note)))))))
4910 (defun org-remove-keyword-keys (list)
4911 "Remove a pair of parenthesis at the end of each string in LIST."
4912 (mapcar (lambda (x)
4913 (if (string-match "(.*)$" x)
4914 (substring x 0 (match-beginning 0))
4916 list))
4918 (defun org-assign-fast-keys (alist)
4919 "Assign fast keys to a keyword-key alist.
4920 Respect keys that are already there."
4921 (let (new e (alt ?0))
4922 (while (setq e (pop alist))
4923 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4924 (cdr e)) ;; Key already assigned.
4925 (push e new)
4926 (let ((clist (string-to-list (downcase (car e))))
4927 (used (append new alist)))
4928 (when (= (car clist) ?@)
4929 (pop clist))
4930 (while (and clist (rassoc (car clist) used))
4931 (pop clist))
4932 (unless clist
4933 (while (rassoc alt used)
4934 (incf alt)))
4935 (push (cons (car e) (or (car clist) alt)) new))))
4936 (nreverse new)))
4938 ;;; Some variables used in various places
4940 (defvar org-window-configuration nil
4941 "Used in various places to store a window configuration.")
4942 (defvar org-selected-window nil
4943 "Used in various places to store a window configuration.")
4944 (defvar org-finish-function nil
4945 "Function to be called when `C-c C-c' is used.
4946 This is for getting out of special buffers like remember.")
4949 ;; FIXME: Occasionally check by commenting these, to make sure
4950 ;; no other functions uses these, forgetting to let-bind them.
4951 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4952 (defvar org-last-state)
4953 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4955 ;; Defined somewhere in this file, but used before definition.
4956 (defvar org-entities) ;; defined in org-entities.el
4957 (defvar org-struct-menu)
4958 (defvar org-org-menu)
4959 (defvar org-tbl-menu)
4961 ;;;; Define the Org-mode
4963 ;; We use a before-change function to check if a table might need
4964 ;; an update.
4965 (defvar org-table-may-need-update t
4966 "Indicates that a table might need an update.
4967 This variable is set by `org-before-change-function'.
4968 `org-table-align' sets it back to nil.")
4969 (defun org-before-change-function (beg end)
4970 "Every change indicates that a table might need an update."
4971 (setq org-table-may-need-update t))
4972 (defvar org-mode-map)
4973 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4974 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4975 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4976 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4977 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4978 (defvar org-table-buffer-is-an nil)
4980 (defvar bidi-paragraph-direction)
4981 (defvar buffer-face-mode-face)
4983 (require 'outline)
4984 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4985 (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"))
4986 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4988 ;; Other stuff we need.
4989 (require 'time-date)
4990 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4991 (require 'easymenu)
4992 (require 'overlay)
4994 (require 'org-macs)
4995 (require 'org-entities)
4996 ;; (require 'org-compat) moved higher up in the file before it is first used
4997 (require 'org-faces)
4998 (require 'org-list)
4999 (require 'org-pcomplete)
5000 (require 'org-src)
5001 (require 'org-footnote)
5003 ;; babel
5004 (require 'ob)
5005 (require 'ob-table)
5006 (require 'ob-lob)
5007 (require 'ob-ref)
5008 (require 'ob-tangle)
5009 (require 'ob-comint)
5010 (require 'ob-keys)
5012 ;;;###autoload
5013 (define-derived-mode org-mode outline-mode "Org"
5014 "Outline-based notes management and organizer, alias
5015 \"Carsten's outline-mode for keeping track of everything.\"
5017 Org-mode develops organizational tasks around a NOTES file which
5018 contains information about projects as plain text. Org-mode is
5019 implemented on top of outline-mode, which is ideal to keep the content
5020 of large files well structured. It supports ToDo items, deadlines and
5021 time stamps, which magically appear in the diary listing of the Emacs
5022 calendar. Tables are easily created with a built-in table editor.
5023 Plain text URL-like links connect to websites, emails (VM), Usenet
5024 messages (Gnus), BBDB entries, and any files related to the project.
5025 For printing and sharing of notes, an Org-mode file (or a part of it)
5026 can be exported as a structured ASCII or HTML file.
5028 The following commands are available:
5030 \\{org-mode-map}"
5032 ;; Get rid of Outline menus, they are not needed
5033 ;; Need to do this here because define-derived-mode sets up
5034 ;; the keymap so late. Still, it is a waste to call this each time
5035 ;; we switch another buffer into org-mode.
5036 (if (featurep 'xemacs)
5037 (when (boundp 'outline-mode-menu-heading)
5038 ;; Assume this is Greg's port, it uses easymenu
5039 (easy-menu-remove outline-mode-menu-heading)
5040 (easy-menu-remove outline-mode-menu-show)
5041 (easy-menu-remove outline-mode-menu-hide))
5042 (define-key org-mode-map [menu-bar headings] 'undefined)
5043 (define-key org-mode-map [menu-bar hide] 'undefined)
5044 (define-key org-mode-map [menu-bar show] 'undefined))
5046 (org-load-modules-maybe)
5047 (easy-menu-add org-org-menu)
5048 (easy-menu-add org-tbl-menu)
5049 (org-install-agenda-files-menu)
5050 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5051 (add-to-invisibility-spec '(org-cwidth))
5052 (add-to-invisibility-spec '(org-hide-block . t))
5053 (when (featurep 'xemacs)
5054 (org-set-local 'line-move-ignore-invisible t))
5055 (org-set-local 'outline-regexp org-outline-regexp)
5056 (org-set-local 'outline-level 'org-outline-level)
5057 (setq bidi-paragraph-direction 'left-to-right)
5058 (when (and org-ellipsis
5059 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5060 (fboundp 'make-glyph-code))
5061 (unless org-display-table
5062 (setq org-display-table (make-display-table)))
5063 (set-display-table-slot
5064 org-display-table 4
5065 (vconcat (mapcar
5066 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5067 org-ellipsis)))
5068 (if (stringp org-ellipsis) org-ellipsis "..."))))
5069 (setq buffer-display-table org-display-table))
5070 (org-set-regexps-and-options)
5071 (when (and org-tag-faces (not org-tags-special-faces-re))
5072 ;; tag faces set outside customize.... force initialization.
5073 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5074 ;; Calc embedded
5075 (org-set-local 'calc-embedded-open-mode "# ")
5076 (modify-syntax-entry ?@ "w")
5077 (if org-startup-truncated (setq truncate-lines t))
5078 (org-set-local 'font-lock-unfontify-region-function
5079 'org-unfontify-region)
5080 ;; Activate before-change-function
5081 (org-set-local 'org-table-may-need-update t)
5082 (org-add-hook 'before-change-functions 'org-before-change-function nil
5083 'local)
5084 ;; Check for running clock before killing a buffer
5085 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5086 ;; Paragraphs and auto-filling
5087 (org-set-autofill-regexps)
5088 (org-set-local 'indent-line-function 'org-indent-line)
5089 (org-set-local 'indent-region-function 'org-indent-region)
5090 (org-update-radio-target-regexp)
5091 ;; Comments
5092 (org-set-local 'comment-use-syntax nil)
5093 (org-set-local 'comment-start "#")
5094 (org-set-local 'comment-start-skip "# ?")
5095 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
5096 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
5097 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region)
5098 ;; Beginning/end of defun
5099 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5100 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5101 ;; Next error for sparse trees
5102 (org-set-local 'next-error-function 'org-occur-next-match)
5103 ;; Make sure dependence stuff works reliably, even for users who set it
5104 ;; too late :-(
5105 (if org-enforce-todo-dependencies
5106 (add-hook 'org-blocker-hook
5107 'org-block-todo-from-children-or-siblings-or-parent)
5108 (remove-hook 'org-blocker-hook
5109 'org-block-todo-from-children-or-siblings-or-parent))
5110 (if org-enforce-todo-checkbox-dependencies
5111 (add-hook 'org-blocker-hook
5112 'org-block-todo-from-checkboxes)
5113 (remove-hook 'org-blocker-hook
5114 'org-block-todo-from-checkboxes))
5116 ;; Align options lines
5117 (org-set-local
5118 'align-mode-rules-list
5119 '((org-in-buffer-settings
5120 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5121 (modes . '(org-mode)))))
5123 ;; Imenu
5124 (org-set-local 'imenu-create-index-function
5125 'org-imenu-get-tree)
5127 ;; Make isearch reveal context
5128 (if (or (featurep 'xemacs)
5129 (not (boundp 'outline-isearch-open-invisible-function)))
5130 ;; Emacs 21 and XEmacs make use of the hook
5131 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5132 ;; Emacs 22 deals with this through a special variable
5133 (org-set-local 'outline-isearch-open-invisible-function
5134 (lambda (&rest ignore) (org-show-context 'isearch))))
5136 ;; Turn on org-beamer-mode?
5137 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5139 ;; Setup the pcomplete hooks
5140 (set (make-local-variable 'pcomplete-command-completion-function)
5141 'org-pcomplete-initial)
5142 (set (make-local-variable 'pcomplete-command-name-function)
5143 'org-command-at-point)
5144 (set (make-local-variable 'pcomplete-default-completion-function)
5145 'ignore)
5146 (set (make-local-variable 'pcomplete-parse-arguments-function)
5147 'org-parse-arguments)
5148 (set (make-local-variable 'pcomplete-termination-string) "")
5149 (when (>= emacs-major-version 23)
5150 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5152 ;; If empty file that did not turn on org-mode automatically, make it to.
5153 (if (and org-insert-mode-line-in-empty-file
5154 (org-called-interactively-p 'any)
5155 (= (point-min) (point-max)))
5156 (insert "# -*- mode: org -*-\n\n"))
5157 (unless org-inhibit-startup
5158 (when org-startup-align-all-tables
5159 (let ((bmp (buffer-modified-p)))
5160 (org-table-map-tables 'org-table-align 'quietly)
5161 (set-buffer-modified-p bmp)))
5162 (when org-startup-with-inline-images
5163 (org-display-inline-images))
5164 (when org-startup-indented
5165 (require 'org-indent)
5166 (org-indent-mode 1))
5167 (unless org-inhibit-startup-visibility-stuff
5168 (org-set-startup-visibility))))
5170 (when (fboundp 'abbrev-table-put)
5171 (abbrev-table-put org-mode-abbrev-table
5172 :parents (list text-mode-abbrev-table)))
5174 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5176 (defun org-current-time ()
5177 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5178 (if (> (car org-time-stamp-rounding-minutes) 1)
5179 (let ((r (car org-time-stamp-rounding-minutes))
5180 (time (decode-time)))
5181 (apply 'encode-time
5182 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5183 (nthcdr 2 time))))
5184 (current-time)))
5186 (defun org-today ()
5187 "Return today date, considering `org-extend-today-until'."
5188 (time-to-days
5189 (time-subtract (current-time)
5190 (list 0 (* 3600 org-extend-today-until) 0))))
5192 ;;;; Font-Lock stuff, including the activators
5194 (defvar org-mouse-map (make-sparse-keymap))
5195 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5196 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5197 (when org-mouse-1-follows-link
5198 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5199 (when org-tab-follows-link
5200 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5201 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5203 (require 'font-lock)
5205 (defconst org-non-link-chars "]\t\n\r<>")
5206 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5207 "shell" "elisp" "doi" "message"))
5208 (defvar org-link-types-re nil
5209 "Matches a link that has a url-like prefix like \"http:\"")
5210 (defvar org-link-re-with-space nil
5211 "Matches a link with spaces, optional angular brackets around it.")
5212 (defvar org-link-re-with-space2 nil
5213 "Matches a link with spaces, optional angular brackets around it.")
5214 (defvar org-link-re-with-space3 nil
5215 "Matches a link with spaces, only for internal part in bracket links.")
5216 (defvar org-angle-link-re nil
5217 "Matches link with angular brackets, spaces are allowed.")
5218 (defvar org-plain-link-re nil
5219 "Matches plain link, without spaces.")
5220 (defvar org-bracket-link-regexp nil
5221 "Matches a link in double brackets.")
5222 (defvar org-bracket-link-analytic-regexp nil
5223 "Regular expression used to analyze links.
5224 Here is what the match groups contain after a match:
5225 1: http:
5226 2: http
5227 3: path
5228 4: [desc]
5229 5: desc")
5230 (defvar org-bracket-link-analytic-regexp++ nil
5231 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5232 (defvar org-any-link-re nil
5233 "Regular expression matching any link.")
5235 (defcustom org-match-sexp-depth 3
5236 "Number of stacked braces for sub/superscript matching.
5237 This has to be set before loading org.el to be effective."
5238 :group 'org-export-translation ; ??????????????????????????/
5239 :type 'integer)
5241 (defun org-create-multibrace-regexp (left right n)
5242 "Create a regular expression which will match a balanced sexp.
5243 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5244 as single character strings.
5245 The regexp returned will match the entire expression including the
5246 delimiters. It will also define a single group which contains the
5247 match except for the outermost delimiters. The maximum depth of
5248 stacked delimiters is N. Escaping delimiters is not possible."
5249 (let* ((nothing (concat "[^" left right "]*?"))
5250 (or "\\|")
5251 (re nothing)
5252 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5253 (while (> n 1)
5254 (setq n (1- n)
5255 re (concat re or next)
5256 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5257 (concat left "\\(" re "\\)" right)))
5259 (defvar org-match-substring-regexp
5260 (concat
5261 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5262 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5263 "\\|"
5264 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5265 "\\|"
5266 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5267 "The regular expression matching a sub- or superscript.")
5269 (defvar org-match-substring-with-braces-regexp
5270 (concat
5271 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5272 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5273 "\\)")
5274 "The regular expression matching a sub- or superscript, forcing braces.")
5276 (defun org-make-link-regexps ()
5277 "Update the link regular expressions.
5278 This should be called after the variable `org-link-types' has changed."
5279 (setq org-link-types-re
5280 (concat
5281 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5282 org-link-re-with-space
5283 (concat
5284 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5285 "\\([^" org-non-link-chars " ]"
5286 "[^" org-non-link-chars "]*"
5287 "[^" org-non-link-chars " ]\\)>?")
5288 org-link-re-with-space2
5289 (concat
5290 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5291 "\\([^" org-non-link-chars " ]"
5292 "[^\t\n\r]*"
5293 "[^" org-non-link-chars " ]\\)>?")
5294 org-link-re-with-space3
5295 (concat
5296 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5297 "\\([^" org-non-link-chars " ]"
5298 "[^\t\n\r]*\\)")
5299 org-angle-link-re
5300 (concat
5301 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5302 "\\([^" org-non-link-chars " ]"
5303 "[^" org-non-link-chars "]*"
5304 "\\)>")
5305 org-plain-link-re
5306 (concat
5307 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5308 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5309 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5310 org-bracket-link-regexp
5311 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5312 org-bracket-link-analytic-regexp
5313 (concat
5314 "\\[\\["
5315 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5316 "\\([^]]+\\)"
5317 "\\]"
5318 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5319 "\\]")
5320 org-bracket-link-analytic-regexp++
5321 (concat
5322 "\\[\\["
5323 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5324 "\\([^]]+\\)"
5325 "\\]"
5326 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5327 "\\]")
5328 org-any-link-re
5329 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5330 org-angle-link-re "\\)\\|\\("
5331 org-plain-link-re "\\)")))
5333 (org-make-link-regexps)
5335 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5336 "Regular expression for fast time stamp matching.")
5337 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5338 "Regular expression for fast time stamp matching.")
5339 (defconst org-ts-regexp0
5340 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5341 "Regular expression matching time strings for analysis.
5342 This one does not require the space after the date, so it can be used
5343 on a string that terminates immediately after the date.")
5344 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5345 "Regular expression matching time strings for analysis.")
5346 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5347 "Regular expression matching time stamps, with groups.")
5348 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5349 "Regular expression matching time stamps (also [..]), with groups.")
5350 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5351 "Regular expression matching a time stamp range.")
5352 (defconst org-tr-regexp-both
5353 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5354 "Regular expression matching a time stamp range.")
5355 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5356 org-ts-regexp "\\)?")
5357 "Regular expression matching a time stamp or time stamp range.")
5358 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5359 org-ts-regexp-both "\\)?")
5360 "Regular expression matching a time stamp or time stamp range.
5361 The time stamps may be either active or inactive.")
5363 (defvar org-emph-face nil)
5365 (defun org-do-emphasis-faces (limit)
5366 "Run through the buffer and add overlays to emphasized strings."
5367 (let (rtn a)
5368 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5369 (if (not (= (char-after (match-beginning 3))
5370 (char-after (match-beginning 4))))
5371 (progn
5372 (setq rtn t)
5373 (setq a (assoc (match-string 3) org-emphasis-alist))
5374 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5375 'face
5376 (nth 1 a))
5377 (and (nth 4 a)
5378 (org-remove-flyspell-overlays-in
5379 (match-beginning 0) (match-end 0)))
5380 (add-text-properties (match-beginning 2) (match-end 2)
5381 '(font-lock-multiline t org-emphasis t))
5382 (when org-hide-emphasis-markers
5383 (add-text-properties (match-end 4) (match-beginning 5)
5384 '(invisible org-link))
5385 (add-text-properties (match-beginning 3) (match-end 3)
5386 '(invisible org-link)))))
5387 (backward-char 1))
5388 rtn))
5390 (defun org-emphasize (&optional char)
5391 "Insert or change an emphasis, i.e. a font like bold or italic.
5392 If there is an active region, change that region to a new emphasis.
5393 If there is no region, just insert the marker characters and position
5394 the cursor between them.
5395 CHAR should be either the marker character, or the first character of the
5396 HTML tag associated with that emphasis. If CHAR is a space, the means
5397 to remove the emphasis of the selected region.
5398 If char is not given (for example in an interactive call) it
5399 will be prompted for."
5400 (interactive)
5401 (let ((eal org-emphasis-alist) e det
5402 (erc org-emphasis-regexp-components)
5403 (prompt "")
5404 (string "") beg end move tag c s)
5405 (if (org-region-active-p)
5406 (setq beg (region-beginning) end (region-end)
5407 string (buffer-substring beg end))
5408 (setq move t))
5410 (while (setq e (pop eal))
5411 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5412 c (aref tag 0))
5413 (push (cons c (string-to-char (car e))) det)
5414 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5415 (substring tag 1)))))
5416 (setq det (nreverse det))
5417 (unless char
5418 (message "%s" (concat "Emphasis marker or tag:" prompt))
5419 (setq char (read-char-exclusive)))
5420 (setq char (or (cdr (assoc char det)) char))
5421 (if (equal char ?\ )
5422 (setq s "" move nil)
5423 (unless (assoc (char-to-string char) org-emphasis-alist)
5424 (error "No such emphasis marker: \"%c\"" char))
5425 (setq s (char-to-string char)))
5426 (while (and (> (length string) 1)
5427 (equal (substring string 0 1) (substring string -1))
5428 (assoc (substring string 0 1) org-emphasis-alist))
5429 (setq string (substring string 1 -1)))
5430 (setq string (concat s string s))
5431 (if beg (delete-region beg end))
5432 (unless (or (bolp)
5433 (string-match (concat "[" (nth 0 erc) "\n]")
5434 (char-to-string (char-before (point)))))
5435 (insert " "))
5436 (unless (or (eobp)
5437 (string-match (concat "[" (nth 1 erc) "\n]")
5438 (char-to-string (char-after (point)))))
5439 (insert " ") (backward-char 1))
5440 (insert string)
5441 (and move (backward-char 1))))
5443 (defconst org-nonsticky-props
5444 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5446 (defsubst org-rear-nonsticky-at (pos)
5447 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5449 (defun org-activate-plain-links (limit)
5450 "Run through the buffer and add overlays to links."
5451 (catch 'exit
5452 (let (f)
5453 (if (re-search-forward org-plain-link-re limit t)
5454 (progn
5455 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5456 (setq f (get-text-property (match-beginning 0) 'face))
5457 (if (or (eq f 'org-tag)
5458 (and (listp f) (memq 'org-tag f)))
5460 (add-text-properties (match-beginning 0) (match-end 0)
5461 (list 'mouse-face 'highlight
5462 'face 'org-link
5463 'keymap org-mouse-map))
5464 (org-rear-nonsticky-at (match-end 0)))
5465 t)))))
5467 (defun org-activate-code (limit)
5468 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5469 (progn
5470 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5471 (remove-text-properties (match-beginning 0) (match-end 0)
5472 '(display t invisible t intangible t))
5473 t)))
5475 (defcustom org-src-fontify-natively nil
5476 "When non-nil, fontify code in code blocks."
5477 :type 'boolean
5478 :version "24.1"
5479 :group 'org-appearance
5480 :group 'org-babel)
5482 (defcustom org-src-prevent-auto-filling nil
5483 "When non-nil, prevent auto-filling in src blocks."
5484 :type 'boolean
5485 :version "24.1"
5486 :group 'org-appearance
5487 :group 'org-babel)
5489 (defcustom org-allow-promoting-top-level-subtree nil
5490 "When non-nil, allow promoting a top level subtree.
5491 The leading star of the top level headline will be replaced
5492 by a #."
5493 :type 'boolean
5494 :version "24.1"
5495 :group 'org-appearance)
5497 (defun org-fontify-meta-lines-and-blocks (limit)
5498 (condition-case nil
5499 (org-fontify-meta-lines-and-blocks-1 limit)
5500 (error (message "org-mode fontification error"))))
5502 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5503 "Fontify #+ lines and blocks, in the correct ways."
5504 (let ((case-fold-search t))
5505 (if (re-search-forward
5506 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5507 limit t)
5508 (let ((beg (match-beginning 0))
5509 (block-start (match-end 0))
5510 (block-end nil)
5511 (lang (match-string 7))
5512 (beg1 (line-beginning-position 2))
5513 (dc1 (downcase (match-string 2)))
5514 (dc3 (downcase (match-string 3)))
5515 end end1 quoting block-type ovl)
5516 (cond
5517 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5518 ;; a single line of backend-specific content
5519 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5520 (remove-text-properties (match-beginning 0) (match-end 0)
5521 '(display t invisible t intangible t))
5522 (add-text-properties (match-beginning 1) (match-end 3)
5523 '(font-lock-fontified t face org-meta-line))
5524 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5525 '(font-lock-fontified t face org-block))
5526 ; for backend-specific code
5528 ((and (match-end 4) (equal dc3 "+begin"))
5529 ;; Truly a block
5530 (setq block-type (downcase (match-string 5))
5531 quoting (member block-type org-protecting-blocks))
5532 (when (re-search-forward
5533 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5534 nil t) ;; on purpose, we look further than LIMIT
5535 (setq end (min (point-max) (match-end 0))
5536 end1 (min (point-max) (1- (match-beginning 0))))
5537 (setq block-end (match-beginning 0))
5538 (when quoting
5539 (remove-text-properties beg end
5540 '(display t invisible t intangible t)))
5541 (add-text-properties
5542 beg end
5543 '(font-lock-fontified t font-lock-multiline t))
5544 (add-text-properties beg beg1 '(face org-meta-line))
5545 (add-text-properties end1 (min (point-max) (1+ end))
5546 '(face org-meta-line)) ; for end_src
5547 (cond
5548 ((and lang (not (string= lang "")) org-src-fontify-natively)
5549 (org-src-font-lock-fontify-block lang block-start block-end)
5550 ;; remove old background overlays
5551 (mapc (lambda (ov)
5552 (if (eq (overlay-get ov 'face) 'org-block-background)
5553 (delete-overlay ov)))
5554 (overlays-at (/ (+ beg1 block-end) 2)))
5555 ;; add a background overlay
5556 (setq ovl (make-overlay beg1 block-end))
5557 (overlay-put ovl 'face 'org-block-background)
5558 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5559 (quoting
5560 (add-text-properties beg1 (min (point-max) (1+ end1))
5561 '(face org-block))) ; end of source block
5562 ((not org-fontify-quote-and-verse-blocks))
5563 ((string= block-type "quote")
5564 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5565 ((string= block-type "verse")
5566 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5567 (add-text-properties beg beg1 '(face org-block-begin-line))
5568 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5569 '(face org-block-end-line))
5571 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5572 (add-text-properties
5573 beg (match-end 3)
5574 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5575 '(font-lock-fontified t invisible t)
5576 '(font-lock-fontified t face org-document-info-keyword)))
5577 (add-text-properties
5578 (match-beginning 6) (match-end 6)
5579 (if (string-equal dc1 "+title:")
5580 '(font-lock-fontified t face org-document-title)
5581 '(font-lock-fontified t face org-document-info))))
5582 ((or (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5583 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5584 "+call:" "+header:" "+headers:" "+name:"))
5585 (and (match-end 4) (equal dc3 "+attr")))
5586 (add-text-properties
5587 beg (match-end 0)
5588 '(font-lock-fontified t face org-meta-line))
5590 ((member dc3 '(" " ""))
5591 (add-text-properties
5592 beg (match-end 0)
5593 '(font-lock-fontified t face font-lock-comment-face)))
5594 ((not (member (char-after beg) '(?\ ?\t)))
5595 ;; just any other in-buffer setting, but not indented
5596 (add-text-properties
5597 beg (match-end 0)
5598 '(font-lock-fontified t face org-meta-line))
5600 (t nil))))))
5602 (defun org-strip-protective-commas (beg end)
5603 "Strip protective commas between BEG and END in the current buffer."
5604 (interactive "r")
5605 (save-excursion
5606 (save-match-data
5607 (goto-char beg)
5608 (let ((front-line (save-excursion
5609 (re-search-forward
5610 "[^[:space:]]" end t)
5611 (goto-char (match-beginning 0))
5612 (current-column))))
5613 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5614 (goto-char (match-beginning 1))
5615 (when (= (current-column) front-line)
5616 (replace-match "" nil nil nil 1)))))))
5618 (defun org-activate-angle-links (limit)
5619 "Run through the buffer and add overlays to links."
5620 (if (re-search-forward org-angle-link-re limit t)
5621 (progn
5622 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5623 (add-text-properties (match-beginning 0) (match-end 0)
5624 (list 'mouse-face 'highlight
5625 'keymap org-mouse-map))
5626 (org-rear-nonsticky-at (match-end 0))
5627 t)))
5629 (defun org-activate-footnote-links (limit)
5630 "Run through the buffer and add overlays to footnotes."
5631 (let ((fn (org-footnote-next-reference-or-definition limit)))
5632 (when fn
5633 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5634 (org-remove-flyspell-overlays-in beg end)
5635 (add-text-properties beg end
5636 (list 'mouse-face 'highlight
5637 'keymap org-mouse-map
5638 'help-echo
5639 (if (= (point-at-bol) beg)
5640 "Footnote definition"
5641 "Footnote reference")
5642 'font-lock-fontified t
5643 'font-lock-multiline t
5644 'face 'org-footnote))))))
5646 (defun org-activate-bracket-links (limit)
5647 "Run through the buffer and add overlays to bracketed links."
5648 (if (re-search-forward org-bracket-link-regexp limit t)
5649 (let* ((help (concat "LINK: "
5650 (org-match-string-no-properties 1)))
5651 ;; FIXME: above we should remove the escapes.
5652 ;; but that requires another match, protecting match data,
5653 ;; a lot of overhead for font-lock.
5654 (ip (org-maybe-intangible
5655 (list 'invisible 'org-link
5656 'keymap org-mouse-map 'mouse-face 'highlight
5657 'font-lock-multiline t 'help-echo help)))
5658 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5659 'font-lock-multiline t 'help-echo help)))
5660 ;; We need to remove the invisible property here. Table narrowing
5661 ;; may have made some of this invisible.
5662 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5663 (remove-text-properties (match-beginning 0) (match-end 0)
5664 '(invisible nil))
5665 (if (match-end 3)
5666 (progn
5667 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5668 (org-rear-nonsticky-at (match-beginning 3))
5669 (add-text-properties (match-beginning 3) (match-end 3) vp)
5670 (org-rear-nonsticky-at (match-end 3))
5671 (add-text-properties (match-end 3) (match-end 0) ip)
5672 (org-rear-nonsticky-at (match-end 0)))
5673 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5674 (org-rear-nonsticky-at (match-beginning 1))
5675 (add-text-properties (match-beginning 1) (match-end 1) vp)
5676 (org-rear-nonsticky-at (match-end 1))
5677 (add-text-properties (match-end 1) (match-end 0) ip)
5678 (org-rear-nonsticky-at (match-end 0)))
5679 t)))
5681 (defun org-activate-dates (limit)
5682 "Run through the buffer and add overlays to dates."
5683 (if (re-search-forward org-tsr-regexp-both limit t)
5684 (progn
5685 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5686 (add-text-properties (match-beginning 0) (match-end 0)
5687 (list 'mouse-face 'highlight
5688 'keymap org-mouse-map))
5689 (org-rear-nonsticky-at (match-end 0))
5690 (when org-display-custom-times
5691 (if (match-end 3)
5692 (org-display-custom-time (match-beginning 3) (match-end 3)))
5693 (org-display-custom-time (match-beginning 1) (match-end 1)))
5694 t)))
5696 (defvar org-target-link-regexp nil
5697 "Regular expression matching radio targets in plain text.")
5698 (make-variable-buffer-local 'org-target-link-regexp)
5699 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5700 "Regular expression matching a link target.")
5701 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5702 "Regular expression matching a radio target.")
5703 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5704 "Regular expression matching any target.")
5706 (defun org-activate-target-links (limit)
5707 "Run through the buffer and add overlays to target matches."
5708 (when org-target-link-regexp
5709 (let ((case-fold-search t))
5710 (if (re-search-forward org-target-link-regexp limit t)
5711 (progn
5712 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5713 (add-text-properties (match-beginning 0) (match-end 0)
5714 (list 'mouse-face 'highlight
5715 'keymap org-mouse-map
5716 'help-echo "Radio target link"
5717 'org-linked-text t))
5718 (org-rear-nonsticky-at (match-end 0))
5719 t)))))
5721 (defun org-update-radio-target-regexp ()
5722 "Find all radio targets in this file and update the regular expression."
5723 (interactive)
5724 (when (memq 'radio org-activate-links)
5725 (setq org-target-link-regexp
5726 (org-make-target-link-regexp (org-all-targets 'radio)))
5727 (org-restart-font-lock)))
5729 (defun org-hide-wide-columns (limit)
5730 (let (s e)
5731 (setq s (text-property-any (point) (or limit (point-max))
5732 'org-cwidth t))
5733 (when s
5734 (setq e (next-single-property-change s 'org-cwidth))
5735 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5736 (goto-char e)
5737 t)))
5739 (defvar org-latex-and-specials-regexp nil
5740 "Regular expression for highlighting export special stuff.")
5741 (defvar org-match-substring-regexp)
5742 (defvar org-match-substring-with-braces-regexp)
5744 ;; This should be with the exporter code, but we also use if for font-locking
5745 (defconst org-export-html-special-string-regexps
5746 '(("\\\\-" . "&shy;")
5747 ("---\\([^-]\\)" . "&mdash;\\1")
5748 ("--\\([^-]\\)" . "&ndash;\\1")
5749 ("\\.\\.\\." . "&hellip;"))
5750 "Regular expressions for special string conversion.")
5753 (defun org-compute-latex-and-specials-regexp ()
5754 "Compute regular expression for stuff treated specially by exporters."
5755 (if (not org-highlight-latex-fragments-and-specials)
5756 (org-set-local 'org-latex-and-specials-regexp nil)
5757 (require 'org-exp)
5758 (let*
5759 ((matchers (plist-get org-format-latex-options :matchers))
5760 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5761 org-latex-regexps)))
5762 (org-export-allow-BIND nil)
5763 (options (org-combine-plists (org-default-export-plist)
5764 (org-infile-export-plist)))
5765 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5766 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5767 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5768 (org-export-html-expand (plist-get options :expand-quoted-html))
5769 (org-export-with-special-strings (plist-get options :special-strings))
5770 (re-sub
5771 (cond
5772 ((equal org-export-with-sub-superscripts '{})
5773 (list org-match-substring-with-braces-regexp))
5774 (org-export-with-sub-superscripts
5775 (list org-match-substring-regexp))
5776 (t nil)))
5777 (re-latex
5778 (if org-export-with-LaTeX-fragments
5779 (mapcar (lambda (x) (nth 1 x)) latexs)))
5780 (re-macros
5781 (if org-export-with-TeX-macros
5782 (list (concat "\\\\"
5783 (regexp-opt
5784 (append
5786 (delq nil
5787 (mapcar 'car-safe
5788 (append org-entities-user
5789 org-entities)))
5790 (if (boundp 'org-latex-entities)
5791 (mapcar (lambda (x)
5792 (or (car-safe x) x))
5793 org-latex-entities)
5794 nil))
5795 'words))) ; FIXME
5797 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5798 (re-special (if org-export-with-special-strings
5799 (mapcar (lambda (x) (car x))
5800 org-export-html-special-string-regexps)))
5801 (re-rest
5802 (delq nil
5803 (list
5804 (if org-export-html-expand "@<[^>\n]+>")
5805 ))))
5806 (org-set-local
5807 'org-latex-and-specials-regexp
5808 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5809 re-rest) "\\|")))))
5811 (defun org-do-latex-and-special-faces (limit)
5812 "Run through the buffer and add overlays to links."
5813 (when org-latex-and-specials-regexp
5814 (let (rtn d)
5815 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5816 limit t))
5817 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5818 'face))
5819 '(org-code org-verbatim underline)))
5820 (progn
5821 (setq rtn t
5822 d (cond ((member (char-after (1+ (match-beginning 0)))
5823 '(?_ ?^)) 1)
5824 (t 0)))
5825 (font-lock-prepend-text-property
5826 (+ d (match-beginning 0)) (match-end 0)
5827 'face 'org-latex-and-export-specials)
5828 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5829 '(font-lock-multiline t)))))
5830 rtn)))
5832 (defun org-restart-font-lock ()
5833 "Restart `font-lock-mode', to force refontification."
5834 (when (and (boundp 'font-lock-mode) font-lock-mode)
5835 (font-lock-mode -1)
5836 (font-lock-mode 1)))
5838 (defun org-all-targets (&optional radio)
5839 "Return a list of all targets in this file.
5840 With optional argument RADIO, only find radio targets."
5841 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5842 rtn)
5843 (save-excursion
5844 (goto-char (point-min))
5845 (while (re-search-forward re nil t)
5846 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5847 rtn)))
5849 (defun org-make-target-link-regexp (targets)
5850 "Make regular expression matching all strings in TARGETS.
5851 The regular expression finds the targets also if there is a line break
5852 between words."
5853 (and targets
5854 (concat
5855 "\\<\\("
5856 (mapconcat
5857 (lambda (x)
5858 (setq x (regexp-quote x))
5859 (while (string-match " +" x)
5860 (setq x (replace-match "\\s-+" t t x)))
5862 targets
5863 "\\|")
5864 "\\)\\>")))
5866 (defun org-activate-tags (limit)
5867 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5868 (progn
5869 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5870 (add-text-properties (match-beginning 1) (match-end 1)
5871 (list 'mouse-face 'highlight
5872 'keymap org-mouse-map))
5873 (org-rear-nonsticky-at (match-end 1))
5874 t)))
5876 (defun org-outline-level ()
5877 "Compute the outline level of the heading at point.
5878 This function assumes that the cursor is at the beginning of a line matched
5879 by `outline-regexp'. Otherwise it returns garbage.
5880 If this is called at a normal headline, the level is the number of stars.
5881 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5882 (save-excursion
5883 (looking-at org-outline-regexp)
5884 (1- (- (match-end 0) (match-beginning 0)))))
5886 (defvar org-font-lock-keywords nil)
5888 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5889 "Regular expression matching a property line.")
5891 (defvar org-font-lock-hook nil
5892 "Functions to be called for special font lock stuff.")
5894 (defvar org-font-lock-set-keywords-hook nil
5895 "Functions that can manipulate `org-font-lock-extra-keywords'.
5896 This is called after `org-font-lock-extra-keywords' is defined, but before
5897 it is installed to be used by font lock. This can be useful if something
5898 needs to be inserted at a specific position in the font-lock sequence.")
5900 (defun org-font-lock-hook (limit)
5901 (run-hook-with-args 'org-font-lock-hook limit))
5903 (defun org-set-font-lock-defaults ()
5904 (let* ((em org-fontify-emphasized-text)
5905 (lk org-activate-links)
5906 (org-font-lock-extra-keywords
5907 (list
5908 ;; Call the hook
5909 '(org-font-lock-hook)
5910 ;; Headlines
5911 `(,(if org-fontify-whole-heading-line
5912 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5913 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5914 (1 (org-get-level-face 1))
5915 (2 (org-get-level-face 2))
5916 (3 (org-get-level-face 3)))
5917 ;; Table lines
5918 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5919 (1 'org-table t))
5920 ;; Table internals
5921 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5922 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5923 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5924 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5925 ;; Drawers
5926 (list org-drawer-regexp '(0 'org-special-keyword t))
5927 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5928 ;; Properties
5929 (list org-property-re
5930 '(1 'org-special-keyword t)
5931 '(3 'org-property-value t))
5932 ;; Links
5933 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5934 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5935 (if (memq 'plain lk) '(org-activate-plain-links))
5936 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5937 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5938 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5939 (if (memq 'footnote lk) '(org-activate-footnote-links))
5940 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5941 '(org-hide-wide-columns (0 nil append))
5942 ;; TODO keyword
5943 (list (format org-heading-keyword-regexp-format
5944 org-todo-regexp)
5945 '(2 (org-get-todo-face 2) t))
5946 ;; DONE
5947 (if org-fontify-done-headline
5948 (list (format org-heading-keyword-regexp-format
5949 (concat
5950 "\\(?:"
5951 (mapconcat 'regexp-quote org-done-keywords "\\|")
5952 "\\)"))
5953 '(2 'org-headline-done t))
5954 nil)
5955 ;; Priorities
5956 '(org-font-lock-add-priority-faces)
5957 ;; Tags
5958 '(org-font-lock-add-tag-faces)
5959 ;; Special keywords
5960 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5961 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5962 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5963 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5964 ;; Emphasis
5965 (if em
5966 (if (featurep 'xemacs)
5967 '(org-do-emphasis-faces (0 nil append))
5968 '(org-do-emphasis-faces)))
5969 ;; Checkboxes
5970 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5971 1 'org-checkbox prepend)
5972 (if (cdr (assq 'checkbox org-list-automatic-rules))
5973 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5974 (0 (org-get-checkbox-statistics-face) t)))
5975 ;; Description list items
5976 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5977 1 'org-list-dt prepend)
5978 ;; ARCHIVEd headings
5979 (list (concat
5980 org-outline-regexp-bol
5981 "\\(.*:" org-archive-tag ":.*\\)")
5982 '(1 'org-archived prepend))
5983 ;; Specials
5984 '(org-do-latex-and-special-faces)
5985 '(org-fontify-entities)
5986 '(org-raise-scripts)
5987 ;; Code
5988 '(org-activate-code (1 'org-code t))
5989 ;; COMMENT
5990 (list (format org-heading-keyword-regexp-format
5991 (concat "\\("
5992 org-comment-string "\\|" org-quote-string
5993 "\\)"))
5994 '(2 'org-special-keyword t))
5995 '("^[ \t]*#.*" (0 'font-lock-comment-face t))
5996 ;; Blocks and meta lines
5997 '(org-fontify-meta-lines-and-blocks)
5999 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6000 (run-hooks 'org-font-lock-set-keywords-hook)
6001 ;; Now set the full font-lock-keywords
6002 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6003 (org-set-local 'font-lock-defaults
6004 '(org-font-lock-keywords t nil nil backward-paragraph))
6005 (kill-local-variable 'font-lock-keywords) nil))
6007 (defun org-toggle-pretty-entities ()
6008 "Toggle the composition display of entities as UTF8 characters."
6009 (interactive)
6010 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6011 (org-restart-font-lock)
6012 (if org-pretty-entities
6013 (message "Entities are displayed as UTF8 characters")
6014 (save-restriction
6015 (widen)
6016 (org-decompose-region (point-min) (point-max))
6017 (message "Entities are displayed plain"))))
6019 (defvar org-custom-properties-overlays nil
6020 "List of overlays used for custom properties.")
6021 (make-variable-buffer-local 'org-custom-properties-overlays)
6023 (defun org-toggle-custom-properties-visibility ()
6024 "Display or hide properties in `org-custom-properties'."
6025 (interactive)
6026 (if org-custom-properties-overlays
6027 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6028 (setq org-custom-properties-overlays nil))
6029 (unless (not org-custom-properties)
6030 (save-excursion
6031 (save-restriction
6032 (widen)
6033 (goto-char (point-min))
6034 (while (re-search-forward org-property-re nil t)
6035 (mapc (lambda(p)
6036 (when (equal p (substring (match-string 1) 1 -1))
6037 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6038 (overlay-put o 'invisible t)
6039 (overlay-put o 'org-custom-property t)
6040 (push o org-custom-properties-overlays))))
6041 org-custom-properties)))))))
6043 (defun org-fontify-entities (limit)
6044 "Find an entity to fontify."
6045 (let (ee)
6046 (when org-pretty-entities
6047 (catch 'match
6048 (while (re-search-forward
6049 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6050 limit t)
6051 (if (and (not (org-in-indented-comment-line))
6052 (setq ee (org-entity-get (match-string 1)))
6053 (= (length (nth 6 ee)) 1))
6054 (let*
6055 ((end (if (equal (match-string 2) "{}")
6056 (match-end 2)
6057 (match-end 1))))
6058 (add-text-properties
6059 (match-beginning 0) end
6060 (list 'font-lock-fontified t))
6061 (compose-region (match-beginning 0) end
6062 (nth 6 ee) nil)
6063 (backward-char 1)
6064 (throw 'match t))))
6065 nil))))
6067 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6068 "Fontify string S like in Org-mode."
6069 (with-temp-buffer
6070 (insert s)
6071 (let ((org-odd-levels-only odd-levels))
6072 (org-mode)
6073 (font-lock-fontify-buffer)
6074 (buffer-string))))
6076 (defvar org-m nil)
6077 (defvar org-l nil)
6078 (defvar org-f nil)
6079 (defun org-get-level-face (n)
6080 "Get the right face for match N in font-lock matching of headlines."
6081 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6082 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6083 (if org-cycle-level-faces
6084 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6085 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6086 (cond
6087 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6088 ((eq n 2) org-f)
6089 (t (if org-level-color-stars-only nil org-f))))
6092 (defun org-get-todo-face (kwd)
6093 "Get the right face for a TODO keyword KWD.
6094 If KWD is a number, get the corresponding match group."
6095 (if (numberp kwd) (setq kwd (match-string kwd)))
6096 (or (org-face-from-face-or-color
6097 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6098 (and (member kwd org-done-keywords) 'org-done)
6099 'org-todo))
6101 (defun org-face-from-face-or-color (context inherit face-or-color)
6102 "Create a face list that inherits INHERIT, but sets the foreground color.
6103 When FACE-OR-COLOR is not a string, just return it."
6104 (if (stringp face-or-color)
6105 (list :inherit inherit
6106 (cdr (assoc context org-faces-easy-properties))
6107 face-or-color)
6108 face-or-color))
6110 (defun org-font-lock-add-tag-faces (limit)
6111 "Add the special tag faces."
6112 (when (and org-tag-faces org-tags-special-faces-re)
6113 (while (re-search-forward org-tags-special-faces-re limit t)
6114 (add-text-properties (match-beginning 1) (match-end 1)
6115 (list 'face (org-get-tag-face 1)
6116 'font-lock-fontified t))
6117 (backward-char 1))))
6119 (defun org-font-lock-add-priority-faces (limit)
6120 "Add the special priority faces."
6121 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6122 (when (save-match-data (org-at-heading-p))
6123 (add-text-properties
6124 (match-beginning 0) (match-end 0)
6125 (list 'face (or (org-face-from-face-or-color
6126 'priority 'org-special-keyword
6127 (cdr (assoc (char-after (match-beginning 1))
6128 org-priority-faces)))
6129 'org-special-keyword)
6130 'font-lock-fontified t)))))
6132 (defun org-get-tag-face (kwd)
6133 "Get the right face for a TODO keyword KWD.
6134 If KWD is a number, get the corresponding match group."
6135 (if (numberp kwd) (setq kwd (match-string kwd)))
6136 (or (org-face-from-face-or-color
6137 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6138 'org-tag))
6140 (defun org-unfontify-region (beg end &optional maybe_loudly)
6141 "Remove fontification and activation overlays from links."
6142 (font-lock-default-unfontify-region beg end)
6143 (let* ((buffer-undo-list t)
6144 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6145 (inhibit-modification-hooks t)
6146 deactivate-mark buffer-file-name buffer-file-truename)
6147 (org-decompose-region beg end)
6148 (remove-text-properties beg end
6149 '(mouse-face t keymap t org-linked-text t
6150 invisible t intangible t
6151 org-no-flyspell t org-emphasis t))
6152 (org-remove-font-lock-display-properties beg end)))
6154 (defconst org-script-display '(((raise -0.3) (height 0.7))
6155 ((raise 0.3) (height 0.7))
6156 ((raise -0.5))
6157 ((raise 0.5)))
6158 "Display properties for showing superscripts and subscripts.")
6160 (defun org-remove-font-lock-display-properties (beg end)
6161 "Remove specific display properties that have been added by font lock.
6162 The will remove the raise properties that are used to show superscripts
6163 and subscripts."
6164 (let (next prop)
6165 (while (< beg end)
6166 (setq next (next-single-property-change beg 'display nil end)
6167 prop (get-text-property beg 'display))
6168 (if (member prop org-script-display)
6169 (put-text-property beg next 'display nil))
6170 (setq beg next))))
6172 (defun org-raise-scripts (limit)
6173 "Add raise properties to sub/superscripts."
6174 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6175 (if (re-search-forward
6176 (if (eq org-use-sub-superscripts t)
6177 org-match-substring-regexp
6178 org-match-substring-with-braces-regexp)
6179 limit t)
6180 (let* ((pos (point)) table-p comment-p
6181 (mpos (match-beginning 3))
6182 (emph-p (get-text-property mpos 'org-emphasis))
6183 (link-p (get-text-property mpos 'mouse-face))
6184 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6185 (goto-char (point-at-bol))
6186 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6187 comment-p (org-looking-at-p "[ \t]*#"))
6188 (goto-char pos)
6189 ;; FIXME: Should we go back one character here, for a_b^c
6190 ;; (goto-char (1- pos)) ;????????????????????
6191 (if (or comment-p emph-p link-p keyw-p)
6193 (put-text-property (match-beginning 3) (match-end 0)
6194 'display
6195 (if (equal (char-after (match-beginning 2)) ?^)
6196 (nth (if table-p 3 1) org-script-display)
6197 (nth (if table-p 2 0) org-script-display)))
6198 (add-text-properties (match-beginning 2) (match-end 2)
6199 (list 'invisible t
6200 'org-dwidth t 'org-dwidth-n 1))
6201 (if (and (eq (char-after (match-beginning 3)) ?{)
6202 (eq (char-before (match-end 3)) ?}))
6203 (progn
6204 (add-text-properties
6205 (match-beginning 3) (1+ (match-beginning 3))
6206 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6207 (add-text-properties
6208 (1- (match-end 3)) (match-end 3)
6209 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6210 t)))))
6212 ;;;; Visibility cycling, including org-goto and indirect buffer
6214 ;;; Cycling
6216 (defvar org-cycle-global-status nil)
6217 (make-variable-buffer-local 'org-cycle-global-status)
6218 (defvar org-cycle-subtree-status nil)
6219 (make-variable-buffer-local 'org-cycle-subtree-status)
6221 ;;;###autoload
6223 (defvar org-inlinetask-min-level)
6225 (defun org-cycle (&optional arg)
6226 "TAB-action and visibility cycling for Org-mode.
6228 This is the command invoked in Org-mode by the TAB key. Its main purpose
6229 is outline visibility cycling, but it also invokes other actions
6230 in special contexts.
6232 - When this function is called with a prefix argument, rotate the entire
6233 buffer through 3 states (global cycling)
6234 1. OVERVIEW: Show only top-level headlines.
6235 2. CONTENTS: Show all headlines of all levels, but no body text.
6236 3. SHOW ALL: Show everything.
6237 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6238 determined by the variable `org-startup-folded', and by any VISIBILITY
6239 properties in the buffer.
6240 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6241 including any drawers.
6243 - When inside a table, re-align the table and move to the next field.
6245 - When point is at the beginning of a headline, rotate the subtree started
6246 by this line through 3 different states (local cycling)
6247 1. FOLDED: Only the main headline is shown.
6248 2. CHILDREN: The main headline and the direct children are shown.
6249 From this state, you can move to one of the children
6250 and zoom in further.
6251 3. SUBTREE: Show the entire subtree, including body text.
6252 If there is no subtree, switch directly from CHILDREN to FOLDED.
6254 - When point is at the beginning of an empty headline and the variable
6255 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6256 of the headline by demoting and promoting it to likely levels. This
6257 speeds up creation document structure by pressing TAB once or several
6258 times right after creating a new headline.
6260 - When there is a numeric prefix, go up to a heading with level ARG, do
6261 a `show-subtree' and return to the previous cursor position. If ARG
6262 is negative, go up that many levels.
6264 - When point is not at the beginning of a headline, execute the global
6265 binding for TAB, which is re-indenting the line. See the option
6266 `org-cycle-emulate-tab' for details.
6268 - Special case: if point is at the beginning of the buffer and there is
6269 no headline in line 1, this function will act as if called with prefix arg
6270 (C-u TAB, same as S-TAB) also when called without prefix arg.
6271 But only if also the variable `org-cycle-global-at-bob' is t."
6272 (interactive "P")
6273 (org-load-modules-maybe)
6274 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6275 (and org-cycle-level-after-item/entry-creation
6276 (or (org-cycle-level)
6277 (org-cycle-item-indentation))))
6278 (let* ((limit-level
6279 (or org-cycle-max-level
6280 (and (boundp 'org-inlinetask-min-level)
6281 org-inlinetask-min-level
6282 (1- org-inlinetask-min-level))))
6283 (nstars (and limit-level
6284 (if org-odd-levels-only
6285 (and limit-level (1- (* limit-level 2)))
6286 limit-level)))
6287 (org-outline-regexp
6288 (if (not (derived-mode-p 'org-mode))
6289 outline-regexp
6290 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6291 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6292 (not (looking-at org-outline-regexp))))
6293 (org-cycle-hook
6294 (if bob-special
6295 (delq 'org-optimize-window-after-visibility-change
6296 (copy-sequence org-cycle-hook))
6297 org-cycle-hook))
6298 (pos (point)))
6300 (if (or bob-special (equal arg '(4)))
6301 ;; special case: use global cycling
6302 (setq arg t))
6304 (cond
6306 ((equal arg '(16))
6307 (setq last-command 'dummy)
6308 (org-set-startup-visibility)
6309 (message "Startup visibility, plus VISIBILITY properties"))
6311 ((equal arg '(64))
6312 (show-all)
6313 (message "Entire buffer visible, including drawers"))
6315 ;; Table: enter it or move to the next field.
6316 ((org-at-table-p 'any)
6317 (if (org-at-table.el-p)
6318 (message "Use C-c ' to edit table.el tables")
6319 (if arg (org-table-edit-field t)
6320 (org-table-justify-field-maybe)
6321 (call-interactively 'org-table-next-field))))
6323 ((run-hook-with-args-until-success
6324 'org-tab-after-check-for-table-hook))
6326 ;; Global cycling: delegate to `org-cycle-internal-global'.
6327 ((eq arg t) (org-cycle-internal-global))
6329 ;; Drawers: delegate to `org-flag-drawer'.
6330 ((and org-drawers org-drawer-regexp
6331 (save-excursion
6332 (beginning-of-line 1)
6333 (looking-at org-drawer-regexp)))
6334 (org-flag-drawer ; toggle block visibility
6335 (not (get-char-property (match-end 0) 'invisible))))
6337 ;; Show-subtree, ARG levels up from here.
6338 ((integerp arg)
6339 (save-excursion
6340 (org-back-to-heading)
6341 (outline-up-heading (if (< arg 0) (- arg)
6342 (- (funcall outline-level) arg)))
6343 (org-show-subtree)))
6345 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6346 ((and (featurep 'org-inlinetask)
6347 (org-inlinetask-at-task-p)
6348 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6349 (org-inlinetask-toggle-visibility))
6351 ((org-try-cdlatex-tab))
6353 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6354 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6355 (save-excursion (beginning-of-line 1)
6356 (looking-at org-outline-regexp)))
6357 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6358 (org-cycle-internal-local))
6360 ;; From there: TAB emulation and template completion.
6361 (buffer-read-only (org-back-to-heading))
6363 ((run-hook-with-args-until-success
6364 'org-tab-after-check-for-cycling-hook))
6366 ((org-try-structure-completion))
6368 ((run-hook-with-args-until-success
6369 'org-tab-before-tab-emulation-hook))
6371 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6372 (or (not (bolp))
6373 (not (looking-at org-outline-regexp))))
6374 (call-interactively (global-key-binding "\t")))
6376 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6377 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6378 (or (and (eq org-cycle-emulate-tab 'white)
6379 (= (match-end 0) (point-at-eol)))
6380 (and (eq org-cycle-emulate-tab 'whitestart)
6381 (>= (match-end 0) pos))))
6383 (eq org-cycle-emulate-tab t))
6384 (call-interactively (global-key-binding "\t")))
6386 (t (save-excursion
6387 (org-back-to-heading)
6388 (org-cycle)))))))
6390 (defun org-cycle-internal-global ()
6391 "Do the global cycling action."
6392 ;; Hack to avoid display of messages for .org attachments in Gnus
6393 (let ((ga (string-match "\\*fontification" (buffer-name))))
6394 (cond
6395 ((and (eq last-command this-command)
6396 (eq org-cycle-global-status 'overview))
6397 ;; We just created the overview - now do table of contents
6398 ;; This can be slow in very large buffers, so indicate action
6399 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6400 (unless ga (message "CONTENTS..."))
6401 (org-content)
6402 (unless ga (message "CONTENTS...done"))
6403 (setq org-cycle-global-status 'contents)
6404 (run-hook-with-args 'org-cycle-hook 'contents))
6406 ((and (eq last-command this-command)
6407 (eq org-cycle-global-status 'contents))
6408 ;; We just showed the table of contents - now show everything
6409 (run-hook-with-args 'org-pre-cycle-hook 'all)
6410 (show-all)
6411 (unless ga (message "SHOW ALL"))
6412 (setq org-cycle-global-status 'all)
6413 (run-hook-with-args 'org-cycle-hook 'all))
6416 ;; Default action: go to overview
6417 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6418 (org-overview)
6419 (unless ga (message "OVERVIEW"))
6420 (setq org-cycle-global-status 'overview)
6421 (run-hook-with-args 'org-cycle-hook 'overview)))))
6423 (defun org-cycle-internal-local ()
6424 "Do the local cycling action."
6425 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6426 ;; First, determine end of headline (EOH), end of subtree or item
6427 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6428 (save-excursion
6429 (if (org-at-item-p)
6430 (progn
6431 (beginning-of-line)
6432 (setq struct (org-list-struct))
6433 (setq eoh (point-at-eol))
6434 (setq eos (org-list-get-item-end-before-blank (point) struct))
6435 (setq has-children (org-list-has-child-p (point) struct)))
6436 (org-back-to-heading)
6437 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6438 (setq eos (save-excursion
6439 (org-end-of-subtree t)
6440 (unless (eobp)
6441 (skip-chars-forward " \t\n"))
6442 (if (eobp) (point) (1- (point)))))
6443 (setq has-children
6444 (or (save-excursion
6445 (let ((level (funcall outline-level)))
6446 (outline-next-heading)
6447 (and (org-at-heading-p t)
6448 (> (funcall outline-level) level))))
6449 (save-excursion
6450 (org-list-search-forward (org-item-beginning-re) eos t)))))
6451 ;; Determine end invisible part of buffer (EOL)
6452 (beginning-of-line 2)
6453 ;; XEmacs doesn't have `next-single-char-property-change'
6454 (if (featurep 'xemacs)
6455 (while (and (not (eobp)) ;; this is like `next-line'
6456 (get-char-property (1- (point)) 'invisible))
6457 (beginning-of-line 2))
6458 (while (and (not (eobp)) ;; this is like `next-line'
6459 (get-char-property (1- (point)) 'invisible))
6460 (goto-char (next-single-char-property-change (point) 'invisible))
6461 (and (eolp) (beginning-of-line 2))))
6462 (setq eol (point)))
6463 ;; Find out what to do next and set `this-command'
6464 (cond
6465 ((= eos eoh)
6466 ;; Nothing is hidden behind this heading
6467 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6468 (message "EMPTY ENTRY")
6469 (setq org-cycle-subtree-status nil)
6470 (save-excursion
6471 (goto-char eos)
6472 (outline-next-heading)
6473 (if (outline-invisible-p) (org-flag-heading nil))))
6474 ((and (or (>= eol eos)
6475 (not (string-match "\\S-" (buffer-substring eol eos))))
6476 (or has-children
6477 (not (setq children-skipped
6478 org-cycle-skip-children-state-if-no-children))))
6479 ;; Entire subtree is hidden in one line: children view
6480 (run-hook-with-args 'org-pre-cycle-hook 'children)
6481 (if (org-at-item-p)
6482 (org-list-set-item-visibility (point-at-bol) struct 'children)
6483 (org-show-entry)
6484 (org-with-limited-levels (show-children))
6485 ;; FIXME: This slows down the func way too much.
6486 ;; How keep drawers hidden in subtree anyway?
6487 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6488 ;; (org-cycle-hide-drawers 'subtree))
6490 ;; Fold every list in subtree to top-level items.
6491 (when (eq org-cycle-include-plain-lists 'integrate)
6492 (save-excursion
6493 (org-back-to-heading)
6494 (while (org-list-search-forward (org-item-beginning-re) eos t)
6495 (beginning-of-line 1)
6496 (let* ((struct (org-list-struct))
6497 (prevs (org-list-prevs-alist struct))
6498 (end (org-list-get-bottom-point struct)))
6499 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6500 (org-list-get-all-items (point) struct prevs))
6501 (goto-char end))))))
6502 (message "CHILDREN")
6503 (save-excursion
6504 (goto-char eos)
6505 (outline-next-heading)
6506 (if (outline-invisible-p) (org-flag-heading nil)))
6507 (setq org-cycle-subtree-status 'children)
6508 (run-hook-with-args 'org-cycle-hook 'children))
6509 ((or children-skipped
6510 (and (eq last-command this-command)
6511 (eq org-cycle-subtree-status 'children)))
6512 ;; We just showed the children, or no children are there,
6513 ;; now show everything.
6514 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6515 (outline-flag-region eoh eos nil)
6516 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6517 (setq org-cycle-subtree-status 'subtree)
6518 (run-hook-with-args 'org-cycle-hook 'subtree))
6520 ;; Default action: hide the subtree.
6521 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6522 (outline-flag-region eoh eos t)
6523 (message "FOLDED")
6524 (setq org-cycle-subtree-status 'folded)
6525 (run-hook-with-args 'org-cycle-hook 'folded)))))
6527 ;;;###autoload
6528 (defun org-global-cycle (&optional arg)
6529 "Cycle the global visibility. For details see `org-cycle'.
6530 With \\[universal-argument] prefix arg, switch to startup visibility.
6531 With a numeric prefix, show all headlines up to that level."
6532 (interactive "P")
6533 (let ((org-cycle-include-plain-lists
6534 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6535 (cond
6536 ((integerp arg)
6537 (show-all)
6538 (hide-sublevels arg)
6539 (setq org-cycle-global-status 'contents))
6540 ((equal arg '(4))
6541 (org-set-startup-visibility)
6542 (message "Startup visibility, plus VISIBILITY properties."))
6544 (org-cycle '(4))))))
6546 (defun org-set-startup-visibility ()
6547 "Set the visibility required by startup options and properties."
6548 (cond
6549 ((eq org-startup-folded t)
6550 (org-cycle '(4)))
6551 ((eq org-startup-folded 'content)
6552 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6553 (org-cycle '(4)) (org-cycle '(4)))))
6554 (unless (eq org-startup-folded 'showeverything)
6555 (if org-hide-block-startup (org-hide-block-all))
6556 (org-set-visibility-according-to-property 'no-cleanup)
6557 (org-cycle-hide-archived-subtrees 'all)
6558 (org-cycle-hide-drawers 'all)
6559 (org-cycle-show-empty-lines t)))
6561 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6562 "Switch subtree visibilities according to :VISIBILITY: property."
6563 (interactive)
6564 (let (org-show-entry-below state)
6565 (save-excursion
6566 (goto-char (point-min))
6567 (while (re-search-forward
6568 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6569 nil t)
6570 (setq state (match-string 1))
6571 (save-excursion
6572 (org-back-to-heading t)
6573 (hide-subtree)
6574 (org-reveal)
6575 (cond
6576 ((equal state '("fold" "folded"))
6577 (hide-subtree))
6578 ((equal state "children")
6579 (org-show-hidden-entry)
6580 (show-children))
6581 ((equal state "content")
6582 (save-excursion
6583 (save-restriction
6584 (org-narrow-to-subtree)
6585 (org-content))))
6586 ((member state '("all" "showall"))
6587 (show-subtree)))))
6588 (unless no-cleanup
6589 (org-cycle-hide-archived-subtrees 'all)
6590 (org-cycle-hide-drawers 'all)
6591 (org-cycle-show-empty-lines 'all)))))
6593 ;; This function uses outline-regexp instead of the more fundamental
6594 ;; org-outline-regexp so that org-cycle-global works outside of Org
6595 ;; buffers, where outline-regexp is needed.
6596 (defun org-overview ()
6597 "Switch to overview mode, showing only top-level headlines.
6598 Really, this shows all headlines with level equal or greater than the level
6599 of the first headline in the buffer. This is important, because if the
6600 first headline is not level one, then (hide-sublevels 1) gives confusing
6601 results."
6602 (interactive)
6603 (let ((level (save-excursion
6604 (goto-char (point-min))
6605 (if (re-search-forward (concat "^" outline-regexp) nil t)
6606 (progn
6607 (goto-char (match-beginning 0))
6608 (funcall outline-level))))))
6609 (and level (hide-sublevels level))))
6611 (defun org-content (&optional arg)
6612 "Show all headlines in the buffer, like a table of contents.
6613 With numerical argument N, show content up to level N."
6614 (interactive "P")
6615 (save-excursion
6616 ;; Visit all headings and show their offspring
6617 (and (integerp arg) (org-overview))
6618 (goto-char (point-max))
6619 (catch 'exit
6620 (while (and (progn (condition-case nil
6621 (outline-previous-visible-heading 1)
6622 (error (goto-char (point-min))))
6624 (looking-at org-outline-regexp))
6625 (if (integerp arg)
6626 (show-children (1- arg))
6627 (show-branches))
6628 (if (bobp) (throw 'exit nil))))))
6631 (defun org-optimize-window-after-visibility-change (state)
6632 "Adjust the window after a change in outline visibility.
6633 This function is the default value of the hook `org-cycle-hook'."
6634 (when (get-buffer-window (current-buffer))
6635 (cond
6636 ((eq state 'content) nil)
6637 ((eq state 'all) nil)
6638 ((eq state 'folded) nil)
6639 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6640 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6642 (defun org-remove-empty-overlays-at (pos)
6643 "Remove outline overlays that do not contain non-white stuff."
6644 (mapc
6645 (lambda (o)
6646 (and (eq 'outline (overlay-get o 'invisible))
6647 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6648 (overlay-end o))))
6649 (delete-overlay o)))
6650 (overlays-at pos)))
6652 (defun org-clean-visibility-after-subtree-move ()
6653 "Fix visibility issues after moving a subtree."
6654 ;; First, find a reasonable region to look at:
6655 ;; Start two siblings above, end three below
6656 (let* ((beg (save-excursion
6657 (and (org-get-last-sibling)
6658 (org-get-last-sibling))
6659 (point)))
6660 (end (save-excursion
6661 (and (org-get-next-sibling)
6662 (org-get-next-sibling)
6663 (org-get-next-sibling))
6664 (if (org-at-heading-p)
6665 (point-at-eol)
6666 (point))))
6667 (level (looking-at "\\*+"))
6668 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6669 (save-excursion
6670 (save-restriction
6671 (narrow-to-region beg end)
6672 (when re
6673 ;; Properly fold already folded siblings
6674 (goto-char (point-min))
6675 (while (re-search-forward re nil t)
6676 (if (and (not (outline-invisible-p))
6677 (save-excursion
6678 (goto-char (point-at-eol)) (outline-invisible-p)))
6679 (hide-entry))))
6680 (org-cycle-show-empty-lines 'overview)
6681 (org-cycle-hide-drawers 'overview)))))
6683 (defun org-cycle-show-empty-lines (state)
6684 "Show empty lines above all visible headlines.
6685 The region to be covered depends on STATE when called through
6686 `org-cycle-hook'. Lisp program can use t for STATE to get the
6687 entire buffer covered. Note that an empty line is only shown if there
6688 are at least `org-cycle-separator-lines' empty lines before the headline."
6689 (when (not (= org-cycle-separator-lines 0))
6690 (save-excursion
6691 (let* ((n (abs org-cycle-separator-lines))
6692 (re (cond
6693 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6694 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6695 (t (let ((ns (number-to-string (- n 2))))
6696 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6697 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6698 beg end b e)
6699 (cond
6700 ((memq state '(overview contents t))
6701 (setq beg (point-min) end (point-max)))
6702 ((memq state '(children folded))
6703 (setq beg (point) end (progn (org-end-of-subtree t t)
6704 (beginning-of-line 2)
6705 (point)))))
6706 (when beg
6707 (goto-char beg)
6708 (while (re-search-forward re end t)
6709 (unless (get-char-property (match-end 1) 'invisible)
6710 (setq e (match-end 1))
6711 (if (< org-cycle-separator-lines 0)
6712 (setq b (save-excursion
6713 (goto-char (match-beginning 0))
6714 (org-back-over-empty-lines)
6715 (if (save-excursion
6716 (goto-char (max (point-min) (1- (point))))
6717 (org-at-heading-p))
6718 (1- (point))
6719 (point))))
6720 (setq b (match-beginning 1)))
6721 (outline-flag-region b e nil)))))))
6722 ;; Never hide empty lines at the end of the file.
6723 (save-excursion
6724 (goto-char (point-max))
6725 (outline-previous-heading)
6726 (outline-end-of-heading)
6727 (if (and (looking-at "[ \t\n]+")
6728 (= (match-end 0) (point-max)))
6729 (outline-flag-region (point) (match-end 0) nil))))
6731 (defun org-show-empty-lines-in-parent ()
6732 "Move to the parent and re-show empty lines before visible headlines."
6733 (save-excursion
6734 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6735 (org-cycle-show-empty-lines context))))
6737 (defun org-files-list ()
6738 "Return `org-agenda-files' list, plus all open org-mode files.
6739 This is useful for operations that need to scan all of a user's
6740 open and agenda-wise Org files."
6741 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6742 (dolist (buf (buffer-list))
6743 (with-current-buffer buf
6744 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6745 (let ((file (expand-file-name (buffer-file-name))))
6746 (unless (member file files)
6747 (push file files))))))
6748 files))
6750 (defsubst org-entry-beginning-position ()
6751 "Return the beginning position of the current entry."
6752 (save-excursion (outline-back-to-heading t) (point)))
6754 (defsubst org-entry-end-position ()
6755 "Return the end position of the current entry."
6756 (save-excursion (outline-next-heading) (point)))
6758 (defun org-cycle-hide-drawers (state)
6759 "Re-hide all drawers after a visibility state change."
6760 (when (and (derived-mode-p 'org-mode)
6761 (not (memq state '(overview folded contents))))
6762 (save-excursion
6763 (let* ((globalp (memq state '(contents all)))
6764 (beg (if globalp (point-min) (point)))
6765 (end (if globalp (point-max)
6766 (if (eq state 'children)
6767 (save-excursion (outline-next-heading) (point))
6768 (org-end-of-subtree t)))))
6769 (goto-char beg)
6770 (while (re-search-forward org-drawer-regexp end t)
6771 (org-flag-drawer t))))))
6773 (defun org-flag-drawer (flag)
6774 "When FLAG is non-nil, hide the drawer we are within.
6775 Otherwise make it visible."
6776 (save-excursion
6777 (beginning-of-line 1)
6778 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6779 (let ((b (match-end 0)))
6780 (if (re-search-forward
6781 "^[ \t]*:END:"
6782 (save-excursion (outline-next-heading) (point)) t)
6783 (outline-flag-region b (point-at-eol) flag)
6784 (error ":END: line missing at position %s" b))))))
6786 (defun org-subtree-end-visible-p ()
6787 "Is the end of the current subtree visible?"
6788 (pos-visible-in-window-p
6789 (save-excursion (org-end-of-subtree t) (point))))
6791 (defun org-first-headline-recenter (&optional N)
6792 "Move cursor to the first headline and recenter the headline.
6793 Optional argument N means put the headline into the Nth line of the window."
6794 (goto-char (point-min))
6795 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6796 (beginning-of-line)
6797 (recenter (prefix-numeric-value N))))
6799 ;;; Saving and restoring visibility
6801 (defun org-outline-overlay-data (&optional use-markers)
6802 "Return a list of the locations of all outline overlays.
6803 These are overlays with the `invisible' property value `outline'.
6804 The return value is a list of cons cells, with start and stop
6805 positions for each overlay.
6806 If USE-MARKERS is set, return the positions as markers."
6807 (let (beg end)
6808 (save-excursion
6809 (save-restriction
6810 (widen)
6811 (delq nil
6812 (mapcar (lambda (o)
6813 (when (eq (overlay-get o 'invisible) 'outline)
6814 (setq beg (overlay-start o)
6815 end (overlay-end o))
6816 (and beg end (> end beg)
6817 (if use-markers
6818 (cons (move-marker (make-marker) beg)
6819 (move-marker (make-marker) end))
6820 (cons beg end)))))
6821 (overlays-in (point-min) (point-max))))))))
6823 (defun org-set-outline-overlay-data (data)
6824 "Create visibility overlays for all positions in DATA.
6825 DATA should have been made by `org-outline-overlay-data'."
6826 (let (o)
6827 (save-excursion
6828 (save-restriction
6829 (widen)
6830 (show-all)
6831 (mapc (lambda (c)
6832 (outline-flag-region (car c) (cdr c) t))
6833 data)))))
6835 ;;; Folding of blocks
6837 (defvar org-hide-block-overlays nil
6838 "Overlays hiding blocks.")
6839 (make-variable-buffer-local 'org-hide-block-overlays)
6841 (defun org-block-map (function &optional start end)
6842 "Call FUNCTION at the head of all source blocks in the current buffer.
6843 Optional arguments START and END can be used to limit the range."
6844 (let ((start (or start (point-min)))
6845 (end (or end (point-max))))
6846 (save-excursion
6847 (goto-char start)
6848 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6849 (save-excursion
6850 (save-match-data
6851 (goto-char (match-beginning 0))
6852 (funcall function)))))))
6854 (defun org-hide-block-toggle-all ()
6855 "Toggle the visibility of all blocks in the current buffer."
6856 (org-block-map #'org-hide-block-toggle))
6858 (defun org-hide-block-all ()
6859 "Fold all blocks in the current buffer."
6860 (interactive)
6861 (org-show-block-all)
6862 (org-block-map #'org-hide-block-toggle-maybe))
6864 (defun org-show-block-all ()
6865 "Unfold all blocks in the current buffer."
6866 (interactive)
6867 (mapc 'delete-overlay org-hide-block-overlays)
6868 (setq org-hide-block-overlays nil))
6870 (defun org-hide-block-toggle-maybe ()
6871 "Toggle visibility of block at point."
6872 (interactive)
6873 (let ((case-fold-search t))
6874 (if (save-excursion
6875 (beginning-of-line 1)
6876 (looking-at org-block-regexp))
6877 (progn (org-hide-block-toggle)
6878 t) ;; to signal that we took action
6879 nil))) ;; to signal that we did not
6881 (defun org-hide-block-toggle (&optional force)
6882 "Toggle the visibility of the current block."
6883 (interactive)
6884 (save-excursion
6885 (beginning-of-line)
6886 (if (re-search-forward org-block-regexp nil t)
6887 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6888 (end (match-end 0)) ;; end of entire body
6890 (if (memq t (mapcar (lambda (overlay)
6891 (eq (overlay-get overlay 'invisible)
6892 'org-hide-block))
6893 (overlays-at start)))
6894 (if (or (not force) (eq force 'off))
6895 (mapc (lambda (ov)
6896 (when (member ov org-hide-block-overlays)
6897 (setq org-hide-block-overlays
6898 (delq ov org-hide-block-overlays)))
6899 (when (eq (overlay-get ov 'invisible)
6900 'org-hide-block)
6901 (delete-overlay ov)))
6902 (overlays-at start)))
6903 (setq ov (make-overlay start end))
6904 (overlay-put ov 'invisible 'org-hide-block)
6905 ;; make the block accessible to isearch
6906 (overlay-put
6907 ov 'isearch-open-invisible
6908 (lambda (ov)
6909 (when (member ov org-hide-block-overlays)
6910 (setq org-hide-block-overlays
6911 (delq ov org-hide-block-overlays)))
6912 (when (eq (overlay-get ov 'invisible)
6913 'org-hide-block)
6914 (delete-overlay ov))))
6915 (push ov org-hide-block-overlays)))
6916 (error "Not looking at a source block"))))
6918 ;; org-tab-after-check-for-cycling-hook
6919 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6920 ;; Remove overlays when changing major mode
6921 (add-hook 'org-mode-hook
6922 (lambda () (org-add-hook 'change-major-mode-hook
6923 'org-show-block-all 'append 'local)))
6925 ;;; Org-goto
6927 (defvar org-goto-window-configuration nil)
6928 (defvar org-goto-marker nil)
6929 (defvar org-goto-map
6930 (let ((map (make-sparse-keymap)))
6931 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6932 (while (setq cmd (pop cmds))
6933 (substitute-key-definition cmd cmd map global-map)))
6934 (suppress-keymap map)
6935 (org-defkey map "\C-m" 'org-goto-ret)
6936 (org-defkey map [(return)] 'org-goto-ret)
6937 (org-defkey map [(left)] 'org-goto-left)
6938 (org-defkey map [(right)] 'org-goto-right)
6939 (org-defkey map [(control ?g)] 'org-goto-quit)
6940 (org-defkey map "\C-i" 'org-cycle)
6941 (org-defkey map [(tab)] 'org-cycle)
6942 (org-defkey map [(down)] 'outline-next-visible-heading)
6943 (org-defkey map [(up)] 'outline-previous-visible-heading)
6944 (if org-goto-auto-isearch
6945 (if (fboundp 'define-key-after)
6946 (define-key-after map [t] 'org-goto-local-auto-isearch)
6947 nil)
6948 (org-defkey map "q" 'org-goto-quit)
6949 (org-defkey map "n" 'outline-next-visible-heading)
6950 (org-defkey map "p" 'outline-previous-visible-heading)
6951 (org-defkey map "f" 'outline-forward-same-level)
6952 (org-defkey map "b" 'outline-backward-same-level)
6953 (org-defkey map "u" 'outline-up-heading))
6954 (org-defkey map "/" 'org-occur)
6955 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6956 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6957 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6958 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6959 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6960 map))
6962 (defconst org-goto-help
6963 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6964 RET=jump to location [Q]uit and return to previous location
6965 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6967 (defvar org-goto-start-pos) ; dynamically scoped parameter
6969 ;; FIXME: Docstring does not mention both interfaces
6970 (defun org-goto (&optional alternative-interface)
6971 "Look up a different location in the current file, keeping current visibility.
6973 When you want look-up or go to a different location in a
6974 document, the fastest way is often to fold the entire buffer and
6975 then dive into the tree. This method has the disadvantage, that
6976 the previous location will be folded, which may not be what you
6977 want.
6979 This command works around this by showing a copy of the current
6980 buffer in an indirect buffer, in overview mode. You can dive
6981 into the tree in that copy, use org-occur and incremental search
6982 to find a location. When pressing RET or `Q', the command
6983 returns to the original buffer in which the visibility is still
6984 unchanged. After RET it will also jump to the location selected
6985 in the indirect buffer and expose the headline hierarchy above.
6987 With a prefix argument, use the alternative interface: e.g. if
6988 `org-goto-interface' is 'outline use 'outline-path-completion."
6989 (interactive "P")
6990 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6991 (org-refile-use-outline-path t)
6992 (org-refile-target-verify-function nil)
6993 (interface
6994 (if (not alternative-interface)
6995 org-goto-interface
6996 (if (eq org-goto-interface 'outline)
6997 'outline-path-completion
6998 'outline)))
6999 (org-goto-start-pos (point))
7000 (selected-point
7001 (if (eq interface 'outline)
7002 (car (org-get-location (current-buffer) org-goto-help))
7003 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7004 (org-refile-check-position pa)
7005 (nth 3 pa)))))
7006 (if selected-point
7007 (progn
7008 (org-mark-ring-push org-goto-start-pos)
7009 (goto-char selected-point)
7010 (if (or (outline-invisible-p) (org-invisible-p2))
7011 (org-show-context 'org-goto)))
7012 (message "Quit"))))
7014 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7015 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7016 (defvar org-goto-local-auto-isearch-map) ; defined below
7018 (defun org-get-location (buf help)
7019 "Let the user select a location in the Org-mode buffer BUF.
7020 This function uses a recursive edit. It returns the selected position
7021 or nil."
7022 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7023 (isearch-hide-immediately nil)
7024 (isearch-search-fun-function
7025 (lambda () 'org-goto-local-search-headings))
7026 (org-goto-selected-point org-goto-exit-command)
7027 (pop-up-frames nil)
7028 (special-display-buffer-names nil)
7029 (special-display-regexps nil)
7030 (special-display-function nil))
7031 (save-excursion
7032 (save-window-excursion
7033 (delete-other-windows)
7034 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7035 (org-pop-to-buffer-same-window
7036 (condition-case nil
7037 (make-indirect-buffer (current-buffer) "*org-goto*")
7038 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7039 (with-output-to-temp-buffer "*Help*"
7040 (princ help))
7041 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7042 (setq buffer-read-only nil)
7043 (let ((org-startup-truncated t)
7044 (org-startup-folded nil)
7045 (org-startup-align-all-tables nil))
7046 (org-mode)
7047 (org-overview))
7048 (setq buffer-read-only t)
7049 (if (and (boundp 'org-goto-start-pos)
7050 (integer-or-marker-p org-goto-start-pos))
7051 (let ((org-show-hierarchy-above t)
7052 (org-show-siblings t)
7053 (org-show-following-heading t))
7054 (goto-char org-goto-start-pos)
7055 (and (outline-invisible-p) (org-show-context)))
7056 (goto-char (point-min)))
7057 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7058 (message "Select location and press RET")
7059 (use-local-map org-goto-map)
7060 (recursive-edit)
7062 (kill-buffer "*org-goto*")
7063 (cons org-goto-selected-point org-goto-exit-command)))
7065 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7066 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7067 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7068 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7070 (defun org-goto-local-search-headings (string bound noerror)
7071 "Search and make sure that any matches are in headlines."
7072 (catch 'return
7073 (while (if isearch-forward
7074 (search-forward string bound noerror)
7075 (search-backward string bound noerror))
7076 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7077 (and (member :headline context)
7078 (not (member :tags context))))
7079 (throw 'return (point))))))
7081 (defun org-goto-local-auto-isearch ()
7082 "Start isearch."
7083 (interactive)
7084 (goto-char (point-min))
7085 (let ((keys (this-command-keys)))
7086 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7087 (isearch-mode t)
7088 (isearch-process-search-char (string-to-char keys)))))
7090 (defun org-goto-ret (&optional arg)
7091 "Finish `org-goto' by going to the new location."
7092 (interactive "P")
7093 (setq org-goto-selected-point (point)
7094 org-goto-exit-command 'return)
7095 (throw 'exit nil))
7097 (defun org-goto-left ()
7098 "Finish `org-goto' by going to the new location."
7099 (interactive)
7100 (if (org-at-heading-p)
7101 (progn
7102 (beginning-of-line 1)
7103 (setq org-goto-selected-point (point)
7104 org-goto-exit-command 'left)
7105 (throw 'exit nil))
7106 (error "Not on a heading")))
7108 (defun org-goto-right ()
7109 "Finish `org-goto' by going to the new location."
7110 (interactive)
7111 (if (org-at-heading-p)
7112 (progn
7113 (setq org-goto-selected-point (point)
7114 org-goto-exit-command 'right)
7115 (throw 'exit nil))
7116 (error "Not on a heading")))
7118 (defun org-goto-quit ()
7119 "Finish `org-goto' without cursor motion."
7120 (interactive)
7121 (setq org-goto-selected-point nil)
7122 (setq org-goto-exit-command 'quit)
7123 (throw 'exit nil))
7125 ;;; Indirect buffer display of subtrees
7127 (defvar org-indirect-dedicated-frame nil
7128 "This is the frame being used for indirect tree display.")
7129 (defvar org-last-indirect-buffer nil)
7131 (defun org-tree-to-indirect-buffer (&optional arg)
7132 "Create indirect buffer and narrow it to current subtree.
7133 With numerical prefix ARG, go up to this level and then take that tree.
7134 If ARG is negative, go up that many levels.
7135 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7136 indirect buffer previously made with this command, to avoid proliferation of
7137 indirect buffers. However, when you call the command with a \
7138 \\[universal-argument] prefix, or
7139 when `org-indirect-buffer-display' is `new-frame', the last buffer
7140 is kept so that you can work with several indirect buffers at the same time.
7141 If `org-indirect-buffer-display' is `dedicated-frame', the \
7142 \\[universal-argument] prefix also
7143 requests that a new frame be made for the new buffer, so that the dedicated
7144 frame is not changed."
7145 (interactive "P")
7146 (let ((cbuf (current-buffer))
7147 (cwin (selected-window))
7148 (pos (point))
7149 beg end level heading ibuf)
7150 (save-excursion
7151 (org-back-to-heading t)
7152 (when (numberp arg)
7153 (setq level (org-outline-level))
7154 (if (< arg 0) (setq arg (+ level arg)))
7155 (while (> (setq level (org-outline-level)) arg)
7156 (outline-up-heading 1 t)))
7157 (setq beg (point)
7158 heading (org-get-heading))
7159 (org-end-of-subtree t t)
7160 (if (org-at-heading-p) (backward-char 1))
7161 (setq end (point)))
7162 (if (and (buffer-live-p org-last-indirect-buffer)
7163 (not (eq org-indirect-buffer-display 'new-frame))
7164 (not arg))
7165 (kill-buffer org-last-indirect-buffer))
7166 (setq ibuf (org-get-indirect-buffer cbuf)
7167 org-last-indirect-buffer ibuf)
7168 (cond
7169 ((or (eq org-indirect-buffer-display 'new-frame)
7170 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7171 (select-frame (make-frame))
7172 (delete-other-windows)
7173 (org-pop-to-buffer-same-window ibuf)
7174 (org-set-frame-title heading))
7175 ((eq org-indirect-buffer-display 'dedicated-frame)
7176 (raise-frame
7177 (select-frame (or (and org-indirect-dedicated-frame
7178 (frame-live-p org-indirect-dedicated-frame)
7179 org-indirect-dedicated-frame)
7180 (setq org-indirect-dedicated-frame (make-frame)))))
7181 (delete-other-windows)
7182 (org-pop-to-buffer-same-window ibuf)
7183 (org-set-frame-title (concat "Indirect: " heading)))
7184 ((eq org-indirect-buffer-display 'current-window)
7185 (org-pop-to-buffer-same-window ibuf))
7186 ((eq org-indirect-buffer-display 'other-window)
7187 (pop-to-buffer ibuf))
7188 (t (error "Invalid value")))
7189 (if (featurep 'xemacs)
7190 (save-excursion (org-mode) (turn-on-font-lock)))
7191 (narrow-to-region beg end)
7192 (show-all)
7193 (goto-char pos)
7194 (run-hook-with-args 'org-cycle-hook 'all)
7195 (and (window-live-p cwin) (select-window cwin))))
7197 (defun org-get-indirect-buffer (&optional buffer)
7198 (setq buffer (or buffer (current-buffer)))
7199 (let ((n 1) (base (buffer-name buffer)) bname)
7200 (while (buffer-live-p
7201 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7202 (setq n (1+ n)))
7203 (condition-case nil
7204 (make-indirect-buffer buffer bname 'clone)
7205 (error (make-indirect-buffer buffer bname)))))
7207 (defun org-set-frame-title (title)
7208 "Set the title of the current frame to the string TITLE."
7209 ;; FIXME: how to name a single frame in XEmacs???
7210 (unless (featurep 'xemacs)
7211 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7213 ;;;; Structure editing
7215 ;;; Inserting headlines
7217 (defun org-previous-line-empty-p ()
7218 (save-excursion
7219 (and (not (bobp))
7220 (or (beginning-of-line 0) t)
7221 (save-match-data
7222 (looking-at "[ \t]*$")))))
7224 (defun org-insert-heading (&optional force-heading invisible-ok)
7225 "Insert a new heading or item with same depth at point.
7226 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7227 If point is at the beginning of a headline, insert a sibling before the
7228 current headline. If point is not at the beginning, split the line,
7229 create the new headline with the text in the current line after point
7230 \(but see also the variable `org-M-RET-may-split-line').
7232 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7233 This is important for non-interactive uses of the command."
7234 (interactive "P")
7235 (if (or (= (buffer-size) 0)
7236 (and (not (save-excursion
7237 (and (ignore-errors (org-back-to-heading invisible-ok))
7238 (org-at-heading-p))))
7239 (or force-heading (not (org-in-item-p)))))
7240 (progn
7241 (insert "\n* ")
7242 (run-hooks 'org-insert-heading-hook))
7243 (when (or force-heading (not (org-insert-item)))
7244 (let* ((empty-line-p nil)
7245 (level nil)
7246 (on-heading (org-at-heading-p))
7247 (head (save-excursion
7248 (condition-case nil
7249 (progn
7250 (org-back-to-heading invisible-ok)
7251 (when (and (not on-heading)
7252 (featurep 'org-inlinetask)
7253 (integerp org-inlinetask-min-level)
7254 (>= (length (match-string 0))
7255 org-inlinetask-min-level))
7256 ;; Find a heading level before the inline task
7257 (while (and (setq level (org-up-heading-safe))
7258 (>= level org-inlinetask-min-level)))
7259 (if (org-at-heading-p)
7260 (org-back-to-heading invisible-ok)
7261 (error "This should not happen")))
7262 (setq empty-line-p (org-previous-line-empty-p))
7263 (match-string 0))
7264 (error "*"))))
7265 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7266 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7267 pos hide-previous previous-pos)
7268 (cond
7269 ((and (org-at-heading-p) (bolp)
7270 (or (bobp)
7271 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7272 ;; insert before the current line
7273 (open-line (if blank 2 1)))
7274 ((and (bolp)
7275 (not org-insert-heading-respect-content)
7276 (or (bobp)
7277 (save-excursion
7278 (backward-char 1) (not (outline-invisible-p)))))
7279 ;; insert right here
7280 nil)
7282 ;; somewhere in the line
7283 (save-excursion
7284 (setq previous-pos (point-at-bol))
7285 (end-of-line)
7286 (setq hide-previous (outline-invisible-p)))
7287 (and org-insert-heading-respect-content (org-show-subtree))
7288 (let ((split
7289 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7290 (save-excursion
7291 (let ((p (point)))
7292 (goto-char (point-at-bol))
7293 (and (looking-at org-complex-heading-regexp)
7294 (match-beginning 4)
7295 (> p (match-beginning 4)))))))
7296 tags pos)
7297 (cond
7298 (org-insert-heading-respect-content
7299 (org-end-of-subtree nil t)
7300 (when (featurep 'org-inlinetask)
7301 (while (and (not (eobp))
7302 (looking-at "\\(\\*+\\)[ \t]+")
7303 (>= (length (match-string 1))
7304 org-inlinetask-min-level))
7305 (org-end-of-subtree nil t)))
7306 (or (bolp) (newline))
7307 (or (org-previous-line-empty-p)
7308 (and blank (newline)))
7309 (open-line 1))
7310 ((org-at-heading-p)
7311 (when hide-previous
7312 (show-children)
7313 (org-show-entry))
7314 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7315 (setq tags (and (match-end 2) (match-string 2)))
7316 (and (match-end 1)
7317 (delete-region (match-beginning 1) (match-end 1)))
7318 (setq pos (point-at-bol))
7319 (or split (end-of-line 1))
7320 (delete-horizontal-space)
7321 (if (string-match "\\`\\*+\\'"
7322 (buffer-substring (point-at-bol) (point)))
7323 (insert " "))
7324 (newline (if blank 2 1))
7325 (when tags
7326 (save-excursion
7327 (goto-char pos)
7328 (end-of-line 1)
7329 (insert " " tags)
7330 (org-set-tags nil 'align))))
7332 (or split (end-of-line 1))
7333 (newline (if blank 2 1)))))))
7334 (insert head) (just-one-space)
7335 (setq pos (point))
7336 (end-of-line 1)
7337 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7338 (when (and org-insert-heading-respect-content hide-previous)
7339 (save-excursion
7340 (goto-char previous-pos)
7341 (hide-subtree)))
7342 (run-hooks 'org-insert-heading-hook)))))
7344 (defun org-get-heading (&optional no-tags no-todo)
7345 "Return the heading of the current entry, without the stars.
7346 When NO-TAGS is non-nil, don't include tags.
7347 When NO-TODO is non-nil, don't include TODO keywords."
7348 (save-excursion
7349 (org-back-to-heading t)
7350 (cond
7351 ((and no-tags no-todo)
7352 (looking-at org-complex-heading-regexp)
7353 (match-string 4))
7354 (no-tags
7355 (looking-at (concat org-outline-regexp
7356 "\\(.*?\\)"
7357 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7358 (match-string 1))
7359 (no-todo
7360 (looking-at org-todo-line-regexp)
7361 (match-string 3))
7362 (t (looking-at org-heading-regexp)
7363 (match-string 2)))))
7365 (defun org-heading-components ()
7366 "Return the components of the current heading.
7367 This is a list with the following elements:
7368 - the level as an integer
7369 - the reduced level, different if `org-odd-levels-only' is set.
7370 - the TODO keyword, or nil
7371 - the priority character, like ?A, or nil if no priority is given
7372 - the headline text itself, or the tags string if no headline text
7373 - the tags string, or nil."
7374 (save-excursion
7375 (org-back-to-heading t)
7376 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7377 (list (length (match-string 1))
7378 (org-reduced-level (length (match-string 1)))
7379 (org-match-string-no-properties 2)
7380 (and (match-end 3) (aref (match-string 3) 2))
7381 (org-match-string-no-properties 4)
7382 (org-match-string-no-properties 5)))))
7384 (defun org-get-entry ()
7385 "Get the entry text, after heading, entire subtree."
7386 (save-excursion
7387 (org-back-to-heading t)
7388 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7390 (defun org-insert-heading-after-current ()
7391 "Insert a new heading with same level as current, after current subtree."
7392 (interactive)
7393 (org-back-to-heading)
7394 (org-insert-heading)
7395 (org-move-subtree-down)
7396 (end-of-line 1))
7398 (defun org-insert-heading-respect-content ()
7399 (interactive)
7400 (let ((org-insert-heading-respect-content t))
7401 (org-insert-heading t)))
7403 (defun org-insert-todo-heading-respect-content (&optional force-state)
7404 (interactive "P")
7405 (let ((org-insert-heading-respect-content t))
7406 (org-insert-todo-heading force-state t)))
7408 (defun org-insert-todo-heading (arg &optional force-heading)
7409 "Insert a new heading with the same level and TODO state as current heading.
7410 If the heading has no TODO state, or if the state is DONE, use the first
7411 state (TODO by default). Also with prefix arg, force first state."
7412 (interactive "P")
7413 (when (or force-heading (not (org-insert-item 'checkbox)))
7414 (org-insert-heading force-heading)
7415 (save-excursion
7416 (org-back-to-heading)
7417 (outline-previous-heading)
7418 (looking-at org-todo-line-regexp))
7419 (let*
7420 ((new-mark-x
7421 (if (or arg
7422 (not (match-beginning 2))
7423 (member (match-string 2) org-done-keywords))
7424 (car org-todo-keywords-1)
7425 (match-string 2)))
7426 (new-mark
7428 (run-hook-with-args-until-success
7429 'org-todo-get-default-hook new-mark-x nil)
7430 new-mark-x)))
7431 (beginning-of-line 1)
7432 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7433 (if org-treat-insert-todo-heading-as-state-change
7434 (org-todo new-mark)
7435 (insert new-mark " "))))
7436 (when org-provide-todo-statistics
7437 (org-update-parent-todo-statistics))))
7439 (defun org-insert-subheading (arg)
7440 "Insert a new subheading and demote it.
7441 Works for outline headings and for plain lists alike."
7442 (interactive "P")
7443 (org-insert-heading arg)
7444 (cond
7445 ((org-at-heading-p) (org-do-demote))
7446 ((org-at-item-p) (org-indent-item))))
7448 (defun org-insert-todo-subheading (arg)
7449 "Insert a new subheading with TODO keyword or checkbox and demote it.
7450 Works for outline headings and for plain lists alike."
7451 (interactive "P")
7452 (org-insert-todo-heading arg)
7453 (cond
7454 ((org-at-heading-p) (org-do-demote))
7455 ((org-at-item-p) (org-indent-item))))
7457 ;;; Promotion and Demotion
7459 (defvar org-after-demote-entry-hook nil
7460 "Hook run after an entry has been demoted.
7461 The cursor will be at the beginning of the entry.
7462 When a subtree is being demoted, the hook will be called for each node.")
7464 (defvar org-after-promote-entry-hook nil
7465 "Hook run after an entry has been promoted.
7466 The cursor will be at the beginning of the entry.
7467 When a subtree is being promoted, the hook will be called for each node.")
7469 (defun org-promote-subtree ()
7470 "Promote the entire subtree.
7471 See also `org-promote'."
7472 (interactive)
7473 (save-excursion
7474 (org-with-limited-levels (org-map-tree 'org-promote)))
7475 (org-fix-position-after-promote))
7477 (defun org-demote-subtree ()
7478 "Demote the entire subtree. See `org-demote'.
7479 See also `org-promote'."
7480 (interactive)
7481 (save-excursion
7482 (org-with-limited-levels (org-map-tree 'org-demote)))
7483 (org-fix-position-after-promote))
7486 (defun org-do-promote ()
7487 "Promote the current heading higher up the tree.
7488 If the region is active in `transient-mark-mode', promote all headings
7489 in the region."
7490 (interactive)
7491 (save-excursion
7492 (if (org-region-active-p)
7493 (org-map-region 'org-promote (region-beginning) (region-end))
7494 (org-promote)))
7495 (org-fix-position-after-promote))
7497 (defun org-do-demote ()
7498 "Demote the current heading lower down the tree.
7499 If the region is active in `transient-mark-mode', demote all headings
7500 in the region."
7501 (interactive)
7502 (save-excursion
7503 (if (org-region-active-p)
7504 (org-map-region 'org-demote (region-beginning) (region-end))
7505 (org-demote)))
7506 (org-fix-position-after-promote))
7508 (defun org-fix-position-after-promote ()
7509 "Make sure that after pro/demotion cursor position is right."
7510 (let ((pos (point)))
7511 (when (save-excursion
7512 (beginning-of-line 1)
7513 (looking-at org-todo-line-regexp)
7514 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7515 (cond ((eobp) (insert " "))
7516 ((eolp) (insert " "))
7517 ((equal (char-after) ?\ ) (forward-char 1))))))
7519 (defun org-current-level ()
7520 "Return the level of the current entry, or nil if before the first headline.
7521 The level is the number of stars at the beginning of the headline."
7522 (save-excursion
7523 (org-with-limited-levels
7524 (if (ignore-errors (org-back-to-heading t))
7525 (funcall outline-level)))))
7527 (defun org-get-previous-line-level ()
7528 "Return the outline depth of the last headline before the current line.
7529 Returns 0 for the first headline in the buffer, and nil if before the
7530 first headline."
7531 (let ((current-level (org-current-level))
7532 (prev-level (when (> (line-number-at-pos) 1)
7533 (save-excursion
7534 (beginning-of-line 0)
7535 (org-current-level)))))
7536 (cond ((null current-level) nil) ; Before first headline
7537 ((null prev-level) 0) ; At first headline
7538 (prev-level))))
7540 (defun org-reduced-level (l)
7541 "Compute the effective level of a heading.
7542 This takes into account the setting of `org-odd-levels-only'."
7543 (cond
7544 ((zerop l) 0)
7545 (org-odd-levels-only (1+ (floor (/ l 2))))
7546 (t l)))
7548 (defun org-level-increment ()
7549 "Return the number of stars that will be added or removed at a
7550 time to headlines when structure editing, based on the value of
7551 `org-odd-levels-only'."
7552 (if org-odd-levels-only 2 1))
7554 (defun org-get-valid-level (level &optional change)
7555 "Rectify a level change under the influence of `org-odd-levels-only'
7556 LEVEL is a current level, CHANGE is by how much the level should be
7557 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7558 even level numbers will become the next higher odd number."
7559 (if org-odd-levels-only
7560 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7561 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7562 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7563 (max 1 (+ level (or change 0)))))
7565 (if (boundp 'define-obsolete-function-alias)
7566 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7567 (define-obsolete-function-alias 'org-get-legal-level
7568 'org-get-valid-level)
7569 (define-obsolete-function-alias 'org-get-legal-level
7570 'org-get-valid-level "23.1")))
7572 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7573 ;; ̀org-with-limited-levels'
7574 (defun org-promote ()
7575 "Promote the current heading higher up the tree.
7576 If the region is active in `transient-mark-mode', promote all headings
7577 in the region."
7578 (org-back-to-heading t)
7579 (let* ((level (save-match-data (funcall outline-level)))
7580 (after-change-functions (remove 'flyspell-after-change-function
7581 after-change-functions))
7582 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7583 (diff (abs (- level (length up-head) -1))))
7584 (cond ((and (= level 1) org-called-with-limited-levels
7585 org-allow-promoting-top-level-subtree)
7586 (replace-match "# " nil t))
7587 ((= level 1)
7588 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7589 (t (replace-match up-head nil t)))
7590 ;; Fixup tag positioning
7591 (unless (= level 1)
7592 (and org-auto-align-tags (org-set-tags nil t))
7593 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7594 (run-hooks 'org-after-promote-entry-hook)))
7596 (defun org-demote ()
7597 "Demote the current heading lower down the tree.
7598 If the region is active in `transient-mark-mode', demote all headings
7599 in the region."
7600 (org-back-to-heading t)
7601 (let* ((level (save-match-data (funcall outline-level)))
7602 (after-change-functions (remove 'flyspell-after-change-function
7603 after-change-functions))
7604 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7605 (diff (abs (- level (length down-head) -1))))
7606 (replace-match down-head nil t)
7607 ;; Fixup tag positioning
7608 (and org-auto-align-tags (org-set-tags nil t))
7609 (if org-adapt-indentation (org-fixup-indentation diff))
7610 (run-hooks 'org-after-demote-entry-hook)))
7612 (defun org-cycle-level ()
7613 "Cycle the level of an empty headline through possible states.
7614 This goes first to child, then to parent, level, then up the hierarchy.
7615 After top level, it switches back to sibling level."
7616 (interactive)
7617 (let ((org-adapt-indentation nil))
7618 (when (org-point-at-end-of-empty-headline)
7619 (setq this-command 'org-cycle-level) ; Only needed for caching
7620 (let ((cur-level (org-current-level))
7621 (prev-level (org-get-previous-line-level)))
7622 (cond
7623 ;; If first headline in file, promote to top-level.
7624 ((= prev-level 0)
7625 (loop repeat (/ (- cur-level 1) (org-level-increment))
7626 do (org-do-promote)))
7627 ;; If same level as prev, demote one.
7628 ((= prev-level cur-level)
7629 (org-do-demote))
7630 ;; If parent is top-level, promote to top level if not already.
7631 ((= prev-level 1)
7632 (loop repeat (/ (- cur-level 1) (org-level-increment))
7633 do (org-do-promote)))
7634 ;; If top-level, return to prev-level.
7635 ((= cur-level 1)
7636 (loop repeat (/ (- prev-level 1) (org-level-increment))
7637 do (org-do-demote)))
7638 ;; If less than prev-level, promote one.
7639 ((< cur-level prev-level)
7640 (org-do-promote))
7641 ;; If deeper than prev-level, promote until higher than
7642 ;; prev-level.
7643 ((> cur-level prev-level)
7644 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7645 do (org-do-promote))))
7646 t))))
7648 (defun org-map-tree (fun)
7649 "Call FUN for every heading underneath the current one."
7650 (org-back-to-heading)
7651 (let ((level (funcall outline-level)))
7652 (save-excursion
7653 (funcall fun)
7654 (while (and (progn
7655 (outline-next-heading)
7656 (> (funcall outline-level) level))
7657 (not (eobp)))
7658 (funcall fun)))))
7660 (defun org-map-region (fun beg end)
7661 "Call FUN for every heading between BEG and END."
7662 (let ((org-ignore-region t))
7663 (save-excursion
7664 (setq end (copy-marker end))
7665 (goto-char beg)
7666 (if (and (re-search-forward org-outline-regexp-bol nil t)
7667 (< (point) end))
7668 (funcall fun))
7669 (while (and (progn
7670 (outline-next-heading)
7671 (< (point) end))
7672 (not (eobp)))
7673 (funcall fun)))))
7675 (defvar org-property-end-re) ; silence byte-compiler
7676 (defun org-fixup-indentation (diff)
7677 "Change the indentation in the current entry by DIFF.
7678 However, if any line in the current entry has no indentation, or if it
7679 would end up with no indentation after the change, nothing at all is done."
7680 (save-excursion
7681 (let ((end (save-excursion (outline-next-heading)
7682 (point-marker)))
7683 (prohibit (if (> diff 0)
7684 "^\\S-"
7685 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7686 col)
7687 (unless (save-excursion (end-of-line 1)
7688 (re-search-forward prohibit end t))
7689 (while (and (< (point) end)
7690 (re-search-forward "^[ \t]+" end t))
7691 (goto-char (match-end 0))
7692 (setq col (current-column))
7693 (if (< diff 0) (replace-match ""))
7694 (org-indent-to-column (+ diff col))))
7695 (move-marker end nil))))
7697 (defun org-convert-to-odd-levels ()
7698 "Convert an org-mode file with all levels allowed to one with odd levels.
7699 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7700 level 5 etc."
7701 (interactive)
7702 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7703 (let ((outline-level 'org-outline-level)
7704 (org-odd-levels-only nil) n)
7705 (save-excursion
7706 (goto-char (point-min))
7707 (while (re-search-forward "^\\*\\*+ " nil t)
7708 (setq n (- (length (match-string 0)) 2))
7709 (while (>= (setq n (1- n)) 0)
7710 (org-demote))
7711 (end-of-line 1))))))
7713 (defun org-convert-to-oddeven-levels ()
7714 "Convert an org-mode file with only odd levels to one with odd/even levels.
7715 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7716 file contains a section with an even level, conversion would
7717 destroy the structure of the file. An error is signaled in this
7718 case."
7719 (interactive)
7720 (goto-char (point-min))
7721 ;; First check if there are no even levels
7722 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7723 (org-show-context t)
7724 (error "Not all levels are odd in this file. Conversion not possible"))
7725 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7726 (let ((outline-regexp org-outline-regexp)
7727 (outline-level 'org-outline-level)
7728 (org-odd-levels-only nil) n)
7729 (save-excursion
7730 (goto-char (point-min))
7731 (while (re-search-forward "^\\*\\*+ " nil t)
7732 (setq n (/ (1- (length (match-string 0))) 2))
7733 (while (>= (setq n (1- n)) 0)
7734 (org-promote))
7735 (end-of-line 1))))))
7737 (defun org-tr-level (n)
7738 "Make N odd if required."
7739 (if org-odd-levels-only (1+ (/ n 2)) n))
7741 ;;; Vertical tree motion, cutting and pasting of subtrees
7743 (defun org-move-subtree-up (&optional arg)
7744 "Move the current subtree up past ARG headlines of the same level."
7745 (interactive "p")
7746 (org-move-subtree-down (- (prefix-numeric-value arg))))
7748 (defun org-move-subtree-down (&optional arg)
7749 "Move the current subtree down past ARG headlines of the same level."
7750 (interactive "p")
7751 (setq arg (prefix-numeric-value arg))
7752 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7753 'org-get-last-sibling))
7754 (ins-point (make-marker))
7755 (cnt (abs arg))
7756 (col (current-column))
7757 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7758 ;; Select the tree
7759 (org-back-to-heading)
7760 (setq beg0 (point))
7761 (save-excursion
7762 (setq ne-beg (org-back-over-empty-lines))
7763 (setq beg (point)))
7764 (save-match-data
7765 (save-excursion (outline-end-of-heading)
7766 (setq folded (outline-invisible-p)))
7767 (outline-end-of-subtree))
7768 (outline-next-heading)
7769 (setq ne-end (org-back-over-empty-lines))
7770 (setq end (point))
7771 (goto-char beg0)
7772 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7773 ;; include less whitespace
7774 (save-excursion
7775 (goto-char beg)
7776 (forward-line (- ne-beg ne-end))
7777 (setq beg (point))))
7778 ;; Find insertion point, with error handling
7779 (while (> cnt 0)
7780 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7781 (progn (goto-char beg0)
7782 (error "Cannot move past superior level or buffer limit")))
7783 (setq cnt (1- cnt)))
7784 (if (> arg 0)
7785 ;; Moving forward - still need to move over subtree
7786 (progn (org-end-of-subtree t t)
7787 (save-excursion
7788 (org-back-over-empty-lines)
7789 (or (bolp) (newline)))))
7790 (setq ne-ins (org-back-over-empty-lines))
7791 (move-marker ins-point (point))
7792 (setq txt (buffer-substring beg end))
7793 (org-save-markers-in-region beg end)
7794 (delete-region beg end)
7795 (org-remove-empty-overlays-at beg)
7796 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7797 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7798 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7799 (let ((bbb (point)))
7800 (insert-before-markers txt)
7801 (org-reinstall-markers-in-region bbb)
7802 (move-marker ins-point bbb))
7803 (or (bolp) (insert "\n"))
7804 (setq ins-end (point))
7805 (goto-char ins-point)
7806 (org-skip-whitespace)
7807 (when (and (< arg 0)
7808 (org-first-sibling-p)
7809 (> ne-ins ne-beg))
7810 ;; Move whitespace back to beginning
7811 (save-excursion
7812 (goto-char ins-end)
7813 (let ((kill-whole-line t))
7814 (kill-line (- ne-ins ne-beg)) (point)))
7815 (insert (make-string (- ne-ins ne-beg) ?\n)))
7816 (move-marker ins-point nil)
7817 (if folded
7818 (hide-subtree)
7819 (org-show-entry)
7820 (show-children)
7821 (org-cycle-hide-drawers 'children))
7822 (org-clean-visibility-after-subtree-move)
7823 ;; move back to the initial column we were at
7824 (move-to-column col)))
7826 (defvar org-subtree-clip ""
7827 "Clipboard for cut and paste of subtrees.
7828 This is actually only a copy of the kill, because we use the normal kill
7829 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7831 (defvar org-subtree-clip-folded nil
7832 "Was the last copied subtree folded?
7833 This is used to fold the tree back after pasting.")
7835 (defun org-cut-subtree (&optional n)
7836 "Cut the current subtree into the clipboard.
7837 With prefix arg N, cut this many sequential subtrees.
7838 This is a short-hand for marking the subtree and then cutting it."
7839 (interactive "p")
7840 (org-copy-subtree n 'cut))
7842 (defun org-copy-subtree (&optional n cut force-store-markers)
7843 "Cut the current subtree into the clipboard.
7844 With prefix arg N, cut this many sequential subtrees.
7845 This is a short-hand for marking the subtree and then copying it.
7846 If CUT is non-nil, actually cut the subtree.
7847 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7848 of some markers in the region, even if CUT is non-nil. This is
7849 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7850 (interactive "p")
7851 (let (beg end folded (beg0 (point)))
7852 (if (org-called-interactively-p 'any)
7853 (org-back-to-heading nil) ; take what looks like a subtree
7854 (org-back-to-heading t)) ; take what is really there
7855 (org-back-over-empty-lines)
7856 (setq beg (point))
7857 (skip-chars-forward " \t\r\n")
7858 (save-match-data
7859 (save-excursion (outline-end-of-heading)
7860 (setq folded (outline-invisible-p)))
7861 (condition-case nil
7862 (org-forward-heading-same-level (1- n) t)
7863 (error nil))
7864 (org-end-of-subtree t t))
7865 (org-back-over-empty-lines)
7866 (setq end (point))
7867 (goto-char beg0)
7868 (when (> end beg)
7869 (setq org-subtree-clip-folded folded)
7870 (when (or cut force-store-markers)
7871 (org-save-markers-in-region beg end))
7872 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7873 (setq org-subtree-clip (current-kill 0))
7874 (message "%s: Subtree(s) with %d characters"
7875 (if cut "Cut" "Copied")
7876 (length org-subtree-clip)))))
7878 (defun org-paste-subtree (&optional level tree for-yank)
7879 "Paste the clipboard as a subtree, with modification of headline level.
7880 The entire subtree is promoted or demoted in order to match a new headline
7881 level.
7883 If the cursor is at the beginning of a headline, the same level as
7884 that headline is used to paste the tree
7886 If not, the new level is derived from the *visible* headings
7887 before and after the insertion point, and taken to be the inferior headline
7888 level of the two. So if the previous visible heading is level 3 and the
7889 next is level 4 (or vice versa), level 4 will be used for insertion.
7890 This makes sure that the subtree remains an independent subtree and does
7891 not swallow low level entries.
7893 You can also force a different level, either by using a numeric prefix
7894 argument, or by inserting the heading marker by hand. For example, if the
7895 cursor is after \"*****\", then the tree will be shifted to level 5.
7897 If optional TREE is given, use this text instead of the kill ring.
7899 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7900 move back over whitespace before inserting, and move point to the end of
7901 the inserted text when done."
7902 (interactive "P")
7903 (setq tree (or tree (and kill-ring (current-kill 0))))
7904 (unless (org-kill-is-subtree-p tree)
7905 (error "%s"
7906 (substitute-command-keys
7907 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7908 (org-with-limited-levels
7909 (let* ((visp (not (outline-invisible-p)))
7910 (txt tree)
7911 (^re_ "\\(\\*+\\)[ \t]*")
7912 (old-level (if (string-match org-outline-regexp-bol txt)
7913 (- (match-end 0) (match-beginning 0) 1)
7914 -1))
7915 (force-level (cond (level (prefix-numeric-value level))
7916 ((and (looking-at "[ \t]*$")
7917 (string-match
7918 "^\\*+$" (buffer-substring
7919 (point-at-bol) (point))))
7920 (- (match-end 1) (match-beginning 1)))
7921 ((and (bolp)
7922 (looking-at org-outline-regexp))
7923 (- (match-end 0) (point) 1))
7924 (t nil)))
7925 (previous-level (save-excursion
7926 (condition-case nil
7927 (progn
7928 (outline-previous-visible-heading 1)
7929 (if (looking-at ^re_)
7930 (- (match-end 0) (match-beginning 0) 1)
7932 (error 1))))
7933 (next-level (save-excursion
7934 (condition-case nil
7935 (progn
7936 (or (looking-at org-outline-regexp)
7937 (outline-next-visible-heading 1))
7938 (if (looking-at ^re_)
7939 (- (match-end 0) (match-beginning 0) 1)
7941 (error 1))))
7942 (new-level (or force-level (max previous-level next-level)))
7943 (shift (if (or (= old-level -1)
7944 (= new-level -1)
7945 (= old-level new-level))
7947 (- new-level old-level)))
7948 (delta (if (> shift 0) -1 1))
7949 (func (if (> shift 0) 'org-demote 'org-promote))
7950 (org-odd-levels-only nil)
7951 beg end newend)
7952 ;; Remove the forced level indicator
7953 (if force-level
7954 (delete-region (point-at-bol) (point)))
7955 ;; Paste
7956 (beginning-of-line (if (bolp) 1 2))
7957 (unless for-yank (org-back-over-empty-lines))
7958 (setq beg (point))
7959 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7960 (insert-before-markers txt)
7961 (unless (string-match "\n\\'" txt) (insert "\n"))
7962 (setq newend (point))
7963 (org-reinstall-markers-in-region beg)
7964 (setq end (point))
7965 (goto-char beg)
7966 (skip-chars-forward " \t\n\r")
7967 (setq beg (point))
7968 (if (and (outline-invisible-p) visp)
7969 (save-excursion (outline-show-heading)))
7970 ;; Shift if necessary
7971 (unless (= shift 0)
7972 (save-restriction
7973 (narrow-to-region beg end)
7974 (while (not (= shift 0))
7975 (org-map-region func (point-min) (point-max))
7976 (setq shift (+ delta shift)))
7977 (goto-char (point-min))
7978 (setq newend (point-max))))
7979 (when (or (org-called-interactively-p 'interactive) for-yank)
7980 (message "Clipboard pasted as level %d subtree" new-level))
7981 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7982 kill-ring
7983 (eq org-subtree-clip (current-kill 0))
7984 org-subtree-clip-folded)
7985 ;; The tree was folded before it was killed/copied
7986 (hide-subtree))
7987 (and for-yank (goto-char newend)))))
7989 (defun org-kill-is-subtree-p (&optional txt)
7990 "Check if the current kill is an outline subtree, or a set of trees.
7991 Returns nil if kill does not start with a headline, or if the first
7992 headline level is not the largest headline level in the tree.
7993 So this will actually accept several entries of equal levels as well,
7994 which is OK for `org-paste-subtree'.
7995 If optional TXT is given, check this string instead of the current kill."
7996 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7997 (re (org-get-limited-outline-regexp))
7998 (^re (concat "^" re))
7999 (start-level (and kill
8000 (string-match
8001 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8002 kill)
8003 (- (match-end 2) (match-beginning 2) 1)))
8004 (start (1+ (or (match-beginning 2) -1))))
8005 (if (not start-level)
8006 (progn
8007 nil) ;; does not even start with a heading
8008 (catch 'exit
8009 (while (setq start (string-match ^re kill (1+ start)))
8010 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8011 (throw 'exit nil)))
8012 t))))
8014 (defvar org-markers-to-move nil
8015 "Markers that should be moved with a cut-and-paste operation.
8016 Those markers are stored together with their positions relative to
8017 the start of the region.")
8019 (defun org-save-markers-in-region (beg end)
8020 "Check markers in region.
8021 If these markers are between BEG and END, record their position relative
8022 to BEG, so that after moving the block of text, we can put the markers back
8023 into place.
8024 This function gets called just before an entry or tree gets cut from the
8025 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8026 called immediately, to move the markers with the entries."
8027 (setq org-markers-to-move nil)
8028 (when (featurep 'org-clock)
8029 (org-clock-save-markers-for-cut-and-paste beg end))
8030 (when (featurep 'org-agenda)
8031 (org-agenda-save-markers-for-cut-and-paste beg end)))
8033 (defun org-check-and-save-marker (marker beg end)
8034 "Check if MARKER is between BEG and END.
8035 If yes, remember the marker and the distance to BEG."
8036 (when (and (marker-buffer marker)
8037 (equal (marker-buffer marker) (current-buffer)))
8038 (if (and (>= marker beg) (< marker end))
8039 (push (cons marker (- marker beg)) org-markers-to-move))))
8041 (defun org-reinstall-markers-in-region (beg)
8042 "Move all remembered markers to their position relative to BEG."
8043 (mapc (lambda (x)
8044 (move-marker (car x) (+ beg (cdr x))))
8045 org-markers-to-move)
8046 (setq org-markers-to-move nil))
8048 (defun org-narrow-to-subtree ()
8049 "Narrow buffer to the current subtree."
8050 (interactive)
8051 (save-excursion
8052 (save-match-data
8053 (org-with-limited-levels
8054 (narrow-to-region
8055 (progn (org-back-to-heading t) (point))
8056 (progn (org-end-of-subtree t t)
8057 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8058 (point)))))))
8060 (defun org-narrow-to-block ()
8061 "Narrow buffer to the current block."
8062 (interactive)
8063 (let* ((case-fold-search t)
8064 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8065 "^[ \t]*#\\+end_.*")))
8066 (if blockp
8067 (narrow-to-region (car blockp) (cdr blockp))
8068 (error "Not in a block"))))
8070 (eval-when-compile
8071 (defvar org-property-drawer-re))
8073 (defvar org-property-start-re) ;; defined below
8074 (defun org-clone-subtree-with-time-shift (n &optional shift)
8075 "Clone the task (subtree) at point N times.
8076 The clones will be inserted as siblings.
8078 In interactive use, the user will be prompted for the number of
8079 clones to be produced, and for a time SHIFT, which may be a
8080 repeater as used in time stamps, for example `+3d'.
8082 When a valid repeater is given and the entry contains any time
8083 stamps, the clones will become a sequence in time, with time
8084 stamps in the subtree shifted for each clone produced. If SHIFT
8085 is nil or the empty string, time stamps will be left alone. The
8086 ID property of the original subtree is removed.
8088 If the original subtree did contain time stamps with a repeater,
8089 the following will happen:
8090 - the repeater will be removed in each clone
8091 - an additional clone will be produced, with the current, unshifted
8092 date(s) in the entry.
8093 - the original entry will be placed *after* all the clones, with
8094 repeater intact.
8095 - the start days in the repeater in the original entry will be shifted
8096 to past the last clone.
8097 In this way you can spell out a number of instances of a repeating task,
8098 and still retain the repeater to cover future instances of the task."
8099 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8100 (let (beg end template task idprop
8101 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8102 (drawer-re org-drawer-regexp))
8103 (if (not (and (integerp n) (> n 0)))
8104 (error "Invalid number of replications %s" n))
8105 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8106 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8107 shift)))
8108 (error "Invalid shift specification %s" shift))
8109 (when doshift
8110 (setq shift-n (string-to-number (match-string 1 shift))
8111 shift-what (cdr (assoc (match-string 2 shift)
8112 '(("d" . day) ("w" . week)
8113 ("m" . month) ("y" . year))))))
8114 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8115 (setq nmin 1 nmax n)
8116 (org-back-to-heading t)
8117 (setq beg (point))
8118 (setq idprop (org-entry-get nil "ID"))
8119 (org-end-of-subtree t t)
8120 (or (bolp) (insert "\n"))
8121 (setq end (point))
8122 (setq template (buffer-substring beg end))
8123 (when (and doshift
8124 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8125 (delete-region beg end)
8126 (setq end beg)
8127 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8128 (goto-char end)
8129 (loop for n from nmin to nmax do
8130 ;; prepare clone
8131 (with-temp-buffer
8132 (insert template)
8133 (org-mode)
8134 (goto-char (point-min))
8135 (org-show-subtree)
8136 (and idprop (if org-clone-delete-id
8137 (org-entry-delete nil "ID")
8138 (org-id-get-create t)))
8139 (unless (= n 0)
8140 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8141 (kill-whole-line))
8142 (goto-char (point-min))
8143 (while (re-search-forward drawer-re nil t)
8144 (mapc (lambda (d)
8145 (org-remove-empty-drawer-at d (point))) org-drawers)))
8146 (goto-char (point-min))
8147 (when doshift
8148 (while (re-search-forward org-ts-regexp-both nil t)
8149 (org-timestamp-change (* n shift-n) shift-what))
8150 (unless (= n n-no-remove)
8151 (goto-char (point-min))
8152 (while (re-search-forward org-ts-regexp nil t)
8153 (save-excursion
8154 (goto-char (match-beginning 0))
8155 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8156 (delete-region (match-beginning 1) (match-end 1)))))))
8157 (setq task (buffer-string)))
8158 (insert task))
8159 (goto-char beg)))
8161 ;;; Outline Sorting
8163 (defun org-sort (with-case)
8164 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8165 Optional argument WITH-CASE means sort case-sensitively."
8166 (interactive "P")
8167 (cond
8168 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8169 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8171 (org-call-with-arg 'org-sort-entries with-case))))
8173 (defun org-sort-remove-invisible (s)
8174 (remove-text-properties 0 (length s) org-rm-props s)
8175 (while (string-match org-bracket-link-regexp s)
8176 (setq s (replace-match (if (match-end 2)
8177 (match-string 3 s)
8178 (match-string 1 s)) t t s)))
8181 (defvar org-priority-regexp) ; defined later in the file
8183 (defvar org-after-sorting-entries-or-items-hook nil
8184 "Hook that is run after a bunch of entries or items have been sorted.
8185 When children are sorted, the cursor is in the parent line when this
8186 hook gets called. When a region or a plain list is sorted, the cursor
8187 will be in the first entry of the sorted region/list.")
8189 (defun org-sort-entries
8190 (&optional with-case sorting-type getkey-func compare-func property)
8191 "Sort entries on a certain level of an outline tree.
8192 If there is an active region, the entries in the region are sorted.
8193 Else, if the cursor is before the first entry, sort the top-level items.
8194 Else, the children of the entry at point are sorted.
8196 Sorting can be alphabetically, numerically, by date/time as given by
8197 a time stamp, by a property or by priority.
8199 The command prompts for the sorting type unless it has been given to the
8200 function through the SORTING-TYPE argument, which needs to be a character,
8201 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8202 precise meaning of each character:
8204 n Numerically, by converting the beginning of the entry/item to a number.
8205 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8206 t By date/time, either the first active time stamp in the entry, or, if
8207 none exist, by the first inactive one.
8208 s By the scheduled date/time.
8209 d By deadline date/time.
8210 c By creation time, which is assumed to be the first inactive time stamp
8211 at the beginning of a line.
8212 p By priority according to the cookie.
8213 r By the value of a property.
8215 Capital letters will reverse the sort order.
8217 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8218 called with point at the beginning of the record. It must return either
8219 a string or a number that should serve as the sorting key for that record.
8221 Comparing entries ignores case by default. However, with an optional argument
8222 WITH-CASE, the sorting considers case as well."
8223 (interactive "P")
8224 (let ((case-func (if with-case 'identity 'downcase))
8225 start beg end stars re re2
8226 txt what tmp)
8227 ;; Find beginning and end of region to sort
8228 (cond
8229 ((org-region-active-p)
8230 ;; we will sort the region
8231 (setq end (region-end)
8232 what "region")
8233 (goto-char (region-beginning))
8234 (if (not (org-at-heading-p)) (outline-next-heading))
8235 (setq start (point)))
8236 ((or (org-at-heading-p)
8237 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8238 ;; we will sort the children of the current headline
8239 (org-back-to-heading)
8240 (setq start (point)
8241 end (progn (org-end-of-subtree t t)
8242 (or (bolp) (insert "\n"))
8243 (org-back-over-empty-lines)
8244 (point))
8245 what "children")
8246 (goto-char start)
8247 (show-subtree)
8248 (outline-next-heading))
8250 ;; we will sort the top-level entries in this file
8251 (goto-char (point-min))
8252 (or (org-at-heading-p) (outline-next-heading))
8253 (setq start (point))
8254 (goto-char (point-max))
8255 (beginning-of-line 1)
8256 (when (looking-at ".*?\\S-")
8257 ;; File ends in a non-white line
8258 (end-of-line 1)
8259 (insert "\n"))
8260 (setq end (point-max))
8261 (setq what "top-level")
8262 (goto-char start)
8263 (show-all)))
8265 (setq beg (point))
8266 (if (>= beg end) (error "Nothing to sort"))
8268 (looking-at "\\(\\*+\\)")
8269 (setq stars (match-string 1)
8270 re (concat "^" (regexp-quote stars) " +")
8271 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8272 txt (buffer-substring beg end))
8273 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8274 (if (and (not (equal stars "*")) (string-match re2 txt))
8275 (error "Region to sort contains a level above the first entry"))
8277 (unless sorting-type
8278 (message
8279 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8280 [t]ime [s]cheduled [d]eadline [c]reated
8281 A/N/T/S/D/C/P/O/F means reversed:"
8282 what)
8283 (setq sorting-type (read-char-exclusive))
8285 (and (= (downcase sorting-type) ?f)
8286 (setq getkey-func
8287 (org-icompleting-read "Sort using function: "
8288 obarray 'fboundp t nil nil))
8289 (setq getkey-func (intern getkey-func)))
8291 (and (= (downcase sorting-type) ?r)
8292 (setq property
8293 (org-icompleting-read "Property: "
8294 (mapcar 'list (org-buffer-property-keys t))
8295 nil t))))
8297 (message "Sorting entries...")
8299 (save-restriction
8300 (narrow-to-region start end)
8301 (let ((dcst (downcase sorting-type))
8302 (case-fold-search nil)
8303 (now (current-time)))
8304 (sort-subr
8305 (/= dcst sorting-type)
8306 ;; This function moves to the beginning character of the "record" to
8307 ;; be sorted.
8308 (lambda nil
8309 (if (re-search-forward re nil t)
8310 (goto-char (match-beginning 0))
8311 (goto-char (point-max))))
8312 ;; This function moves to the last character of the "record" being
8313 ;; sorted.
8314 (lambda nil
8315 (save-match-data
8316 (condition-case nil
8317 (outline-forward-same-level 1)
8318 (error
8319 (goto-char (point-max))))))
8320 ;; This function returns the value that gets sorted against.
8321 (lambda nil
8322 (cond
8323 ((= dcst ?n)
8324 (if (looking-at org-complex-heading-regexp)
8325 (string-to-number (match-string 4))
8326 nil))
8327 ((= dcst ?a)
8328 (if (looking-at org-complex-heading-regexp)
8329 (funcall case-func (match-string 4))
8330 nil))
8331 ((= dcst ?t)
8332 (let ((end (save-excursion (outline-next-heading) (point))))
8333 (if (or (re-search-forward org-ts-regexp end t)
8334 (re-search-forward org-ts-regexp-both end t))
8335 (org-time-string-to-seconds (match-string 0))
8336 (org-float-time now))))
8337 ((= dcst ?c)
8338 (let ((end (save-excursion (outline-next-heading) (point))))
8339 (if (re-search-forward
8340 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8341 end t)
8342 (org-time-string-to-seconds (match-string 0))
8343 (org-float-time now))))
8344 ((= dcst ?s)
8345 (let ((end (save-excursion (outline-next-heading) (point))))
8346 (if (re-search-forward org-scheduled-time-regexp end t)
8347 (org-time-string-to-seconds (match-string 1))
8348 (org-float-time now))))
8349 ((= dcst ?d)
8350 (let ((end (save-excursion (outline-next-heading) (point))))
8351 (if (re-search-forward org-deadline-time-regexp end t)
8352 (org-time-string-to-seconds (match-string 1))
8353 (org-float-time now))))
8354 ((= dcst ?p)
8355 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8356 (string-to-char (match-string 2))
8357 org-default-priority))
8358 ((= dcst ?r)
8359 (or (org-entry-get nil property) ""))
8360 ((= dcst ?o)
8361 (if (looking-at org-complex-heading-regexp)
8362 (- 9999 (length (member (match-string 2)
8363 org-todo-keywords-1)))))
8364 ((= dcst ?f)
8365 (if getkey-func
8366 (progn
8367 (setq tmp (funcall getkey-func))
8368 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8369 tmp)
8370 (error "Invalid key function `%s'" getkey-func)))
8371 (t (error "Invalid sorting type `%c'" sorting-type))))
8373 (cond
8374 ((= dcst ?a) 'string<)
8375 ((= dcst ?f) compare-func)
8376 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8377 (t nil)))))
8378 (run-hooks 'org-after-sorting-entries-or-items-hook)
8379 (message "Sorting entries...done")))
8381 (defun org-do-sort (table what &optional with-case sorting-type)
8382 "Sort TABLE of WHAT according to SORTING-TYPE.
8383 The user will be prompted for the SORTING-TYPE if the call to this
8384 function does not specify it. WHAT is only for the prompt, to indicate
8385 what is being sorted. The sorting key will be extracted from
8386 the car of the elements of the table.
8387 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8388 (unless sorting-type
8389 (message
8390 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8391 what)
8392 (setq sorting-type (read-char-exclusive)))
8393 (let ((dcst (downcase sorting-type))
8394 extractfun comparefun)
8395 ;; Define the appropriate functions
8396 (cond
8397 ((= dcst ?n)
8398 (setq extractfun 'string-to-number
8399 comparefun (if (= dcst sorting-type) '< '>)))
8400 ((= dcst ?a)
8401 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8402 (lambda(x) (downcase (org-sort-remove-invisible x))))
8403 comparefun (if (= dcst sorting-type)
8404 'string<
8405 (lambda (a b) (and (not (string< a b))
8406 (not (string= a b)))))))
8407 ((= dcst ?t)
8408 (setq extractfun
8409 (lambda (x)
8410 (if (or (string-match org-ts-regexp x)
8411 (string-match org-ts-regexp-both x))
8412 (org-float-time
8413 (org-time-string-to-time (match-string 0 x)))
8415 comparefun (if (= dcst sorting-type) '< '>)))
8416 (t (error "Invalid sorting type `%c'" sorting-type)))
8418 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8419 table)
8420 (lambda (a b) (funcall comparefun (car a) (car b))))))
8423 ;;; The orgstruct minor mode
8425 ;; Define a minor mode which can be used in other modes in order to
8426 ;; integrate the org-mode structure editing commands.
8428 ;; This is really a hack, because the org-mode structure commands use
8429 ;; keys which normally belong to the major mode. Here is how it
8430 ;; works: The minor mode defines all the keys necessary to operate the
8431 ;; structure commands, but wraps the commands into a function which
8432 ;; tests if the cursor is currently at a headline or a plain list
8433 ;; item. If that is the case, the structure command is used,
8434 ;; temporarily setting many Org-mode variables like regular
8435 ;; expressions for filling etc. However, when any of those keys is
8436 ;; used at a different location, function uses `key-binding' to look
8437 ;; up if the key has an associated command in another currently active
8438 ;; keymap (minor modes, major mode, global), and executes that
8439 ;; command. There might be problems if any of the keys is otherwise
8440 ;; used as a prefix key.
8442 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8443 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8444 ;; addresses this by checking explicitly for both bindings.
8446 (defvar orgstruct-mode-map (make-sparse-keymap)
8447 "Keymap for the minor `orgstruct-mode'.")
8449 (defvar org-local-vars nil
8450 "List of local variables, for use by `orgstruct-mode'.")
8452 ;;;###autoload
8453 (define-minor-mode orgstruct-mode
8454 "Toggle the minor mode `orgstruct-mode'.
8455 This mode is for using Org-mode structure commands in other
8456 modes. The following keys behave as if Org-mode were active, if
8457 the cursor is on a headline, or on a plain list item (both as
8458 defined by Org-mode).
8460 M-up Move entry/item up
8461 M-down Move entry/item down
8462 M-left Promote
8463 M-right Demote
8464 M-S-up Move entry/item up
8465 M-S-down Move entry/item down
8466 M-S-left Promote subtree
8467 M-S-right Demote subtree
8468 M-q Fill paragraph and items like in Org-mode
8469 C-c ^ Sort entries
8470 C-c - Cycle list bullet
8471 TAB Cycle item visibility
8472 M-RET Insert new heading/item
8473 S-M-RET Insert new TODO heading / Checkbox item
8474 C-c C-c Set tags / toggle checkbox"
8475 nil " OrgStruct" nil
8476 (org-load-modules-maybe)
8477 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8479 ;;;###autoload
8480 (defun turn-on-orgstruct ()
8481 "Unconditionally turn on `orgstruct-mode'."
8482 (orgstruct-mode 1))
8484 (defvar org-fb-vars nil)
8485 (make-variable-buffer-local 'org-fb-vars)
8486 (defun orgstruct++-mode (&optional arg)
8487 "Toggle `orgstruct-mode', the enhanced version of it.
8488 In addition to setting orgstruct-mode, this also exports all
8489 indentation and autofilling variables from org-mode into the
8490 buffer. It will also recognize item context in multiline items."
8491 (interactive "P")
8492 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8493 (if (< arg 1)
8494 (progn (orgstruct-mode -1)
8495 (mapc (lambda(v)
8496 (org-set-local (car v)
8497 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8498 org-fb-vars))
8499 (orgstruct-mode 1)
8500 (setq org-fb-vars nil)
8501 (let (var val)
8502 (mapc
8503 (lambda (x)
8504 (when (string-match
8505 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8506 (symbol-name (car x)))
8507 (setq var (car x) val (nth 1 x))
8508 (push (list var `(quote ,(eval var))) org-fb-vars)
8509 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8510 org-local-vars)
8511 (org-set-local 'orgstruct-is-++ t))))
8513 (defvar orgstruct-is-++ nil
8514 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8515 (make-variable-buffer-local 'orgstruct-is-++)
8517 ;;;###autoload
8518 (defun turn-on-orgstruct++ ()
8519 "Unconditionally turn on `orgstruct++-mode'."
8520 (orgstruct++-mode 1))
8522 (defun orgstruct-error ()
8523 "Error when there is no default binding for a structure key."
8524 (interactive)
8525 (error "This key has no function outside structure elements"))
8527 (defun orgstruct-setup ()
8528 "Setup orgstruct keymaps."
8529 (let ((nfunc 0)
8530 (bindings
8531 (list
8532 '([(meta up)] org-metaup)
8533 '([(meta down)] org-metadown)
8534 '([(meta left)] org-metaleft)
8535 '([(meta right)] org-metaright)
8536 '([(meta shift up)] org-shiftmetaup)
8537 '([(meta shift down)] org-shiftmetadown)
8538 '([(meta shift left)] org-shiftmetaleft)
8539 '([(meta shift right)] org-shiftmetaright)
8540 '([?\e (up)] org-metaup)
8541 '([?\e (down)] org-metadown)
8542 '([?\e (left)] org-metaleft)
8543 '([?\e (right)] org-metaright)
8544 '([?\e (shift up)] org-shiftmetaup)
8545 '([?\e (shift down)] org-shiftmetadown)
8546 '([?\e (shift left)] org-shiftmetaleft)
8547 '([?\e (shift right)] org-shiftmetaright)
8548 '([(shift up)] org-shiftup)
8549 '([(shift down)] org-shiftdown)
8550 '([(shift left)] org-shiftleft)
8551 '([(shift right)] org-shiftright)
8552 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8553 '("\M-q" fill-paragraph)
8554 '("\C-c^" org-sort)
8555 '("\C-c-" org-cycle-list-bullet)))
8556 elt key fun cmd)
8557 (while (setq elt (pop bindings))
8558 (setq nfunc (1+ nfunc))
8559 (setq key (org-key (car elt))
8560 fun (nth 1 elt)
8561 cmd (orgstruct-make-binding fun nfunc key))
8562 (org-defkey orgstruct-mode-map key cmd))
8564 ;; Prevent an error for users who forgot to make autoloads
8565 (require 'org-element)
8567 ;; Special treatment needed for TAB and RET
8568 (org-defkey orgstruct-mode-map [(tab)]
8569 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8570 (org-defkey orgstruct-mode-map "\C-i"
8571 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8573 (org-defkey orgstruct-mode-map "\M-\C-m"
8574 (orgstruct-make-binding 'org-insert-heading 105
8575 "\M-\C-m" [(meta return)]))
8576 (org-defkey orgstruct-mode-map [(meta return)]
8577 (orgstruct-make-binding 'org-insert-heading 106
8578 [(meta return)] "\M-\C-m"))
8580 (org-defkey orgstruct-mode-map [(shift meta return)]
8581 (orgstruct-make-binding 'org-insert-todo-heading 107
8582 [(meta return)] "\M-\C-m"))
8584 (org-defkey orgstruct-mode-map "\e\C-m"
8585 (orgstruct-make-binding 'org-insert-heading 108
8586 "\e\C-m" [?\e (return)]))
8587 (org-defkey orgstruct-mode-map [?\e (return)]
8588 (orgstruct-make-binding 'org-insert-heading 109
8589 [?\e (return)] "\e\C-m"))
8590 (org-defkey orgstruct-mode-map [?\e (shift return)]
8591 (orgstruct-make-binding 'org-insert-todo-heading 110
8592 [?\e (return)] "\e\C-m"))
8594 (unless org-local-vars
8595 (setq org-local-vars (org-get-local-variables)))
8599 (defun orgstruct-make-binding (fun n &rest keys)
8600 "Create a function for binding in the structure minor mode.
8601 FUN is the command to call inside a table. N is used to create a unique
8602 command name. KEYS are keys that should be checked in for a command
8603 to execute outside of tables."
8604 (eval
8605 (list 'defun
8606 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8607 '(arg)
8608 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8609 "Outside of structure, run the binding of `"
8610 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8611 "'.")
8612 '(interactive "p")
8613 (list 'if
8614 `(org-context-p 'headline 'item
8615 (and orgstruct-is-++
8616 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8617 'item-body))
8618 (list 'org-run-like-in-org-mode (list 'quote fun))
8619 (list 'let '(orgstruct-mode)
8620 (list 'call-interactively
8621 (append '(or)
8622 (mapcar (lambda (k)
8623 (list 'key-binding k))
8624 keys)
8625 '('orgstruct-error))))))))
8627 (defun org-context-p (&rest contexts)
8628 "Check if local context is any of CONTEXTS.
8629 Possible values in the list of contexts are `table', `headline', and `item'."
8630 (let ((pos (point)))
8631 (goto-char (point-at-bol))
8632 (prog1 (or (and (memq 'table contexts)
8633 (looking-at "[ \t]*|"))
8634 (and (memq 'headline contexts)
8635 (looking-at org-outline-regexp))
8636 (and (memq 'item contexts)
8637 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8638 (and (memq 'item-body contexts)
8639 (org-in-item-p)))
8640 (goto-char pos))))
8642 (defun org-get-local-variables ()
8643 "Return a list of all local variables in an Org mode buffer."
8644 (let (varlist)
8645 (with-current-buffer (get-buffer-create "*Org tmp*")
8646 (erase-buffer)
8647 (org-mode)
8648 (setq varlist (buffer-local-variables)))
8649 (kill-buffer "*Org tmp*")
8650 (delq nil
8651 (mapcar
8652 (lambda (x)
8653 (setq x
8654 (if (symbolp x)
8655 (list x)
8656 (list (car x) (list 'quote (cdr x)))))
8657 (if (string-match
8658 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8659 (symbol-name (car x)))
8660 x nil))
8661 varlist))))
8663 (defun org-clone-local-variables (from-buffer &optional regexp)
8664 "Clone local variables from FROM-BUFFER.
8665 Optional argument REGEXP selects variables to clone."
8666 (mapc
8667 (lambda (pair)
8668 (and (symbolp (car pair))
8669 (or (null regexp)
8670 (string-match regexp (symbol-name (car pair))))
8671 (set (make-local-variable (car pair))
8672 (cdr pair))))
8673 (buffer-local-variables from-buffer)))
8675 ;;;###autoload
8676 (defun org-run-like-in-org-mode (cmd)
8677 "Run a command, pretending that the current buffer is in Org-mode.
8678 This will temporarily bind local variables that are typically bound in
8679 Org-mode to the values they have in Org-mode, and then interactively
8680 call CMD."
8681 (org-load-modules-maybe)
8682 (unless org-local-vars
8683 (setq org-local-vars (org-get-local-variables)))
8684 (eval (list 'let org-local-vars
8685 (list 'call-interactively (list 'quote cmd)))))
8687 ;;;; Archiving
8689 (defun org-get-category (&optional pos force-refresh)
8690 "Get the category applying to position POS."
8691 (save-match-data
8692 (if force-refresh (org-refresh-category-properties))
8693 (let ((pos (or pos (point))))
8694 (or (get-text-property pos 'org-category)
8695 (progn (org-refresh-category-properties)
8696 (get-text-property pos 'org-category))))))
8698 (defun org-refresh-category-properties ()
8699 "Refresh category text properties in the buffer."
8700 (let ((inhibit-read-only t)
8701 (def-cat (cond
8702 ((null org-category)
8703 (if buffer-file-name
8704 (file-name-sans-extension
8705 (file-name-nondirectory buffer-file-name))
8706 "???"))
8707 ((symbolp org-category) (symbol-name org-category))
8708 (t org-category)))
8709 beg end cat pos optionp)
8710 (org-unmodified
8711 (save-excursion
8712 (save-restriction
8713 (widen)
8714 (goto-char (point-min))
8715 (put-text-property (point) (point-max) 'org-category def-cat)
8716 (while (re-search-forward
8717 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8718 (setq pos (match-end 0)
8719 optionp (equal (char-after (match-beginning 0)) ?#)
8720 cat (org-trim (match-string 2)))
8721 (if optionp
8722 (setq beg (point-at-bol) end (point-max))
8723 (org-back-to-heading t)
8724 (setq beg (point) end (org-end-of-subtree t t)))
8725 (put-text-property beg end 'org-category cat)
8726 (put-text-property beg end 'org-category-position beg)
8727 (goto-char pos)))))))
8730 ;;;; Link Stuff
8732 ;;; Link abbreviations
8734 (defun org-link-expand-abbrev (link)
8735 "Apply replacements as defined in `org-link-abbrev-alist'."
8736 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8737 (let* ((key (match-string 1 link))
8738 (as (or (assoc key org-link-abbrev-alist-local)
8739 (assoc key org-link-abbrev-alist)))
8740 (tag (and (match-end 2) (match-string 3 link)))
8741 rpl)
8742 (if (not as)
8743 link
8744 (setq rpl (cdr as))
8745 (cond
8746 ((symbolp rpl) (funcall rpl tag))
8747 ((string-match "%(\\([^)]+\\))" rpl)
8748 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8749 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8750 ((string-match "%h" rpl)
8751 (replace-match (url-hexify-string (or tag "")) t t rpl))
8752 (t (concat rpl tag)))))
8753 link))
8755 ;;; Storing and inserting links
8757 (defvar org-insert-link-history nil
8758 "Minibuffer history for links inserted with `org-insert-link'.")
8760 (defvar org-stored-links nil
8761 "Contains the links stored with `org-store-link'.")
8763 (defvar org-store-link-plist nil
8764 "Plist with info about the most recently link created with `org-store-link'.")
8766 (defvar org-link-protocols nil
8767 "Link protocols added to Org-mode using `org-add-link-type'.")
8769 (defvar org-store-link-functions nil
8770 "List of functions that are called to create and store a link.
8771 Each function will be called in turn until one returns a non-nil
8772 value. Each function should check if it is responsible for creating
8773 this link (for example by looking at the major mode).
8774 If not, it must exit and return nil.
8775 If yes, it should return a non-nil value after a calling
8776 `org-store-link-props' with a list of properties and values.
8777 Special properties are:
8779 :type The link prefix, like \"http\". This must be given.
8780 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8781 This is obligatory as well.
8782 :description Optional default description for the second pair
8783 of brackets in an Org-mode link. The user can still change
8784 this when inserting this link into an Org-mode buffer.
8786 In addition to these, any additional properties can be specified
8787 and then used in remember templates.")
8789 (defun org-add-link-type (type &optional follow export)
8790 "Add TYPE to the list of `org-link-types'.
8791 Re-compute all regular expressions depending on `org-link-types'
8793 FOLLOW and EXPORT are two functions.
8795 FOLLOW should take the link path as the single argument and do whatever
8796 is necessary to follow the link, for example find a file or display
8797 a mail message.
8799 EXPORT should format the link path for export to one of the export formats.
8800 It should be a function accepting three arguments:
8802 path the path of the link, the text after the prefix (like \"http:\")
8803 desc the description of the link, if any, or a description added by
8804 org-export-normalize-links if there is none
8805 format the export format, a symbol like `html' or `latex' or `ascii'..
8807 The function may use the FORMAT information to return different values
8808 depending on the format. The return value will be put literally into
8809 the exported file. If the return value is nil, this means Org should
8810 do what it normally does with links which do not have EXPORT defined.
8812 Org-mode has a built-in default for exporting links. If you are happy with
8813 this default, there is no need to define an export function for the link
8814 type. For a simple example of an export function, see `org-bbdb.el'."
8815 (add-to-list 'org-link-types type t)
8816 (org-make-link-regexps)
8817 (if (assoc type org-link-protocols)
8818 (setcdr (assoc type org-link-protocols) (list follow export))
8819 (push (list type follow export) org-link-protocols)))
8821 (defvar org-agenda-buffer-name)
8823 ;;;###autoload
8824 (defun org-store-link (arg)
8825 "\\<org-mode-map>Store an org-link to the current location.
8826 This link is added to `org-stored-links' and can later be inserted
8827 into an org-buffer with \\[org-insert-link].
8829 For some link types, a prefix arg is interpreted:
8830 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8831 For file links, arg negates `org-context-in-file-links'."
8832 (interactive "P")
8833 (org-load-modules-maybe)
8834 (setq org-store-link-plist nil) ; reset
8835 (org-with-limited-levels
8836 (let (link cpltxt desc description search txt custom-id agenda-link)
8837 (cond
8839 ((run-hook-with-args-until-success 'org-store-link-functions)
8840 (setq link (plist-get org-store-link-plist :link)
8841 desc (or (plist-get org-store-link-plist :description) link)))
8843 ((org-src-edit-buffer-p)
8844 (let (label gc)
8845 (while (or (not label)
8846 (save-excursion
8847 (save-restriction
8848 (widen)
8849 (goto-char (point-min))
8850 (re-search-forward
8851 (regexp-quote (format org-coderef-label-format label))
8852 nil t))))
8853 (when label (message "Label exists already") (sit-for 2))
8854 (setq label (read-string "Code line label: " label)))
8855 (end-of-line 1)
8856 (setq link (format org-coderef-label-format label))
8857 (setq gc (- 79 (length link)))
8858 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8859 (insert link)
8860 (setq link (concat "(" label ")") desc nil)))
8862 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8863 ;; We are in the agenda, link to referenced location
8864 (let ((m (or (get-text-property (point) 'org-hd-marker)
8865 (get-text-property (point) 'org-marker))))
8866 (when m
8867 (org-with-point-at m
8868 (setq agenda-link
8869 (if (org-called-interactively-p 'any)
8870 (call-interactively 'org-store-link)
8871 (org-store-link nil)))))))
8873 ((eq major-mode 'calendar-mode)
8874 (let ((cd (calendar-cursor-to-date)))
8875 (setq link
8876 (format-time-string
8877 (car org-time-stamp-formats)
8878 (apply 'encode-time
8879 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8880 nil nil nil))))
8881 (org-store-link-props :type "calendar" :date cd)))
8883 ((eq major-mode 'help-mode)
8884 (setq link (concat "help:" (save-excursion
8885 (goto-char (point-min))
8886 (looking-at "^[^ ]+")
8887 (match-string 0))))
8888 (org-store-link-props :type "help"))
8890 ((eq major-mode 'w3-mode)
8891 (setq cpltxt (if (and (buffer-name)
8892 (not (string-match "Untitled" (buffer-name))))
8893 (buffer-name)
8894 (url-view-url t))
8895 link (url-view-url t))
8896 (org-store-link-props :type "w3" :url (url-view-url t)))
8898 ((eq major-mode 'w3m-mode)
8899 (setq cpltxt (or w3m-current-title w3m-current-url)
8900 link w3m-current-url)
8901 (org-store-link-props :type "w3m" :url (url-view-url t)))
8903 ((setq search (run-hook-with-args-until-success
8904 'org-create-file-search-functions))
8905 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8906 "::" search))
8907 (setq cpltxt (or description link)))
8909 ((eq major-mode 'image-mode)
8910 (setq cpltxt (concat "file:"
8911 (abbreviate-file-name buffer-file-name))
8912 link cpltxt)
8913 (org-store-link-props :type "image" :file buffer-file-name))
8915 ((eq major-mode 'dired-mode)
8916 ;; link to the file in the current line
8917 (let ((file (dired-get-filename nil t)))
8918 (setq file (if file
8919 (abbreviate-file-name
8920 (expand-file-name (dired-get-filename nil t)))
8921 ;; otherwise, no file so use current directory.
8922 default-directory))
8923 (setq cpltxt (concat "file:" file)
8924 link cpltxt)))
8926 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8927 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8928 (cond
8929 ((org-in-regexp "<<\\(.*?\\)>>")
8930 (setq cpltxt
8931 (concat "file:"
8932 (abbreviate-file-name
8933 (buffer-file-name (buffer-base-buffer)))
8934 "::" (match-string 1))
8935 link cpltxt))
8936 ((and (featurep 'org-id)
8937 (or (eq org-link-to-org-use-id t)
8938 (and (org-called-interactively-p 'any)
8939 (or (eq org-link-to-org-use-id 'create-if-interactive)
8940 (and (eq org-link-to-org-use-id
8941 'create-if-interactive-and-no-custom-id)
8942 (not custom-id))))
8943 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8944 ;; We can make a link using the ID.
8945 (setq link (condition-case nil
8946 (prog1 (org-id-store-link)
8947 (setq desc (plist-get org-store-link-plist :description)))
8948 (error
8949 ;; probably before first headline, link to file only
8950 (concat "file:"
8951 (abbreviate-file-name
8952 (buffer-file-name (buffer-base-buffer))))))))
8954 ;; Just link to current headline
8955 (setq cpltxt (concat "file:"
8956 (abbreviate-file-name
8957 (buffer-file-name (buffer-base-buffer)))))
8958 ;; Add a context search string
8959 (when (org-xor org-context-in-file-links arg)
8960 (setq txt (cond
8961 ((org-at-heading-p) nil)
8962 ((org-region-active-p)
8963 (buffer-substring (region-beginning) (region-end)))
8964 (t nil)))
8965 (when (or (null txt) (string-match "\\S-" txt))
8966 (setq cpltxt
8967 (concat cpltxt "::"
8968 (condition-case nil
8969 (org-make-org-heading-search-string txt)
8970 (error "")))
8971 desc (or (nth 4 (ignore-errors
8972 (org-heading-components))) "NONE"))))
8973 (if (string-match "::\\'" cpltxt)
8974 (setq cpltxt (substring cpltxt 0 -2)))
8975 (setq link cpltxt))))
8977 ((buffer-file-name (buffer-base-buffer))
8978 ;; Just link to this file here.
8979 (setq cpltxt (concat "file:"
8980 (abbreviate-file-name
8981 (buffer-file-name (buffer-base-buffer)))))
8982 ;; Add a context string
8983 (when (org-xor org-context-in-file-links arg)
8984 (setq txt (if (org-region-active-p)
8985 (buffer-substring (region-beginning) (region-end))
8986 (buffer-substring (point-at-bol) (point-at-eol))))
8987 ;; Only use search option if there is some text.
8988 (when (string-match "\\S-" txt)
8989 (setq cpltxt
8990 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8991 desc "NONE")))
8992 (setq link cpltxt))
8994 ((org-called-interactively-p 'interactive)
8995 (error "Cannot link to a buffer which is not visiting a file"))
8997 (t (setq link nil)))
8999 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9000 (setq link (or link cpltxt)
9001 desc (or desc cpltxt))
9002 (if (equal desc "NONE") (setq desc nil))
9004 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9005 (progn
9006 (setq org-stored-links
9007 (cons (list link desc) org-stored-links))
9008 (message "Stored: %s" (or desc link))
9009 (when custom-id
9010 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9011 "::#" custom-id))
9012 (setq org-stored-links
9013 (cons (list link desc) org-stored-links))))
9014 (or agenda-link (and link (org-make-link-string link desc)))))))
9016 (defun org-store-link-props (&rest plist)
9017 "Store link properties, extract names and addresses."
9018 (let (x adr)
9019 (when (setq x (plist-get plist :from))
9020 (setq adr (mail-extract-address-components x))
9021 (setq plist (plist-put plist :fromname (car adr)))
9022 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9023 (when (setq x (plist-get plist :to))
9024 (setq adr (mail-extract-address-components x))
9025 (setq plist (plist-put plist :toname (car adr)))
9026 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9027 (let ((from (plist-get plist :from))
9028 (to (plist-get plist :to)))
9029 (when (and from to org-from-is-user-regexp)
9030 (setq plist
9031 (plist-put plist :fromto
9032 (if (string-match org-from-is-user-regexp from)
9033 (concat "to %t")
9034 (concat "from %f"))))))
9035 (setq org-store-link-plist plist))
9037 (defun org-add-link-props (&rest plist)
9038 "Add these properties to the link property list."
9039 (let (key value)
9040 (while plist
9041 (setq key (pop plist) value (pop plist))
9042 (setq org-store-link-plist
9043 (plist-put org-store-link-plist key value)))))
9045 (defun org-email-link-description (&optional fmt)
9046 "Return the description part of an email link.
9047 This takes information from `org-store-link-plist' and formats it
9048 according to FMT (default from `org-email-link-description-format')."
9049 (setq fmt (or fmt org-email-link-description-format))
9050 (let* ((p org-store-link-plist)
9051 (to (plist-get p :toaddress))
9052 (from (plist-get p :fromaddress))
9053 (table
9054 (list
9055 (cons "%c" (plist-get p :fromto))
9056 (cons "%F" (plist-get p :from))
9057 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9058 (cons "%T" (plist-get p :to))
9059 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9060 (cons "%s" (plist-get p :subject))
9061 (cons "%d" (plist-get p :date))
9062 (cons "%m" (plist-get p :message-id)))))
9063 (when (string-match "%c" fmt)
9064 ;; Check if the user wrote this message
9065 (if (and org-from-is-user-regexp from to
9066 (save-match-data (string-match org-from-is-user-regexp from)))
9067 (setq fmt (replace-match "to %t" t t fmt))
9068 (setq fmt (replace-match "from %f" t t fmt))))
9069 (org-replace-escapes fmt table)))
9071 (defun org-make-org-heading-search-string (&optional string heading)
9072 "Make search string for STRING or current headline."
9073 (interactive)
9074 (let ((s (or string (org-get-heading)))
9075 (lines org-context-in-file-links))
9076 (unless (and string (not heading))
9077 ;; We are using a headline, clean up garbage in there.
9078 (if (string-match org-todo-regexp s)
9079 (setq s (replace-match "" t t s)))
9080 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9081 (setq s (replace-match "" t t s)))
9082 (setq s (org-trim s))
9083 (if (string-match (concat "^\\(" org-quote-string "\\|"
9084 org-comment-string "\\)") s)
9085 (setq s (replace-match "" t t s)))
9086 (while (string-match org-ts-regexp s)
9087 (setq s (replace-match "" t t s))))
9088 (or string (setq s (concat "*" s))) ; Add * for headlines
9089 (when (and string (integerp lines) (> lines 0))
9090 (let ((slines (org-split-string s "\n")))
9091 (when (< lines (length slines))
9092 (setq s (mapconcat
9093 'identity
9094 (reverse (nthcdr (- (length slines) lines)
9095 (reverse slines))) "\n")))))
9096 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9098 (defun org-make-link-string (link &optional description)
9099 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9100 (unless (string-match "\\S-" link)
9101 (error "Empty link"))
9102 (when (and description
9103 (stringp description)
9104 (not (string-match "\\S-" description)))
9105 (setq description nil))
9106 (when (stringp description)
9107 ;; Remove brackets from the description, they are fatal.
9108 (while (string-match "\\[" description)
9109 (setq description (replace-match "{" t t description)))
9110 (while (string-match "\\]" description)
9111 (setq description (replace-match "}" t t description))))
9112 (when (equal link description)
9113 ;; No description needed, it is identical
9114 (setq description nil))
9115 (when (and (not description)
9116 (not (string-match (org-image-file-name-regexp) link))
9117 (not (equal link (org-link-escape link))))
9118 (setq description (org-extract-attributes link)))
9119 (setq link
9120 (cond ((string-match (org-image-file-name-regexp) link) link)
9121 ((string-match org-link-types-re link)
9122 (concat (match-string 1 link)
9123 (org-link-escape (substring link (match-end 1)))))
9124 (t (org-link-escape link))))
9125 (concat "[[" link "]"
9126 (if description (concat "[" description "]") "")
9127 "]"))
9129 (defconst org-link-escape-chars
9130 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9131 "List of characters that should be escaped in link.
9132 This is the list that is used for internal purposes.")
9134 (defconst org-link-escape-chars-browser
9135 '(?\ )
9136 "List of escapes for characters that are problematic in links.
9137 This is the list that is used before handing over to the browser.")
9139 (defun org-link-escape (text &optional table merge)
9140 "Return percent escaped representation of TEXT.
9141 TEXT is a string with the text to escape.
9142 Optional argument TABLE is a list with characters that should be
9143 escaped. When nil, `org-link-escape-chars' is used.
9144 If optional argument MERGE is set, merge TABLE into
9145 `org-link-escape-chars'."
9146 (cond
9147 ((and table merge)
9148 (mapc (lambda (defchr)
9149 (unless (member defchr table)
9150 (setq table (cons defchr table)))) org-link-escape-chars))
9151 ((null table)
9152 (setq table org-link-escape-chars)))
9153 (mapconcat
9154 (lambda (char)
9155 (if (or (member char table)
9156 (and (or (< char 32) (= char 37) (> char 126))
9157 org-url-hexify-p))
9158 (mapconcat (lambda (sequence-element)
9159 (format "%%%.2X" sequence-element))
9160 (or (encode-coding-char char 'utf-8)
9161 (error "Unable to percent escape character: %s"
9162 (char-to-string char))) "")
9163 (char-to-string char))) text ""))
9165 (defun org-link-unescape (str)
9166 "Unhex hexified Unicode strings as returned from the JavaScript function
9167 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9168 (unless (and (null str) (string= "" str))
9169 (let ((pos 0) (case-fold-search t) unhexed)
9170 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9171 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9172 (setq str (replace-match unhexed t t str))
9173 (setq pos (+ pos (length unhexed))))))
9174 str)
9176 (defun org-link-unescape-compound (hex)
9177 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9178 Note: this function also decodes single byte encodings like
9179 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9180 (save-match-data
9181 (let* ((bytes (cdr (split-string hex "%")))
9182 (ret "")
9183 (eat 0)
9184 (sum 0))
9185 (while bytes
9186 (let* ((val (string-to-number (pop bytes) 16))
9187 (shift-xor
9188 (if (= 0 eat)
9189 (cond
9190 ((>= val 252) (cons 6 252))
9191 ((>= val 248) (cons 5 248))
9192 ((>= val 240) (cons 4 240))
9193 ((>= val 224) (cons 3 224))
9194 ((>= val 192) (cons 2 192))
9195 (t (cons 0 0)))
9196 (cons 6 128))))
9197 (if (>= val 192) (setq eat (car shift-xor)))
9198 (setq val (logxor val (cdr shift-xor)))
9199 (setq sum (+ (lsh sum (car shift-xor)) val))
9200 (if (> eat 0) (setq eat (- eat 1)))
9201 (cond
9202 ((= 0 eat) ;multi byte
9203 (setq ret (concat ret (org-char-to-string sum)))
9204 (setq sum 0))
9205 ((not bytes) ; single byte(s)
9206 (setq ret (org-link-unescape-single-byte-sequence hex))))
9207 )) ;; end (while bytes
9208 ret )))
9210 (defun org-link-unescape-single-byte-sequence (hex)
9211 "Unhexify hex-encoded single byte character sequences."
9212 (mapconcat (lambda (byte)
9213 (char-to-string (string-to-number byte 16)))
9214 (cdr (split-string hex "%")) ""))
9216 (defun org-xor (a b)
9217 "Exclusive or."
9218 (if a (not b) b))
9220 (defun org-fixup-message-id-for-http (s)
9221 "Replace special characters in a message id, so it can be used in an http query."
9222 (when (string-match "%" s)
9223 (setq s (mapconcat (lambda (c)
9224 (if (eq c ?%)
9225 "%25"
9226 (char-to-string c)))
9227 s "")))
9228 (while (string-match "<" s)
9229 (setq s (replace-match "%3C" t t s)))
9230 (while (string-match ">" s)
9231 (setq s (replace-match "%3E" t t s)))
9232 (while (string-match "@" s)
9233 (setq s (replace-match "%40" t t s)))
9236 (defun org-link-prettify (link)
9237 "Return a human-readable representation of LINK.
9238 The car of LINK must be a raw link the cdr of LINK must be either
9239 a link description or nil."
9240 (let ((desc (or (cadr link) "<no description>")))
9241 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9242 "<" (car link) ">")))
9244 ;;;###autoload
9245 (defun org-insert-link-global ()
9246 "Insert a link like Org-mode does.
9247 This command can be called in any mode to insert a link in Org-mode syntax."
9248 (interactive)
9249 (org-load-modules-maybe)
9250 (org-run-like-in-org-mode 'org-insert-link))
9252 (defun org-insert-all-links (&optional keep)
9253 "Insert all links in `org-stored-links'."
9254 (interactive "P")
9255 (let ((links (copy-sequence org-stored-links)) l)
9256 (while (setq l (if keep (pop links) (pop org-stored-links)))
9257 (insert "- ")
9258 (org-insert-link nil (car l) (cadr l))
9259 (insert "\n"))))
9261 (defun org-link-fontify-links-to-this-file ()
9262 "Fontify links to the current file in `org-stored-links'."
9263 (let ((f (buffer-file-name)) a b)
9264 (setq a (mapcar (lambda(l)
9265 (let ((ll (car l)))
9266 (when (and (string-match "^file:\\(.+\\)::" ll)
9267 (equal f (expand-file-name (match-string 1 ll))))
9268 ll)))
9269 org-stored-links))
9270 (when (featurep 'org-id)
9271 (setq b (mapcar (lambda(l)
9272 (let ((ll (car l)))
9273 (when (and (string-match "^id:\\(.+\\)$" ll)
9274 (equal f (expand-file-name
9275 (or (org-id-find-id-file
9276 (match-string 1 ll)) ""))))
9277 ll)))
9278 org-stored-links)))
9279 (mapcar (lambda(l)
9280 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9281 (delq nil (append a b)))))
9283 (defvar org-link-links-in-this-file nil)
9284 (defun org-insert-link (&optional complete-file link-location default-description)
9285 "Insert a link. At the prompt, enter the link.
9287 Completion can be used to insert any of the link protocol prefixes like
9288 http or ftp in use.
9290 The history can be used to select a link previously stored with
9291 `org-store-link'. When the empty string is entered (i.e. if you just
9292 press RET at the prompt), the link defaults to the most recently
9293 stored link. As SPC triggers completion in the minibuffer, you need to
9294 use M-SPC or C-q SPC to force the insertion of a space character.
9296 You will also be prompted for a description, and if one is given, it will
9297 be displayed in the buffer instead of the link.
9299 If there is already a link at point, this command will allow you to edit link
9300 and description parts.
9302 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9303 be selected using completion. The path to the file will be relative to the
9304 current directory if the file is in the current directory or a subdirectory.
9305 Otherwise, the link will be the absolute path as completed in the minibuffer
9306 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9307 option `org-link-file-path-type'.
9309 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9310 the current directory or below.
9312 With three \\[universal-argument] prefixes, negate the meaning of
9313 `org-keep-stored-link-after-insertion'.
9315 If `org-make-link-description-function' is non-nil, this function will be
9316 called with the link target, and the result will be the default
9317 link description.
9319 If the LINK-LOCATION parameter is non-nil, this value will be
9320 used as the link location instead of reading one interactively.
9322 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9323 be used as the default description."
9324 (interactive "P")
9325 (let* ((wcf (current-window-configuration))
9326 (region (if (org-region-active-p)
9327 (buffer-substring (region-beginning) (region-end))))
9328 (remove (and region (list (region-beginning) (region-end))))
9329 (desc region)
9330 tmphist ; byte-compile incorrectly complains about this
9331 (link link-location)
9332 entry file all-prefixes auto-desc)
9333 (cond
9334 (link-location) ; specified by arg, just use it.
9335 ((org-in-regexp org-bracket-link-regexp 1)
9336 ;; We do have a link at point, and we are going to edit it.
9337 (setq remove (list (match-beginning 0) (match-end 0)))
9338 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9339 (setq link (read-string "Link: "
9340 (org-link-unescape
9341 (org-match-string-no-properties 1)))))
9342 ((or (org-in-regexp org-angle-link-re)
9343 (org-in-regexp org-plain-link-re))
9344 ;; Convert to bracket link
9345 (setq remove (list (match-beginning 0) (match-end 0))
9346 link (read-string "Link: "
9347 (org-remove-angle-brackets (match-string 0)))))
9348 ((member complete-file '((4) (16)))
9349 ;; Completing read for file names.
9350 (setq link (org-file-complete-link complete-file)))
9352 ;; Read link, with completion for stored links.
9353 (org-link-fontify-links-to-this-file)
9354 (org-switch-to-buffer-other-window "*Org Links*")
9355 (with-current-buffer "*Org Links*"
9356 (erase-buffer)
9357 (insert "Insert a link.
9358 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9359 (when org-stored-links
9360 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9361 (insert (mapconcat 'org-link-prettify
9362 (reverse org-stored-links) "\n")))
9363 (goto-char (point-min)))
9364 (let ((cw (selected-window)))
9365 (select-window (get-buffer-window "*Org Links*" 'visible))
9366 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9367 (unless (pos-visible-in-window-p (point-max))
9368 (org-fit-window-to-buffer))
9369 (and (window-live-p cw) (select-window cw)))
9370 ;; Fake a link history, containing the stored links.
9371 (setq tmphist (append (mapcar 'car org-stored-links)
9372 org-insert-link-history))
9373 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9374 (mapcar 'car org-link-abbrev-alist)
9375 org-link-types))
9376 (unwind-protect
9377 (progn
9378 (setq link
9379 (let ((org-completion-use-ido nil)
9380 (org-completion-use-iswitchb nil))
9381 (org-completing-read
9382 "Link: "
9383 (append
9384 (mapcar (lambda (x) (list (concat x ":")))
9385 all-prefixes)
9386 (mapcar 'car org-stored-links)
9387 (mapcar 'cadr org-stored-links))
9388 nil nil nil
9389 'tmphist
9390 (caar org-stored-links))))
9391 (if (not (string-match "\\S-" link))
9392 (error "No link selected"))
9393 (mapc (lambda(l)
9394 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9395 org-stored-links)
9396 (if (or (member link all-prefixes)
9397 (and (equal ":" (substring link -1))
9398 (member (substring link 0 -1) all-prefixes)
9399 (setq link (substring link 0 -1))))
9400 (setq link (org-link-try-special-completion link))))
9401 (set-window-configuration wcf)
9402 (kill-buffer "*Org Links*"))
9403 (setq entry (assoc link org-stored-links))
9404 (or entry (push link org-insert-link-history))
9405 (setq desc (or desc (nth 1 entry)))))
9407 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9408 (not org-keep-stored-link-after-insertion))
9409 (setq org-stored-links (delq (assoc link org-stored-links)
9410 org-stored-links)))
9412 (if (string-match org-plain-link-re link)
9413 ;; URL-like link, normalize the use of angular brackets.
9414 (setq link (org-remove-angle-brackets link)))
9416 ;; Check if we are linking to the current file with a search option
9417 ;; If yes, simplify the link by using only the search option.
9418 (when (and buffer-file-name
9419 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9420 (let* ((path (match-string 1 link))
9421 (case-fold-search nil)
9422 (search (match-string 2 link)))
9423 (save-match-data
9424 (if (equal (file-truename buffer-file-name) (file-truename path))
9425 ;; We are linking to this same file, with a search option
9426 (setq link search)))))
9428 ;; Check if we can/should use a relative path. If yes, simplify the link
9429 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9430 (let* ((type (match-string 1 link))
9431 (path (match-string 2 link))
9432 (origpath path)
9433 (case-fold-search nil))
9434 (cond
9435 ((or (eq org-link-file-path-type 'absolute)
9436 (equal complete-file '(16)))
9437 (setq path (abbreviate-file-name (expand-file-name path))))
9438 ((eq org-link-file-path-type 'noabbrev)
9439 (setq path (expand-file-name path)))
9440 ((eq org-link-file-path-type 'relative)
9441 (setq path (file-relative-name path)))
9443 (save-match-data
9444 (if (string-match (concat "^" (regexp-quote
9445 (expand-file-name
9446 (file-name-as-directory
9447 default-directory))))
9448 (expand-file-name path))
9449 ;; We are linking a file with relative path name.
9450 (setq path (substring (expand-file-name path)
9451 (match-end 0)))
9452 (setq path (abbreviate-file-name (expand-file-name path)))))))
9453 (setq link (concat type path))
9454 (if (equal desc origpath)
9455 (setq desc path))))
9457 (if org-make-link-description-function
9458 (setq desc (funcall org-make-link-description-function link desc))
9459 (if default-description (setq desc default-description)
9460 (setq desc (or (and auto-desc desc)
9461 (read-string "Description: " desc)))))
9463 (unless (string-match "\\S-" desc) (setq desc nil))
9464 (if remove (apply 'delete-region remove))
9465 (insert (org-make-link-string link desc))))
9467 (defun org-link-try-special-completion (type)
9468 "If there is completion support for link type TYPE, offer it."
9469 (let ((fun (intern (concat "org-" type "-complete-link"))))
9470 (if (functionp fun)
9471 (funcall fun)
9472 (read-string "Link (no completion support): " (concat type ":")))))
9474 (defun org-file-complete-link (&optional arg)
9475 "Create a file link using completion."
9476 (let (file link)
9477 (setq file (read-file-name "File: "))
9478 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9479 (pwd1 (file-name-as-directory (abbreviate-file-name
9480 (expand-file-name ".")))))
9481 (cond
9482 ((equal arg '(16))
9483 (setq link (concat
9484 "file:"
9485 (abbreviate-file-name (expand-file-name file)))))
9486 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9487 (setq link (concat "file:" (match-string 1 file))))
9488 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9489 (expand-file-name file))
9490 (setq link (concat
9491 "file:" (match-string 1 (expand-file-name file)))))
9492 (t (setq link (concat "file:" file)))))
9493 link))
9495 (defun org-completing-read (&rest args)
9496 "Completing-read with SPACE being a normal character."
9497 (let ((enable-recursive-minibuffers t)
9498 (minibuffer-local-completion-map
9499 (copy-keymap minibuffer-local-completion-map)))
9500 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9501 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9502 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9503 (apply 'org-icompleting-read args)))
9505 (defun org-completing-read-no-i (&rest args)
9506 (let (org-completion-use-ido org-completion-use-iswitchb)
9507 (apply 'org-completing-read args)))
9509 (defun org-iswitchb-completing-read (prompt choices &rest args)
9510 "Use iswitch as a completing-read replacement to choose from choices.
9511 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9512 from."
9513 (let* ((iswitchb-use-virtual-buffers nil)
9514 (iswitchb-make-buflist-hook
9515 (lambda ()
9516 (setq iswitchb-temp-buflist choices))))
9517 (iswitchb-read-buffer prompt)))
9519 (defun org-icompleting-read (&rest args)
9520 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9521 (org-without-partial-completion
9522 (if (and org-completion-use-ido
9523 (fboundp 'ido-completing-read)
9524 (boundp 'ido-mode) ido-mode
9525 (listp (second args)))
9526 (let ((ido-enter-matching-directory nil))
9527 (apply 'ido-completing-read (concat (car args))
9528 (if (consp (car (nth 1 args)))
9529 (mapcar 'car (nth 1 args))
9530 (nth 1 args))
9531 (cddr args)))
9532 (if (and org-completion-use-iswitchb
9533 (boundp 'iswitchb-mode) iswitchb-mode
9534 (listp (second args)))
9535 (apply 'org-iswitchb-completing-read (concat (car args))
9536 (if (consp (car (nth 1 args)))
9537 (mapcar 'car (nth 1 args))
9538 (nth 1 args))
9539 (cddr args))
9540 (apply 'completing-read args)))))
9542 (defun org-extract-attributes (s)
9543 "Extract the attributes cookie from a string and set as text property."
9544 (let (a attr (start 0) key value)
9545 (save-match-data
9546 (when (string-match "{{\\([^}]+\\)}}$" s)
9547 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9548 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9549 (setq key (match-string 1 a) value (match-string 2 a)
9550 start (match-end 0)
9551 attr (plist-put attr (intern key) value))))
9552 (org-add-props s nil 'org-attr attr))
9555 (defun org-extract-attributes-from-string (tag)
9556 (let (key value attr)
9557 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9558 (setq key (match-string 1 tag) value (match-string 2 tag)
9559 tag (replace-match "" t t tag)
9560 attr (plist-put attr (intern key) value)))
9561 (cons tag attr)))
9563 (defun org-attributes-to-string (plist)
9564 "Format a property list into an HTML attribute list."
9565 (let ((s "") key value)
9566 (while plist
9567 (setq key (pop plist) value (pop plist))
9568 (and value
9569 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9572 ;;; Opening/following a link
9574 (defvar org-link-search-failed nil)
9576 (defvar org-open-link-functions nil
9577 "Hook for functions finding a plain text link.
9578 These functions must take a single argument, the link content.
9579 They will be called for links that look like [[link text][description]]
9580 when LINK TEXT does not have a protocol like \"http:\" and does not look
9581 like a filename (e.g. \"./blue.png\").
9583 These functions will be called *before* Org attempts to resolve the
9584 link by doing text searches in the current buffer - so if you want a
9585 link \"[[target]]\" to still find \"<<target>>\", your function should
9586 handle this as a special case.
9588 When the function does handle the link, it must return a non-nil value.
9589 If it decides that it is not responsible for this link, it must return
9590 nil to indicate that that Org-mode can continue with other options
9591 like exact and fuzzy text search.")
9593 (defun org-next-link ()
9594 "Move forward to the next link.
9595 If the link is in hidden text, expose it."
9596 (interactive)
9597 (when (and org-link-search-failed (eq this-command last-command))
9598 (goto-char (point-min))
9599 (message "Link search wrapped back to beginning of buffer"))
9600 (setq org-link-search-failed nil)
9601 (let* ((pos (point))
9602 (ct (org-context))
9603 (a (assoc :link ct)))
9604 (if a (goto-char (nth 2 a)))
9605 (if (re-search-forward org-any-link-re nil t)
9606 (progn
9607 (goto-char (match-beginning 0))
9608 (if (outline-invisible-p) (org-show-context)))
9609 (goto-char pos)
9610 (setq org-link-search-failed t)
9611 (error "No further link found"))))
9613 (defun org-previous-link ()
9614 "Move backward to the previous link.
9615 If the link is in hidden text, expose it."
9616 (interactive)
9617 (when (and org-link-search-failed (eq this-command last-command))
9618 (goto-char (point-max))
9619 (message "Link search wrapped back to end of buffer"))
9620 (setq org-link-search-failed nil)
9621 (let* ((pos (point))
9622 (ct (org-context))
9623 (a (assoc :link ct)))
9624 (if a (goto-char (nth 1 a)))
9625 (if (re-search-backward org-any-link-re nil t)
9626 (progn
9627 (goto-char (match-beginning 0))
9628 (if (outline-invisible-p) (org-show-context)))
9629 (goto-char pos)
9630 (setq org-link-search-failed t)
9631 (error "No further link found"))))
9633 (defun org-translate-link (s)
9634 "Translate a link string if a translation function has been defined."
9635 (if (and org-link-translation-function
9636 (fboundp org-link-translation-function)
9637 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9638 (progn
9639 (setq s (funcall org-link-translation-function
9640 (match-string 1 s) (match-string 2 s)))
9641 (concat (car s) ":" (cdr s)))
9644 (defun org-translate-link-from-planner (type path)
9645 "Translate a link from Emacs Planner syntax so that Org can follow it.
9646 This is still an experimental function, your mileage may vary."
9647 (cond
9648 ((member type '("http" "https" "news" "ftp"))
9649 ;; standard Internet links are the same.
9650 nil)
9651 ((and (equal type "irc") (string-match "^//" path))
9652 ;; Planner has two / at the beginning of an irc link, we have 1.
9653 ;; We should have zero, actually....
9654 (setq path (substring path 1)))
9655 ((and (equal type "lisp") (string-match "^/" path))
9656 ;; Planner has a slash, we do not.
9657 (setq type "elisp" path (substring path 1)))
9658 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9659 ;; A typical message link. Planner has the id after the final slash,
9660 ;; we separate it with a hash mark
9661 (setq path (concat (match-string 1 path) "#"
9662 (org-remove-angle-brackets (match-string 2 path)))))
9664 (cons type path))
9666 (defun org-find-file-at-mouse (ev)
9667 "Open file link or URL at mouse."
9668 (interactive "e")
9669 (mouse-set-point ev)
9670 (org-open-at-point 'in-emacs))
9672 (defun org-open-at-mouse (ev)
9673 "Open file link or URL at mouse.
9674 See the docstring of `org-open-file' for details."
9675 (interactive "e")
9676 (mouse-set-point ev)
9677 (if (eq major-mode 'org-agenda-mode)
9678 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9679 (org-open-at-point))
9681 (defvar org-window-config-before-follow-link nil
9682 "The window configuration before following a link.
9683 This is saved in case the need arises to restore it.")
9685 (defvar org-open-link-marker (make-marker)
9686 "Marker pointing to the location where `org-open-at-point; was called.")
9688 ;;;###autoload
9689 (defun org-open-at-point-global ()
9690 "Follow a link like Org-mode does.
9691 This command can be called in any mode to follow a link that has
9692 Org-mode syntax."
9693 (interactive)
9694 (org-run-like-in-org-mode 'org-open-at-point))
9696 ;;;###autoload
9697 (defun org-open-link-from-string (s &optional arg reference-buffer)
9698 "Open a link in the string S, as if it was in Org-mode."
9699 (interactive "sLink: \nP")
9700 (let ((reference-buffer (or reference-buffer (current-buffer))))
9701 (with-temp-buffer
9702 (let ((org-inhibit-startup (not reference-buffer)))
9703 (org-mode)
9704 (insert s)
9705 (goto-char (point-min))
9706 (when reference-buffer
9707 (setq org-link-abbrev-alist-local
9708 (with-current-buffer reference-buffer
9709 org-link-abbrev-alist-local)))
9710 (org-open-at-point arg reference-buffer)))))
9712 (defvar org-open-at-point-functions nil
9713 "Hook that is run when following a link at point.
9715 Functions in this hook must return t if they identify and follow
9716 a link at point. If they don't find anything interesting at point,
9717 they must return nil.")
9719 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9720 (defun org-open-at-point (&optional arg reference-buffer)
9721 "Open link at or after point.
9722 If there is no link at point, this function will search forward up to
9723 the end of the current line.
9724 Normally, files will be opened by an appropriate application. If the
9725 optional prefix argument ARG is non-nil, Emacs will visit the file.
9726 With a double prefix argument, try to open outside of Emacs, in the
9727 application the system uses for this file type."
9728 (interactive "P")
9729 ;; if in a code block, then open the block's results
9730 (unless (call-interactively #'org-babel-open-src-block-result)
9731 (org-load-modules-maybe)
9732 (move-marker org-open-link-marker (point))
9733 (setq org-window-config-before-follow-link (current-window-configuration))
9734 (org-remove-occur-highlights nil nil t)
9735 (cond
9736 ((and (org-at-heading-p)
9737 (not (org-at-timestamp-p t))
9738 (not (org-in-regexp
9739 (concat org-plain-link-re "\\|"
9740 org-bracket-link-regexp "\\|"
9741 org-angle-link-re "\\|"
9742 "[ \t]:[^ \t\n]+:[ \t]*$")))
9743 (not (get-text-property (point) 'org-linked-text)))
9744 (or (org-offer-links-in-entry arg)
9745 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9746 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9747 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9748 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9749 (not (org-in-regexp org-bracket-link-regexp)))
9750 (org-footnote-action))
9752 (let (type path link line search (pos (point)))
9753 (catch 'match
9754 (save-excursion
9755 (skip-chars-forward "^]\n\r")
9756 (when (org-in-regexp org-bracket-link-regexp 1)
9757 (setq link (org-extract-attributes
9758 (org-link-unescape (org-match-string-no-properties 1))))
9759 (while (string-match " *\n *" link)
9760 (setq link (replace-match " " t t link)))
9761 (setq link (org-link-expand-abbrev link))
9762 (cond
9763 ((or (file-name-absolute-p link)
9764 (string-match "^\\.\\.?/" link))
9765 (setq type "file" path link))
9766 ((string-match org-link-re-with-space3 link)
9767 (setq type (match-string 1 link) path (match-string 2 link)))
9768 ((string-match "^help:+\\(.+\\)" link)
9769 (setq type "help" path (match-string 1 link)))
9770 (t (setq type "thisfile" path link)))
9771 (throw 'match t)))
9773 (when (get-text-property (point) 'org-linked-text)
9774 (setq type "thisfile"
9775 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9776 (1+ (point)) (point))
9777 path (buffer-substring
9778 (or (previous-single-property-change pos 'org-linked-text)
9779 (point-min))
9780 (or (next-single-property-change pos 'org-linked-text)
9781 (point-max))))
9782 (throw 'match t))
9784 (save-excursion
9785 (when (or (org-in-regexp org-angle-link-re)
9786 (org-in-regexp org-plain-link-re))
9787 (setq type (match-string 1)
9788 path (org-link-unescape (match-string 2)))
9789 (throw 'match t)))
9790 (save-excursion
9791 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9792 (setq type "tags"
9793 path (match-string 1))
9794 (while (string-match ":" path)
9795 (setq path (replace-match "+" t t path)))
9796 (throw 'match t)))
9797 (when (org-in-regexp "<\\([^><\n]+\\)>")
9798 (setq type "tree-match"
9799 path (match-string 1))
9800 (throw 'match t)))
9801 (unless path
9802 (error "No link found"))
9804 ;; switch back to reference buffer
9805 ;; needed when if called in a temporary buffer through
9806 ;; org-open-link-from-string
9807 (with-current-buffer (or reference-buffer (current-buffer))
9809 ;; Remove any trailing spaces in path
9810 (if (string-match " +\\'" path)
9811 (setq path (replace-match "" t t path)))
9812 (if (and org-link-translation-function
9813 (fboundp org-link-translation-function))
9814 ;; Check if we need to translate the link
9815 (let ((tmp (funcall org-link-translation-function type path)))
9816 (setq type (car tmp) path (cdr tmp))))
9818 (cond
9820 ((assoc type org-link-protocols)
9821 (funcall (nth 1 (assoc type org-link-protocols)) path))
9823 ((equal type "help")
9824 (let ((f-or-v (intern path)))
9825 (cond ((fboundp f-or-v)
9826 (describe-function f-or-v))
9827 ((boundp f-or-v)
9828 (describe-variable f-or-v))
9829 (t (error "Not a known function or variable")))))
9831 ((equal type "mailto")
9832 (let ((cmd (car org-link-mailto-program))
9833 (args (cdr org-link-mailto-program)) args1
9834 (address path) (subject "") a)
9835 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9836 (setq address (match-string 1 path)
9837 subject (org-link-escape (match-string 2 path))))
9838 (while args
9839 (cond
9840 ((not (stringp (car args))) (push (pop args) args1))
9841 (t (setq a (pop args))
9842 (if (string-match "%a" a)
9843 (setq a (replace-match address t t a)))
9844 (if (string-match "%s" a)
9845 (setq a (replace-match subject t t a)))
9846 (push a args1))))
9847 (apply cmd (nreverse args1))))
9849 ((member type '("http" "https" "ftp" "news"))
9850 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9851 (org-link-escape
9852 path org-link-escape-chars-browser)
9853 path))))
9855 ((string= type "doi")
9856 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9857 (org-link-escape
9858 path org-link-escape-chars-browser)
9859 path))))
9861 ((member type '("message"))
9862 (browse-url (concat type ":" path)))
9864 ((string= type "tags")
9865 (org-tags-view arg path))
9867 ((string= type "tree-match")
9868 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9870 ((string= type "file")
9871 (if (string-match "::\\([0-9]+\\)\\'" path)
9872 (setq line (string-to-number (match-string 1 path))
9873 path (substring path 0 (match-beginning 0)))
9874 (if (string-match "::\\(.+\\)\\'" path)
9875 (setq search (match-string 1 path)
9876 path (substring path 0 (match-beginning 0)))))
9877 (if (string-match "[*?{]" (file-name-nondirectory path))
9878 (dired path)
9879 (org-open-file path arg line search)))
9881 ((string= type "shell")
9882 (let ((buf (generate-new-buffer "*Org Shell Output"))
9883 (cmd path))
9884 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9885 (string-match org-confirm-shell-link-not-regexp cmd))
9886 (not org-confirm-shell-link-function)
9887 (funcall org-confirm-shell-link-function
9888 (format "Execute \"%s\" in shell? "
9889 (org-add-props cmd nil
9890 'face 'org-warning))))
9891 (progn
9892 (message "Executing %s" cmd)
9893 (shell-command cmd buf)
9894 (if (featurep 'midnight)
9895 (setq clean-buffer-list-kill-buffer-names
9896 (cons buf clean-buffer-list-kill-buffer-names))))
9897 (error "Abort"))))
9899 ((string= type "elisp")
9900 (let ((cmd path))
9901 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9902 (string-match org-confirm-elisp-link-not-regexp cmd))
9903 (not org-confirm-elisp-link-function)
9904 (funcall org-confirm-elisp-link-function
9905 (format "Execute \"%s\" as elisp? "
9906 (org-add-props cmd nil
9907 'face 'org-warning))))
9908 (message "%s => %s" cmd
9909 (if (equal (string-to-char cmd) ?\()
9910 (eval (read cmd))
9911 (call-interactively (read cmd))))
9912 (error "Abort"))))
9914 ((and (string= type "thisfile")
9915 (run-hook-with-args-until-success
9916 'org-open-link-functions path)))
9918 ((string= type "thisfile")
9919 (if arg
9920 (switch-to-buffer-other-window
9921 (org-get-buffer-for-internal-link (current-buffer)))
9922 (org-mark-ring-push))
9923 (let ((cmd `(org-link-search
9924 ,path
9925 ,(cond ((equal arg '(4)) ''occur)
9926 ((equal arg '(16)) ''org-occur)
9927 (t nil))
9928 ,pos)))
9929 (condition-case nil (let ((org-link-search-inhibit-query t))
9930 (eval cmd))
9931 (error (progn (widen) (eval cmd))))))
9934 (browse-url-at-point)))))))
9935 (move-marker org-open-link-marker nil)
9936 (run-hook-with-args 'org-follow-link-hook)))
9938 (defun org-offer-links-in-entry (&optional nth zero)
9939 "Offer links in the current entry and follow the selected link.
9940 If there is only one link, follow it immediately as well.
9941 If NTH is an integer, immediately pick the NTH link found.
9942 If ZERO is a string, check also this string for a link, and if
9943 there is one, offer it as link number zero."
9944 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9945 "\\(" org-angle-link-re "\\)\\|"
9946 "\\(" org-plain-link-re "\\)"))
9947 (cnt ?0)
9948 (in-emacs (if (integerp nth) nil nth))
9949 have-zero end links link c)
9950 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9951 (push (match-string 0 zero) links)
9952 (setq cnt (1- cnt) have-zero t))
9953 (save-excursion
9954 (org-back-to-heading t)
9955 (setq end (save-excursion (outline-next-heading) (point)))
9956 (while (re-search-forward re end t)
9957 (push (match-string 0) links))
9958 (setq links (org-uniquify (reverse links))))
9960 (cond
9961 ((null links)
9962 (message "No links"))
9963 ((equal (length links) 1)
9964 (setq link (list (car links))))
9965 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9966 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9967 (t ; we have to select a link
9968 (save-excursion
9969 (save-window-excursion
9970 (delete-other-windows)
9971 (with-output-to-temp-buffer "*Select Link*"
9972 (mapc (lambda (l)
9973 (if (not (string-match org-bracket-link-regexp l))
9974 (princ (format "[%c] %s\n" (incf cnt)
9975 (org-remove-angle-brackets l)))
9976 (if (match-end 3)
9977 (princ (format "[%c] %s (%s)\n" (incf cnt)
9978 (match-string 3 l) (match-string 1 l)))
9979 (princ (format "[%c] %s\n" (incf cnt)
9980 (match-string 1 l))))))
9981 links))
9982 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9983 (message "Select link to open, RET to open all:")
9984 (setq c (read-char-exclusive))
9985 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9986 (when (equal c ?q) (error "Abort"))
9987 (if (equal c ?\C-m)
9988 (setq link links)
9989 (setq nth (- c ?0))
9990 (if have-zero (setq nth (1+ nth)))
9991 (unless (and (integerp nth) (>= (length links) nth))
9992 (error "Invalid link selection"))
9993 (setq link (list (nth (1- nth) links))))))
9994 (if link
9995 (let ((buf (current-buffer)))
9996 (dolist (l link)
9997 (org-open-link-from-string l in-emacs buf))
9999 nil)))
10001 ;; Add special file links that specify the way of opening
10003 (org-add-link-type "file+sys" 'org-open-file-with-system)
10004 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10005 (defun org-open-file-with-system (path)
10006 "Open file at PATH using the system way of opening it."
10007 (org-open-file path 'system))
10008 (defun org-open-file-with-emacs (path)
10009 "Open file at PATH in Emacs."
10010 (org-open-file path 'emacs))
10011 (defun org-remove-file-link-modifiers ()
10012 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10013 (goto-char (point-min))
10014 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10015 (org-if-unprotected
10016 (replace-match "file:" t t))))
10017 (eval-after-load "org-exp"
10018 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10019 'org-remove-file-link-modifiers))
10021 ;;;; Time estimates
10023 (defun org-get-effort (&optional pom)
10024 "Get the effort estimate for the current entry."
10025 (org-entry-get pom org-effort-property))
10027 ;;; File search
10029 (defvar org-create-file-search-functions nil
10030 "List of functions to construct the right search string for a file link.
10031 These functions are called in turn with point at the location to
10032 which the link should point.
10034 A function in the hook should first test if it would like to
10035 handle this file type, for example by checking the `major-mode'
10036 or the file extension. If it decides not to handle this file, it
10037 should just return nil to give other functions a chance. If it
10038 does handle the file, it must return the search string to be used
10039 when following the link. The search string will be part of the
10040 file link, given after a double colon, and `org-open-at-point'
10041 will automatically search for it. If special measures must be
10042 taken to make the search successful, another function should be
10043 added to the companion hook `org-execute-file-search-functions',
10044 which see.
10046 A function in this hook may also use `setq' to set the variable
10047 `description' to provide a suggestion for the descriptive text to
10048 be used for this link when it gets inserted into an Org-mode
10049 buffer with \\[org-insert-link].")
10051 (defvar org-execute-file-search-functions nil
10052 "List of functions to execute a file search triggered by a link.
10054 Functions added to this hook must accept a single argument, the
10055 search string that was part of the file link, the part after the
10056 double colon. The function must first check if it would like to
10057 handle this search, for example by checking the `major-mode' or
10058 the file extension. If it decides not to handle this search, it
10059 should just return nil to give other functions a chance. If it
10060 does handle the search, it must return a non-nil value to keep
10061 other functions from trying.
10063 Each function can access the current prefix argument through the
10064 variable `current-prefix-argument'. Note that a single prefix is
10065 used to force opening a link in Emacs, so it may be good to only
10066 use a numeric or double prefix to guide the search function.
10068 In case this is needed, a function in this hook can also restore
10069 the window configuration before `org-open-at-point' was called using:
10071 (set-window-configuration org-window-config-before-follow-link)")
10073 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10074 (defun org-link-search (s &optional type avoid-pos stealth)
10075 "Search for a link search option.
10076 If S is surrounded by forward slashes, it is interpreted as a
10077 regular expression. In org-mode files, this will create an `org-occur'
10078 sparse tree. In ordinary files, `occur' will be used to list matches.
10079 If the current buffer is in `dired-mode', grep will be used to search
10080 in all files. If AVOID-POS is given, ignore matches near that position.
10082 When optional argument STEALTH is non-nil, do not modify
10083 visibility around point, thus ignoring
10084 `org-show-hierarchy-above', `org-show-following-heading' and
10085 `org-show-siblings' variables."
10086 (let ((case-fold-search t)
10087 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10088 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10089 (append '(("") (" ") ("\t") ("\n"))
10090 org-emphasis-alist)
10091 "\\|") "\\)"))
10092 (pos (point))
10093 (pre nil) (post nil)
10094 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10095 (cond
10096 ;; First check if there are any special search functions
10097 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10098 ;; Now try the builtin stuff
10099 ((and (equal (string-to-char s0) ?#)
10100 (> (length s0) 1)
10101 (save-excursion
10102 (goto-char (point-min))
10103 (and
10104 (re-search-forward
10105 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10106 (setq type 'dedicated
10107 pos (match-beginning 0))))
10108 ;; There is an exact target for this
10109 (goto-char pos)
10110 (org-back-to-heading t)))
10111 ((save-excursion
10112 (goto-char (point-min))
10113 (and
10114 (re-search-forward
10115 (concat "<<" (regexp-quote s0) ">>") nil t)
10116 (setq type 'dedicated
10117 pos (match-beginning 0))))
10118 ;; There is an exact target for this
10119 (goto-char pos))
10120 ((save-excursion
10121 (goto-char (point-min))
10122 (and
10123 (re-search-forward
10124 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10125 (setq type 'dedicated pos (match-beginning 0))))
10126 ;; Found an invisible target.
10127 (goto-char pos))
10128 ((save-excursion
10129 (goto-char (point-min))
10130 (and
10131 (re-search-forward
10132 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10133 (setq type 'dedicated pos (match-beginning 0))))
10134 ;; Found an element with a matching #+name affiliated keyword.
10135 (goto-char pos))
10136 ((and (string-match "^(\\(.*\\))$" s0)
10137 (save-excursion
10138 (goto-char (point-min))
10139 (and
10140 (re-search-forward
10141 (concat "[^[]" (regexp-quote
10142 (format org-coderef-label-format
10143 (match-string 1 s0))))
10144 nil t)
10145 (setq type 'dedicated
10146 pos (1+ (match-beginning 0))))))
10147 ;; There is a coderef target for this
10148 (goto-char pos))
10149 ((string-match "^/\\(.*\\)/$" s)
10150 ;; A regular expression
10151 (cond
10152 ((derived-mode-p 'org-mode)
10153 (org-occur (match-string 1 s)))
10154 ;;((eq major-mode 'dired-mode)
10155 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10156 (t (org-do-occur (match-string 1 s)))))
10157 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10158 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10159 (goto-char (point-min))
10160 (cond
10161 ((let (case-fold-search)
10162 (re-search-forward (format org-complex-heading-regexp-format
10163 (regexp-quote s))
10164 nil t))
10165 ;; OK, found a match
10166 (setq type 'dedicated)
10167 (goto-char (match-beginning 0)))
10168 ((and (not org-link-search-inhibit-query)
10169 (eq org-link-search-must-match-exact-headline 'query-to-create)
10170 (y-or-n-p "No match - create this as a new heading? "))
10171 (goto-char (point-max))
10172 (or (bolp) (newline))
10173 (insert "* " s "\n")
10174 (beginning-of-line 0))
10176 (goto-char pos)
10177 (error "No match"))))
10179 ;; A normal search string
10180 (when (equal (string-to-char s) ?*)
10181 ;; Anchor on headlines, post may include tags.
10182 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10183 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10184 s (substring s 1)))
10185 (remove-text-properties
10186 0 (length s)
10187 '(face nil mouse-face nil keymap nil fontified nil) s)
10188 ;; Make a series of regular expressions to find a match
10189 (setq words (org-split-string s "[ \n\r\t]+")
10191 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10192 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10193 "\\)" markers)
10194 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10195 re2a (concat "[ \t\r\n]" re2a_)
10196 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10197 re4 (concat "[^a-zA-Z_]" re4_)
10199 re1 (concat pre re2 post)
10200 re3 (concat pre (if pre re4_ re4) post)
10201 re5 (concat pre ".*" re4)
10202 re2 (concat pre re2)
10203 re2a (concat pre (if pre re2a_ re2a))
10204 re4 (concat pre (if pre re4_ re4))
10205 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10206 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10207 re5 "\\)"
10209 (cond
10210 ((eq type 'org-occur) (org-occur reall))
10211 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10212 (t (goto-char (point-min))
10213 (setq type 'fuzzy)
10214 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10215 (org-search-not-self 1 re1 nil t)
10216 (org-search-not-self 1 re2 nil t)
10217 (org-search-not-self 1 re2a nil t)
10218 (org-search-not-self 1 re3 nil t)
10219 (org-search-not-self 1 re4 nil t)
10220 (org-search-not-self 1 re5 nil t)
10222 (goto-char (match-beginning 1))
10223 (goto-char pos)
10224 (error "No match"))))))
10225 (and (derived-mode-p 'org-mode)
10226 (not stealth)
10227 (org-show-context 'link-search))
10228 type))
10230 (defun org-search-not-self (group &rest args)
10231 "Execute `re-search-forward', but only accept matches that do not
10232 enclose the position of `org-open-link-marker'."
10233 (let ((m org-open-link-marker))
10234 (catch 'exit
10235 (while (apply 're-search-forward args)
10236 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10237 (goto-char (match-end group))
10238 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10239 (> (match-beginning 0) (marker-position m))
10240 (< (match-end 0) (marker-position m)))
10241 (save-match-data
10242 (or (not (org-in-regexp
10243 org-bracket-link-analytic-regexp 1))
10244 (not (match-end 4)) ; no description
10245 (and (<= (match-beginning 4) (point))
10246 (>= (match-end 4) (point))))))
10247 (throw 'exit (point))))))))
10249 (defun org-get-buffer-for-internal-link (buffer)
10250 "Return a buffer to be used for displaying the link target of internal links."
10251 (cond
10252 ((not org-display-internal-link-with-indirect-buffer)
10253 buffer)
10254 ((string-match "(Clone)$" (buffer-name buffer))
10255 (message "Buffer is already a clone, not making another one")
10256 ;; we also do not modify visibility in this case
10257 buffer)
10258 (t ; make a new indirect buffer for displaying the link
10259 (let* ((bn (buffer-name buffer))
10260 (ibn (concat bn "(Clone)"))
10261 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10262 (with-current-buffer ib (org-overview))
10263 ib))))
10265 (defun org-do-occur (regexp &optional cleanup)
10266 "Call the Emacs command `occur'.
10267 If CLEANUP is non-nil, remove the printout of the regular expression
10268 in the *Occur* buffer. This is useful if the regex is long and not useful
10269 to read."
10270 (occur regexp)
10271 (when cleanup
10272 (let ((cwin (selected-window)) win beg end)
10273 (when (setq win (get-buffer-window "*Occur*"))
10274 (select-window win))
10275 (goto-char (point-min))
10276 (when (re-search-forward "match[a-z]+" nil t)
10277 (setq beg (match-end 0))
10278 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10279 (setq end (1- (match-beginning 0)))))
10280 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10281 (goto-char (point-min))
10282 (select-window cwin))))
10284 ;;; The mark ring for links jumps
10286 (defvar org-mark-ring nil
10287 "Mark ring for positions before jumps in Org-mode.")
10288 (defvar org-mark-ring-last-goto nil
10289 "Last position in the mark ring used to go back.")
10290 ;; Fill and close the ring
10291 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10292 (loop for i from 1 to org-mark-ring-length do
10293 (push (make-marker) org-mark-ring))
10294 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10295 org-mark-ring)
10297 (defun org-mark-ring-push (&optional pos buffer)
10298 "Put the current position or POS into the mark ring and rotate it."
10299 (interactive)
10300 (setq pos (or pos (point)))
10301 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10302 (move-marker (car org-mark-ring)
10303 (or pos (point))
10304 (or buffer (current-buffer)))
10305 (message "%s"
10306 (substitute-command-keys
10307 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10309 (defun org-mark-ring-goto (&optional n)
10310 "Jump to the previous position in the mark ring.
10311 With prefix arg N, jump back that many stored positions. When
10312 called several times in succession, walk through the entire ring.
10313 Org-mode commands jumping to a different position in the current file,
10314 or to another Org-mode file, automatically push the old position
10315 onto the ring."
10316 (interactive "p")
10317 (let (p m)
10318 (if (eq last-command this-command)
10319 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10320 (setq p org-mark-ring))
10321 (setq org-mark-ring-last-goto p)
10322 (setq m (car p))
10323 (org-pop-to-buffer-same-window (marker-buffer m))
10324 (goto-char m)
10325 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10327 (defun org-remove-angle-brackets (s)
10328 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10329 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10331 (defun org-add-angle-brackets (s)
10332 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10333 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10335 (defun org-remove-double-quotes (s)
10336 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10337 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10340 ;;; Following specific links
10342 (defun org-follow-timestamp-link ()
10343 (cond
10344 ((org-at-date-range-p t)
10345 (let ((org-agenda-start-on-weekday)
10346 (t1 (match-string 1))
10347 (t2 (match-string 2)))
10348 (setq t1 (time-to-days (org-time-string-to-time t1))
10349 t2 (time-to-days (org-time-string-to-time t2)))
10350 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10351 ((org-at-timestamp-p t)
10352 (org-agenda-list nil (time-to-days (org-time-string-to-time
10353 (substring (match-string 1) 0 10)))
10355 (t (error "This should not happen"))))
10358 ;;; Following file links
10359 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10360 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10361 (declare-function mailcap-mime-info
10362 "mailcap" (string &optional request no-decode))
10363 (defvar org-wait nil)
10364 (defun org-open-file (path &optional in-emacs line search)
10365 "Open the file at PATH.
10366 First, this expands any special file name abbreviations. Then the
10367 configuration variable `org-file-apps' is checked if it contains an
10368 entry for this file type, and if yes, the corresponding command is launched.
10370 If no application is found, Emacs simply visits the file.
10372 With optional prefix argument IN-EMACS, Emacs will visit the file.
10373 With a double \\[universal-argument] \\[universal-argument] \
10374 prefix arg, Org tries to avoid opening in Emacs
10375 and to use an external application to visit the file.
10377 Optional LINE specifies a line to go to, optional SEARCH a string
10378 to search for. If LINE or SEARCH is given, the file will be
10379 opened in Emacs, unless an entry from org-file-apps that makes
10380 use of groups in a regexp matches.
10382 If you want to change the way frames are used when following a
10383 link, please customize `org-link-frame-setup'.
10385 If the file does not exist, an error is thrown."
10386 (let* ((file (if (equal path "")
10387 buffer-file-name
10388 (substitute-in-file-name (expand-file-name path))))
10389 (file-apps (append org-file-apps (org-default-apps)))
10390 (apps (org-remove-if
10391 'org-file-apps-entry-match-against-dlink-p file-apps))
10392 (apps-dlink (org-remove-if-not
10393 'org-file-apps-entry-match-against-dlink-p file-apps))
10394 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10395 (dirp (if remp nil (file-directory-p file)))
10396 (file (if (and dirp org-open-directory-means-index-dot-org)
10397 (concat (file-name-as-directory file) "index.org")
10398 file))
10399 (a-m-a-p (assq 'auto-mode apps))
10400 (dfile (downcase file))
10401 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10402 (link (cond ((and (eq line nil)
10403 (eq search nil))
10404 file)
10405 (line
10406 (concat file "::" (number-to-string line)))
10407 (search
10408 (concat file "::" search))))
10409 (dlink (downcase link))
10410 (old-buffer (current-buffer))
10411 (old-pos (point))
10412 (old-mode major-mode)
10413 ext cmd link-match-data)
10414 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10415 (setq ext (match-string 1 dfile))
10416 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10417 (setq ext (match-string 1 dfile))))
10418 (cond
10419 ((member in-emacs '((16) system))
10420 (setq cmd (cdr (assoc 'system apps))))
10421 (in-emacs (setq cmd 'emacs))
10423 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10424 (and dirp (cdr (assoc 'directory apps)))
10425 ; first, try matching against apps-dlink
10426 ; if we get a match here, store the match data for later
10427 (let ((match (assoc-default dlink apps-dlink
10428 'string-match)))
10429 (if match
10430 (progn (setq link-match-data (match-data))
10431 match)
10432 (progn (setq in-emacs (or in-emacs line search))
10433 nil))) ; if we have no match in apps-dlink,
10434 ; always open the file in emacs if line or search
10435 ; is given (for backwards compatibility)
10436 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10437 'string-match)
10438 (cdr (assoc ext apps))
10439 (cdr (assoc t apps))))))
10440 (when (eq cmd 'system)
10441 (setq cmd (cdr (assoc 'system apps))))
10442 (when (eq cmd 'default)
10443 (setq cmd (cdr (assoc t apps))))
10444 (when (eq cmd 'mailcap)
10445 (require 'mailcap)
10446 (mailcap-parse-mailcaps)
10447 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10448 (command (mailcap-mime-info mime-type)))
10449 (if (stringp command)
10450 (setq cmd command)
10451 (setq cmd 'emacs))))
10452 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10453 (not (file-exists-p file))
10454 (not org-open-non-existing-files))
10455 (error "No such file: %s" file))
10456 (cond
10457 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10458 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10459 (while (string-match "['\"]%s['\"]" cmd)
10460 (setq cmd (replace-match "%s" t t cmd)))
10461 (while (string-match "%s" cmd)
10462 (setq cmd (replace-match
10463 (save-match-data
10464 (shell-quote-argument
10465 (convert-standard-filename file)))
10466 t t cmd)))
10468 ;; Replace "%1", "%2" etc. in command with group matches from regex
10469 (save-match-data
10470 (let ((match-index 1)
10471 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10472 (set-match-data link-match-data)
10473 (while (<= match-index number-of-groups)
10474 (let ((regex (concat "%" (number-to-string match-index)))
10475 (replace-with (match-string match-index dlink)))
10476 (while (string-match regex cmd)
10477 (setq cmd (replace-match replace-with t t cmd))))
10478 (setq match-index (+ match-index 1)))))
10480 (save-window-excursion
10481 (start-process-shell-command cmd nil cmd)
10482 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10484 ((or (stringp cmd)
10485 (eq cmd 'emacs))
10486 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10487 (widen)
10488 (if line (org-goto-line line)
10489 (if search (org-link-search search))))
10490 ((consp cmd)
10491 (let ((file (convert-standard-filename file)))
10492 (save-match-data
10493 (set-match-data link-match-data)
10494 (eval cmd))))
10495 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10496 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10497 (or (not (equal old-buffer (current-buffer)))
10498 (not (equal old-pos (point))))
10499 (org-mark-ring-push old-pos old-buffer))))
10501 (defun org-file-apps-entry-match-against-dlink-p (entry)
10502 "This function returns non-nil if `entry' uses a regular
10503 expression which should be matched against the whole link by
10504 org-open-file.
10506 It assumes that is the case when the entry uses a regular
10507 expression which has at least one grouping construct and the
10508 action is either a lisp form or a command string containing
10509 '%1', i.e. using at least one subexpression match as a
10510 parameter."
10511 (let ((selector (car entry))
10512 (action (cdr entry)))
10513 (if (stringp selector)
10514 (and (> (regexp-opt-depth selector) 0)
10515 (or (and (stringp action)
10516 (string-match "%[0-9]" action))
10517 (consp action)))
10518 nil)))
10520 (defun org-default-apps ()
10521 "Return the default applications for this operating system."
10522 (cond
10523 ((eq system-type 'darwin)
10524 org-file-apps-defaults-macosx)
10525 ((eq system-type 'windows-nt)
10526 org-file-apps-defaults-windowsnt)
10527 (t org-file-apps-defaults-gnu)))
10529 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10530 "Convert extensions to regular expressions in the cars of LIST.
10531 Also, weed out any non-string entries, because the return value is used
10532 only for regexp matching.
10533 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10534 point to the symbol `emacs', indicating that the file should
10535 be opened in Emacs."
10536 (append
10537 (delq nil
10538 (mapcar (lambda (x)
10539 (if (not (stringp (car x)))
10541 (if (string-match "\\W" (car x))
10543 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10544 list))
10545 (if add-auto-mode
10546 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10548 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10549 (defun org-file-remote-p (file)
10550 "Test whether FILE specifies a location on a remote system.
10551 Return non-nil if the location is indeed remote.
10553 For example, the filename \"/user@host:/foo\" specifies a location
10554 on the system \"/user@host:\"."
10555 (cond ((fboundp 'file-remote-p)
10556 (file-remote-p file))
10557 ((fboundp 'tramp-handle-file-remote-p)
10558 (tramp-handle-file-remote-p file))
10559 ((and (boundp 'ange-ftp-name-format)
10560 (string-match (car ange-ftp-name-format) file))
10562 (t nil)))
10565 ;;;; Refiling
10567 (defun org-get-org-file ()
10568 "Read a filename, with default directory `org-directory'."
10569 (let ((default (or org-default-notes-file remember-data-file)))
10570 (read-file-name (format "File name [%s]: " default)
10571 (file-name-as-directory org-directory)
10572 default)))
10574 (defun org-notes-order-reversed-p ()
10575 "Check if the current file should receive notes in reversed order."
10576 (cond
10577 ((not org-reverse-note-order) nil)
10578 ((eq t org-reverse-note-order) t)
10579 ((not (listp org-reverse-note-order)) nil)
10580 (t (catch 'exit
10581 (let ((all org-reverse-note-order)
10582 entry)
10583 (while (setq entry (pop all))
10584 (if (string-match (car entry) buffer-file-name)
10585 (throw 'exit (cdr entry))))
10586 nil)))))
10588 (defvar org-refile-target-table nil
10589 "The list of refile targets, created by `org-refile'.")
10591 (defvar org-agenda-new-buffers nil
10592 "Buffers created to visit agenda files.")
10594 (defvar org-refile-cache nil
10595 "Cache for refile targets.")
10597 (defvar org-refile-markers nil
10598 "All the markers used for caching refile locations.")
10600 (defun org-refile-marker (pos)
10601 "Get a new refile marker, but only if caching is in use."
10602 (if (not org-refile-use-cache)
10604 (let ((m (make-marker)))
10605 (move-marker m pos)
10606 (push m org-refile-markers)
10607 m)))
10609 (defun org-refile-cache-clear ()
10610 "Clear the refile cache and disable all the markers."
10611 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10612 (setq org-refile-markers nil)
10613 (setq org-refile-cache nil)
10614 (message "Refile cache has been cleared"))
10616 (defun org-refile-cache-check-set (set)
10617 "Check if all the markers in the cache still have live buffers."
10618 (let (marker)
10619 (catch 'exit
10620 (while (and set (setq marker (nth 3 (pop set))))
10621 ;; if org-refile-use-outline-path is 'file, marker may be nil
10622 (when (and marker (null (marker-buffer marker)))
10623 (message "not found") (sit-for 3)
10624 (throw 'exit nil)))
10625 t)))
10627 (defun org-refile-cache-put (set &rest identifiers)
10628 "Push the refile targets SET into the cache, under IDENTIFIERS."
10629 (let* ((key (sha1 (prin1-to-string identifiers)))
10630 (entry (assoc key org-refile-cache)))
10631 (if entry
10632 (setcdr entry set)
10633 (push (cons key set) org-refile-cache))))
10635 (defun org-refile-cache-get (&rest identifiers)
10636 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10637 (cond
10638 ((not org-refile-cache) nil)
10639 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10641 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10642 org-refile-cache))))
10643 (and set (org-refile-cache-check-set set) set)))))
10645 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10646 "Produce a table with refile targets."
10647 (let ((case-fold-search nil)
10648 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10649 (entries (or org-refile-targets '((nil . (:level . 1)))))
10650 targets tgs txt re files f desc descre fast-path-p level pos0)
10651 (message "Getting targets...")
10652 (with-current-buffer (or default-buffer (current-buffer))
10653 (while (setq entry (pop entries))
10654 (setq files (car entry) desc (cdr entry))
10655 (setq fast-path-p nil)
10656 (cond
10657 ((null files) (setq files (list (current-buffer))))
10658 ((eq files 'org-agenda-files)
10659 (setq files (org-agenda-files 'unrestricted)))
10660 ((and (symbolp files) (fboundp files))
10661 (setq files (funcall files)))
10662 ((and (symbolp files) (boundp files))
10663 (setq files (symbol-value files))))
10664 (if (stringp files) (setq files (list files)))
10665 (cond
10666 ((eq (car desc) :tag)
10667 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10668 ((eq (car desc) :todo)
10669 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10670 ((eq (car desc) :regexp)
10671 (setq descre (cdr desc)))
10672 ((eq (car desc) :level)
10673 (setq descre (concat "^\\*\\{" (number-to-string
10674 (if org-odd-levels-only
10675 (1- (* 2 (cdr desc)))
10676 (cdr desc)))
10677 "\\}[ \t]")))
10678 ((eq (car desc) :maxlevel)
10679 (setq fast-path-p t)
10680 (setq descre (concat "^\\*\\{1," (number-to-string
10681 (if org-odd-levels-only
10682 (1- (* 2 (cdr desc)))
10683 (cdr desc)))
10684 "\\}[ \t]")))
10685 (t (error "Bad refiling target description %s" desc)))
10686 (while (setq f (pop files))
10687 (with-current-buffer
10688 (if (bufferp f) f (org-get-agenda-file-buffer f))
10690 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10691 (progn
10692 (if (bufferp f) (setq f (buffer-file-name
10693 (buffer-base-buffer f))))
10694 (setq f (and f (expand-file-name f)))
10695 (if (eq org-refile-use-outline-path 'file)
10696 (push (list (file-name-nondirectory f) f nil nil) tgs))
10697 (save-excursion
10698 (save-restriction
10699 (widen)
10700 (goto-char (point-min))
10701 (while (re-search-forward descre nil t)
10702 (goto-char (setq pos0 (point-at-bol)))
10703 (catch 'next
10704 (when org-refile-target-verify-function
10705 (save-match-data
10706 (or (funcall org-refile-target-verify-function)
10707 (throw 'next t))))
10708 (when (and (looking-at org-complex-heading-regexp)
10709 (not (member (match-string 4) excluded-entries))
10710 (match-string 4))
10711 (setq level (org-reduced-level
10712 (- (match-end 1) (match-beginning 1)))
10713 txt (org-link-display-format (match-string 4))
10714 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10715 re (format org-complex-heading-regexp-format
10716 (regexp-quote (match-string 4))))
10717 (when org-refile-use-outline-path
10718 (setq txt (mapconcat
10719 'org-protect-slash
10720 (append
10721 (if (eq org-refile-use-outline-path
10722 'file)
10723 (list (file-name-nondirectory
10724 (buffer-file-name
10725 (buffer-base-buffer))))
10726 (if (eq org-refile-use-outline-path
10727 'full-file-path)
10728 (list (buffer-file-name
10729 (buffer-base-buffer)))))
10730 (org-get-outline-path fast-path-p
10731 level txt)
10732 (list txt))
10733 "/")))
10734 (push (list txt f re (org-refile-marker (point)))
10735 tgs)))
10736 (when (= (point) pos0)
10737 ;; verification function has not moved point
10738 (goto-char (point-at-eol))))))))
10739 (when org-refile-use-cache
10740 (org-refile-cache-put tgs (buffer-file-name) descre))
10741 (setq targets (append tgs targets))
10742 ))))
10743 (message "Getting targets...done")
10744 (nreverse targets)))
10746 (defun org-protect-slash (s)
10747 (while (string-match "/" s)
10748 (setq s (replace-match "\\" t t s)))
10751 (defvar org-olpa (make-vector 20 nil))
10753 (defun org-get-outline-path (&optional fastp level heading)
10754 "Return the outline path to the current entry, as a list.
10756 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10757 routine which makes outline path derivations for an entire file,
10758 avoiding backtracing. Refile target collection makes use of that."
10759 (if fastp
10760 (progn
10761 (if (> level 19)
10762 (error "Outline path failure, more than 19 levels"))
10763 (loop for i from level upto 19 do
10764 (aset org-olpa i nil))
10765 (prog1
10766 (delq nil (append org-olpa nil))
10767 (aset org-olpa level heading)))
10768 (let (rtn case-fold-search)
10769 (save-excursion
10770 (save-restriction
10771 (widen)
10772 (while (org-up-heading-safe)
10773 (when (looking-at org-complex-heading-regexp)
10774 (push (org-match-string-no-properties 4) rtn)))
10775 rtn)))))
10777 (defun org-format-outline-path (path &optional width prefix)
10778 "Format the outline path PATH for display.
10779 Width is the maximum number of characters that is available.
10780 Prefix is a prefix to be included in the returned string,
10781 such as the file name."
10782 (setq width (or width 79))
10783 (if prefix (setq width (- width (length prefix))))
10784 (if (not path)
10785 (or prefix "")
10786 (let* ((nsteps (length path))
10787 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10788 (maxwidth (if (<= total-width width)
10789 10000 ;; everything fits
10790 ;; we need to shorten the level headings
10791 (/ (- width nsteps) nsteps)))
10792 (org-odd-levels-only nil)
10793 (n 0)
10794 (total (1+ (length prefix))))
10795 (setq maxwidth (max maxwidth 10))
10796 (concat prefix
10797 (mapconcat
10798 (lambda (h)
10799 (setq n (1+ n))
10800 (if (and (= n nsteps) (< maxwidth 10000))
10801 (setq maxwidth (- total-width total)))
10802 (if (< (length h) maxwidth)
10803 (progn (setq total (+ total (length h) 1)) h)
10804 (setq h (substring h 0 (- maxwidth 2))
10805 total (+ total maxwidth 1))
10806 (if (string-match "[ \t]+\\'" h)
10807 (setq h (substring h 0 (match-beginning 0))))
10808 (setq h (concat h "..")))
10809 (org-add-props h nil 'face
10810 (nth (% (1- n) org-n-level-faces)
10811 org-level-faces))
10813 path "/")))))
10815 (defun org-display-outline-path (&optional file current)
10816 "Display the current outline path in the echo area."
10817 (interactive "P")
10818 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10819 (case-fold-search nil)
10820 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10821 (if current (setq path (append path
10822 (save-excursion
10823 (org-back-to-heading t)
10824 (if (looking-at org-complex-heading-regexp)
10825 (list (match-string 4)))))))
10826 (message "%s"
10827 (org-format-outline-path
10828 path
10829 (1- (frame-width))
10830 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10832 (defvar org-refile-history nil
10833 "History for refiling operations.")
10835 (defvar org-after-refile-insert-hook nil
10836 "Hook run after `org-refile' has inserted its stuff at the new location.
10837 Note that this is still *before* the stuff will be removed from
10838 the *old* location.")
10840 (defvar org-capture-last-stored-marker)
10841 (defun org-refile (&optional goto default-buffer rfloc)
10842 "Move the entry or entries at point to another heading.
10843 The list of target headings is compiled using the information in
10844 `org-refile-targets', which see.
10846 At the target location, the entry is filed as a subitem of the target
10847 heading. Depending on `org-reverse-note-order', the new subitem will
10848 either be the first or the last subitem.
10850 If there is an active region, all entries in that region will be moved.
10851 However, the region must fulfill the requirement that the first heading
10852 is the first one sets the top-level of the moved text - at most siblings
10853 below it are allowed.
10855 With prefix arg GOTO, the command will only visit the target location
10856 and not actually move anything.
10858 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10859 go to the location where the last refiling operation has put the subtree.
10860 With a prefix argument of `2', refile to the running clock.
10862 RFLOC can be a refile location obtained in a different way.
10864 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10866 If you are using target caching (see `org-refile-use-cache'),
10867 you have to clear the target cache in order to find new targets.
10868 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10869 prefix argument (`C-u C-u C-u C-c C-w')."
10871 (interactive "P")
10872 (if (member goto '(0 (64)))
10873 (org-refile-cache-clear)
10874 (let* ((cbuf (current-buffer))
10875 (regionp (org-region-active-p))
10876 (region-start (and regionp (region-beginning)))
10877 (region-end (and regionp (region-end)))
10878 (region-length (and regionp (- region-end region-start)))
10879 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10880 pos it nbuf file re level reversed)
10881 (setq last-command nil)
10882 (when regionp
10883 (goto-char region-start)
10884 (or (bolp) (goto-char (point-at-bol)))
10885 (setq region-start (point))
10886 (unless (or (org-kill-is-subtree-p
10887 (buffer-substring region-start region-end))
10888 (prog1 org-refile-active-region-within-subtree
10889 (org-toggle-heading)))
10890 (error "The region is not a (sequence of) subtree(s)")))
10891 (if (equal goto '(16))
10892 (org-refile-goto-last-stored)
10893 (when (or
10894 (and (equal goto 2)
10895 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10896 (prog1
10897 (setq it (list (or org-clock-heading "running clock")
10898 (buffer-file-name
10899 (marker-buffer org-clock-hd-marker))
10901 (marker-position org-clock-hd-marker)))
10902 (setq goto nil)))
10903 (setq it (or rfloc
10904 (let (heading-text)
10905 (save-excursion
10906 (unless goto
10907 (org-back-to-heading t)
10908 (setq heading-text
10909 (nth 4 (org-heading-components))))
10910 (org-refile-get-location
10911 (cond (goto "Goto")
10912 (regionp "Refile region to")
10913 (t (concat "Refile subtree \""
10914 heading-text "\" to")))
10915 default-buffer
10916 (and (not (equal '(4) goto))
10917 org-refile-allow-creating-parent-nodes)
10918 goto))))))
10919 (setq file (nth 1 it)
10920 re (nth 2 it)
10921 pos (nth 3 it))
10922 (if (and (not goto)
10924 (equal (buffer-file-name) file)
10925 (if regionp
10926 (and (>= pos region-start)
10927 (<= pos region-end))
10928 (and (>= pos (point))
10929 (< pos (save-excursion
10930 (org-end-of-subtree t t))))))
10931 (error "Cannot refile to position inside the tree or region"))
10933 (setq nbuf (or (find-buffer-visiting file)
10934 (find-file-noselect file)))
10935 (if goto
10936 (progn
10937 (org-pop-to-buffer-same-window nbuf)
10938 (goto-char pos)
10939 (org-show-context 'org-goto))
10940 (if regionp
10941 (progn
10942 (org-kill-new (buffer-substring region-start region-end))
10943 (org-save-markers-in-region region-start region-end))
10944 (org-copy-subtree 1 nil t))
10945 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10946 (find-file-noselect file)))
10947 (setq reversed (org-notes-order-reversed-p))
10948 (save-excursion
10949 (save-restriction
10950 (widen)
10951 (if pos
10952 (progn
10953 (goto-char pos)
10954 (looking-at org-outline-regexp)
10955 (setq level (org-get-valid-level (funcall outline-level) 1))
10956 (goto-char
10957 (if reversed
10958 (or (outline-next-heading) (point-max))
10959 (or (save-excursion (org-get-next-sibling))
10960 (org-end-of-subtree t t)
10961 (point-max)))))
10962 (setq level 1)
10963 (if (not reversed)
10964 (goto-char (point-max))
10965 (goto-char (point-min))
10966 (or (outline-next-heading) (goto-char (point-max)))))
10967 (if (not (bolp)) (newline))
10968 (org-paste-subtree level)
10969 (when org-log-refile
10970 (org-add-log-setup 'refile nil nil 'findpos
10971 org-log-refile)
10972 (unless (eq org-log-refile 'note)
10973 (save-excursion (org-add-log-note))))
10974 (and org-auto-align-tags
10975 (let ((org-loop-over-headlines-in-active-region nil))
10976 (org-set-tags nil t)))
10977 (bookmark-set "org-refile-last-stored")
10978 ;; If we are refiling for capture, make sure that the
10979 ;; last-capture pointers point here
10980 (when (org-bound-and-true-p org-refile-for-capture)
10981 (bookmark-set "org-capture-last-stored-marker")
10982 (move-marker org-capture-last-stored-marker (point)))
10983 (if (fboundp 'deactivate-mark) (deactivate-mark))
10984 (run-hooks 'org-after-refile-insert-hook))))
10985 (if regionp
10986 (delete-region (point) (+ (point) region-length))
10987 (org-cut-subtree))
10988 (when (featurep 'org-inlinetask)
10989 (org-inlinetask-remove-END-maybe))
10990 (setq org-markers-to-move nil)
10991 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10993 (defun org-refile-goto-last-stored ()
10994 "Go to the location where the last refile was stored."
10995 (interactive)
10996 (bookmark-jump "org-refile-last-stored")
10997 (message "This is the location of the last refile"))
10999 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11000 no-exclude)
11001 "Prompt the user for a refile location, using PROMPT.
11002 PROMPT should not be suffixed with a colon and a space, because
11003 this function appends the default value from
11004 `org-refile-history' automatically, if that is not empty.
11005 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11006 this is used for the GOTO interface."
11007 (let ((org-refile-targets org-refile-targets)
11008 (org-refile-use-outline-path org-refile-use-outline-path)
11009 excluded-entries)
11010 (when (and (derived-mode-p 'org-mode)
11011 (not org-refile-use-cache)
11012 (not no-exclude))
11013 (org-map-tree
11014 (lambda()
11015 (setq excluded-entries
11016 (append excluded-entries (list (org-get-heading t t)))))))
11017 (setq org-refile-target-table
11018 (org-refile-get-targets default-buffer excluded-entries)))
11019 (unless org-refile-target-table
11020 (error "No refile targets"))
11021 (let* ((prompt (concat prompt
11022 (and (car org-refile-history)
11023 (concat " (default " (car org-refile-history) ")"))
11024 ": "))
11025 (cbuf (current-buffer))
11026 (partial-completion-mode nil)
11027 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11028 (cfunc (if (and org-refile-use-outline-path
11029 org-outline-path-complete-in-steps)
11030 'org-olpath-completing-read
11031 'org-icompleting-read))
11032 (extra (if org-refile-use-outline-path "/" ""))
11033 (filename (and cfn (expand-file-name cfn)))
11034 (tbl (mapcar
11035 (lambda (x)
11036 (if (and (not (member org-refile-use-outline-path
11037 '(file full-file-path)))
11038 (not (equal filename (nth 1 x))))
11039 (cons (concat (car x) extra " ("
11040 (file-name-nondirectory (nth 1 x)) ")")
11041 (cdr x))
11042 (cons (concat (car x) extra) (cdr x))))
11043 org-refile-target-table))
11044 (completion-ignore-case t)
11045 pa answ parent-target child parent old-hist)
11046 (setq old-hist org-refile-history)
11047 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11048 nil 'org-refile-history (car org-refile-history)))
11049 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11050 (org-refile-check-position pa)
11051 (if pa
11052 (progn
11053 (when (or (not org-refile-history)
11054 (not (eq old-hist org-refile-history))
11055 (not (equal (car pa) (car org-refile-history))))
11056 (setq org-refile-history
11057 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11058 org-refile-history
11059 (cdr org-refile-history))))
11060 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11061 (pop org-refile-history)))
11063 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11064 (progn
11065 (setq parent (match-string 1 answ)
11066 child (match-string 2 answ))
11067 (setq parent-target (or (assoc parent tbl)
11068 (assoc (concat parent "/") tbl)))
11069 (when (and parent-target
11070 (or (eq new-nodes t)
11071 (and (eq new-nodes 'confirm)
11072 (y-or-n-p (format "Create new node \"%s\"? "
11073 child)))))
11074 (org-refile-new-child parent-target child)))
11075 (error "Invalid target location")))))
11077 (declare-function org-string-nw-p "org-macs.el" (s))
11078 (defun org-refile-check-position (refile-pointer)
11079 "Check if the refile pointer matches the readline to which it points."
11080 (let* ((file (nth 1 refile-pointer))
11081 (re (nth 2 refile-pointer))
11082 (pos (nth 3 refile-pointer))
11083 buffer)
11084 (when (org-string-nw-p re)
11085 (setq buffer (if (markerp pos)
11086 (marker-buffer pos)
11087 (or (find-buffer-visiting file)
11088 (find-file-noselect file))))
11089 (with-current-buffer buffer
11090 (save-excursion
11091 (save-restriction
11092 (widen)
11093 (goto-char pos)
11094 (beginning-of-line 1)
11095 (unless (org-looking-at-p re)
11096 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11098 (defun org-refile-new-child (parent-target child)
11099 "Use refile target PARENT-TARGET to add new CHILD below it."
11100 (unless parent-target
11101 (error "Cannot find parent for new node"))
11102 (let ((file (nth 1 parent-target))
11103 (pos (nth 3 parent-target))
11104 level)
11105 (with-current-buffer (or (find-buffer-visiting file)
11106 (find-file-noselect file))
11107 (save-excursion
11108 (save-restriction
11109 (widen)
11110 (if pos
11111 (goto-char pos)
11112 (goto-char (point-max))
11113 (if (not (bolp)) (newline)))
11114 (when (looking-at org-outline-regexp)
11115 (setq level (funcall outline-level))
11116 (org-end-of-subtree t t))
11117 (org-back-over-empty-lines)
11118 (insert "\n" (make-string
11119 (if pos (org-get-valid-level level 1) 1) ?*)
11120 " " child "\n")
11121 (beginning-of-line 0)
11122 (list (concat (car parent-target) "/" child) file "" (point)))))))
11124 (defun org-olpath-completing-read (prompt collection &rest args)
11125 "Read an outline path like a file name."
11126 (let ((thetable collection)
11127 (org-completion-use-ido nil) ; does not work with ido.
11128 (org-completion-use-iswitchb nil)) ; or iswitchb
11129 (apply
11130 'org-icompleting-read prompt
11131 (lambda (string predicate &optional flag)
11132 (let (rtn r f (l (length string)))
11133 (cond
11134 ((eq flag nil)
11135 ;; try completion
11136 (try-completion string thetable))
11137 ((eq flag t)
11138 ;; all-completions
11139 (setq rtn (all-completions string thetable predicate))
11140 (mapcar
11141 (lambda (x)
11142 (setq r (substring x l))
11143 (if (string-match " ([^)]*)$" x)
11144 (setq f (match-string 0 x))
11145 (setq f ""))
11146 (if (string-match "/" r)
11147 (concat string (substring r 0 (match-end 0)) f)
11149 rtn))
11150 ((eq flag 'lambda)
11151 ;; exact match?
11152 (assoc string thetable)))))
11153 args)))
11155 ;;;; Dynamic blocks
11157 (defun org-find-dblock (name)
11158 "Find the first dynamic block with name NAME in the buffer.
11159 If not found, stay at current position and return nil."
11160 (let (pos)
11161 (save-excursion
11162 (goto-char (point-min))
11163 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11164 nil t)
11165 (match-beginning 0))))
11166 (if pos (goto-char pos))
11167 pos))
11169 (defconst org-dblock-start-re
11170 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11171 "Matches the start line of a dynamic block, with parameters.")
11173 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11174 "Matches the end of a dynamic block.")
11176 (defun org-create-dblock (plist)
11177 "Create a dynamic block section, with parameters taken from PLIST.
11178 PLIST must contain a :name entry which is used as name of the block."
11179 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11180 (end-of-line 1)
11181 (newline))
11182 (let ((col (current-column))
11183 (name (plist-get plist :name)))
11184 (insert "#+BEGIN: " name)
11185 (while plist
11186 (if (eq (car plist) :name)
11187 (setq plist (cddr plist))
11188 (insert " " (prin1-to-string (pop plist)))))
11189 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11190 (beginning-of-line -2)))
11192 (defun org-prepare-dblock ()
11193 "Prepare dynamic block for refresh.
11194 This empties the block, puts the cursor at the insert position and returns
11195 the property list including an extra property :name with the block name."
11196 (unless (looking-at org-dblock-start-re)
11197 (error "Not at a dynamic block"))
11198 (let* ((begdel (1+ (match-end 0)))
11199 (name (org-no-properties (match-string 1)))
11200 (params (append (list :name name)
11201 (read (concat "(" (match-string 3) ")")))))
11202 (save-excursion
11203 (beginning-of-line 1)
11204 (skip-chars-forward " \t")
11205 (setq params (plist-put params :indentation-column (current-column))))
11206 (unless (re-search-forward org-dblock-end-re nil t)
11207 (error "Dynamic block not terminated"))
11208 (setq params
11209 (append params
11210 (list :content (buffer-substring
11211 begdel (match-beginning 0)))))
11212 (delete-region begdel (match-beginning 0))
11213 (goto-char begdel)
11214 (open-line 1)
11215 params))
11217 (defun org-map-dblocks (&optional command)
11218 "Apply COMMAND to all dynamic blocks in the current buffer.
11219 If COMMAND is not given, use `org-update-dblock'."
11220 (let ((cmd (or command 'org-update-dblock)))
11221 (save-excursion
11222 (goto-char (point-min))
11223 (while (re-search-forward org-dblock-start-re nil t)
11224 (goto-char (match-beginning 0))
11225 (save-excursion
11226 (condition-case nil
11227 (funcall cmd)
11228 (error (message "Error during update of dynamic block"))))
11229 (unless (re-search-forward org-dblock-end-re nil t)
11230 (error "Dynamic block not terminated"))))))
11232 (defun org-dblock-update (&optional arg)
11233 "User command for updating dynamic blocks.
11234 Update the dynamic block at point. With prefix ARG, update all dynamic
11235 blocks in the buffer."
11236 (interactive "P")
11237 (if arg
11238 (org-update-all-dblocks)
11239 (or (looking-at org-dblock-start-re)
11240 (org-beginning-of-dblock))
11241 (org-update-dblock)))
11243 (defun org-update-dblock ()
11244 "Update the dynamic block at point.
11245 This means to empty the block, parse for parameters and then call
11246 the correct writing function."
11247 (interactive)
11248 (save-window-excursion
11249 (let* ((pos (point))
11250 (line (org-current-line))
11251 (params (org-prepare-dblock))
11252 (name (plist-get params :name))
11253 (indent (plist-get params :indentation-column))
11254 (cmd (intern (concat "org-dblock-write:" name))))
11255 (message "Updating dynamic block `%s' at line %d..." name line)
11256 (funcall cmd params)
11257 (message "Updating dynamic block `%s' at line %d...done" name line)
11258 (goto-char pos)
11259 (when (and indent (> indent 0))
11260 (setq indent (make-string indent ?\ ))
11261 (save-excursion
11262 (org-beginning-of-dblock)
11263 (forward-line 1)
11264 (while (not (looking-at org-dblock-end-re))
11265 (insert indent)
11266 (beginning-of-line 2))
11267 (when (looking-at org-dblock-end-re)
11268 (and (looking-at "[ \t]+")
11269 (replace-match ""))
11270 (insert indent)))))))
11272 (defun org-beginning-of-dblock ()
11273 "Find the beginning of the dynamic block at point.
11274 Error if there is no such block at point."
11275 (let ((pos (point))
11276 beg)
11277 (end-of-line 1)
11278 (if (and (re-search-backward org-dblock-start-re nil t)
11279 (setq beg (match-beginning 0))
11280 (re-search-forward org-dblock-end-re nil t)
11281 (> (match-end 0) pos))
11282 (goto-char beg)
11283 (goto-char pos)
11284 (error "Not in a dynamic block"))))
11286 ;;;###autoload
11287 (defun org-update-all-dblocks ()
11288 "Update all dynamic blocks in the buffer.
11289 This function can be used in a hook."
11290 (interactive)
11291 (when (derived-mode-p 'org-mode)
11292 (org-map-dblocks 'org-update-dblock)))
11295 ;;;; Completion
11297 (defconst org-additional-option-like-keywords
11298 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11299 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11300 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11301 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11302 "BEGIN:" "END:"
11303 "ORGTBL" "TBLFM:" "TBLNAME:"
11304 "BEGIN_EXAMPLE" "END_EXAMPLE"
11305 "BEGIN_VERBATIM" "END_VERBATIM"
11306 "BEGIN_QUOTE" "END_QUOTE"
11307 "BEGIN_VERSE" "END_VERSE"
11308 "BEGIN_CENTER" "END_CENTER"
11309 "BEGIN_SRC" "END_SRC"
11310 "BEGIN_RESULT" "END_RESULT"
11311 "BEGIN_lstlisting" "END_lstlisting"
11312 "NAME:" "RESULTS:"
11313 "HEADER:" "HEADERS:"
11314 "COLUMNS:" "PROPERTY:"
11315 "CAPTION:" "LABEL:"
11316 "SETUPFILE:"
11317 "INCLUDE:"
11318 "BIND:"
11319 "MACRO:"))
11321 (defconst org-options-keywords
11322 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11323 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11324 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11325 "LINK_UP:" "LINK_HOME:" "LINK:"
11326 "XSLT:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11327 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11328 "FILETAGS:" "ARCHIVE:"))
11330 (defconst org-additional-option-like-keywords-for-flyspell
11331 (delete-dups
11332 (split-string
11333 (mapconcat (lambda(k)
11334 (replace-regexp-in-string
11335 "_\\|:" " "
11336 (concat k " " (downcase k) " " (upcase k))))
11337 (append org-options-keywords org-additional-option-like-keywords)
11338 " ")
11339 " +" t)))
11341 (defcustom org-structure-template-alist
11343 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11344 "<src lang=\"?\">\n\n</src>")
11345 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11346 "<example>\n?\n</example>")
11347 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11348 "<quote>\n?\n</quote>")
11349 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11350 "<verse>\n?\n</verse>")
11351 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11352 "<center>\n?\n</center>")
11353 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11354 "<literal style=\"latex\">\n?\n</literal>")
11355 ("L" "#+LaTeX: "
11356 "<literal style=\"latex\">?</literal>")
11357 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11358 "<literal style=\"html\">\n?\n</literal>")
11359 ("H" "#+HTML: "
11360 "<literal style=\"html\">?</literal>")
11361 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11362 ("A" "#+ASCII: ")
11363 ("i" "#+INDEX: ?"
11364 "#+INDEX: ?")
11365 ("I" "#+INCLUDE %file ?"
11366 "<include file=%file markup=\"?\">")
11368 "Structure completion elements.
11369 This is a list of abbreviation keys and values. The value gets inserted
11370 if you type `<' followed by the key and then press the completion key,
11371 usually `M-TAB'. %file will be replaced by a file name after prompting
11372 for the file using completion. The cursor will be placed at the position
11373 of the `?` in the template.
11374 There are two templates for each key, the first uses the original Org syntax,
11375 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11376 the default when the /org-mtags.el/ module has been loaded. See also the
11377 variable `org-mtags-prefer-muse-templates'."
11378 :group 'org-completion
11379 :type '(repeat
11380 (string :tag "Key")
11381 (string :tag "Template")
11382 (string :tag "Muse Template")))
11384 (defun org-try-structure-completion ()
11385 "Try to complete a structure template before point.
11386 This looks for strings like \"<e\" on an otherwise empty line and
11387 expands them."
11388 (let ((l (buffer-substring (point-at-bol) (point)))
11390 (when (and (looking-at "[ \t]*$")
11391 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11392 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11393 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11394 (match-beginning 1)) a)
11395 t)))
11397 (defun org-complete-expand-structure-template (start cell)
11398 "Expand a structure template."
11399 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11400 (rpl (nth (if musep 2 1) cell))
11401 (ind ""))
11402 (delete-region start (point))
11403 (when (string-match "\\`#\\+" rpl)
11404 (cond
11405 ((bolp))
11406 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11407 (setq ind (buffer-substring (point-at-bol) (point))))
11408 (t (newline))))
11409 (setq start (point))
11410 (if (string-match "%file" rpl)
11411 (setq rpl (replace-match
11412 (concat
11413 "\""
11414 (save-match-data
11415 (abbreviate-file-name (read-file-name "Include file: ")))
11416 "\"")
11417 t t rpl)))
11418 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11419 (concat "\n" ind)))
11420 (insert rpl)
11421 (if (re-search-backward "\\?" start t) (delete-char 1))))
11423 ;;;; TODO, DEADLINE, Comments
11425 (defun org-toggle-comment ()
11426 "Change the COMMENT state of an entry."
11427 (interactive)
11428 (save-excursion
11429 (org-back-to-heading)
11430 (let (case-fold-search)
11431 (cond
11432 ((looking-at (format org-heading-keyword-regexp-format
11433 org-comment-string))
11434 (goto-char (match-end 1))
11435 (looking-at (concat " +" org-comment-string))
11436 (replace-match "" t t)
11437 (when (eolp) (insert " ")))
11438 ((looking-at org-outline-regexp)
11439 (goto-char (match-end 0))
11440 (insert org-comment-string " "))))))
11442 (defvar org-last-todo-state-is-todo nil
11443 "This is non-nil when the last TODO state change led to a TODO state.
11444 If the last change removed the TODO tag or switched to DONE, then
11445 this is nil.")
11447 (defvar org-setting-tags nil) ; dynamically skipped
11449 (defvar org-todo-setup-filter-hook nil
11450 "Hook for functions that pre-filter todo specs.
11451 Each function takes a todo spec and returns either nil or the spec
11452 transformed into canonical form." )
11454 (defvar org-todo-get-default-hook nil
11455 "Hook for functions that get a default item for todo.
11456 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11457 nil or a string to be used for the todo mark." )
11459 (defvar org-agenda-headline-snapshot-before-repeat)
11461 (defun org-current-effective-time ()
11462 "Return current time adjusted for `org-extend-today-until' variable."
11463 (let* ((ct (org-current-time))
11464 (dct (decode-time ct))
11465 (ct1
11466 (if (and org-use-effective-time
11467 (< (nth 2 dct) org-extend-today-until))
11468 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11469 ct)))
11470 ct1))
11472 (defun org-todo-yesterday (&optional arg)
11473 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11474 (interactive "P")
11475 (if (eq major-mode 'org-agenda-mode)
11476 (apply 'org-agenda-todo-yesterday arg)
11477 (let* ((hour (third (decode-time
11478 (org-current-time))))
11479 (org-extend-today-until (1+ hour)))
11480 (org-todo arg))))
11482 (defun org-todo (&optional arg)
11483 "Change the TODO state of an item.
11484 The state of an item is given by a keyword at the start of the heading,
11485 like
11486 *** TODO Write paper
11487 *** DONE Call mom
11489 The different keywords are specified in the variable `org-todo-keywords'.
11490 By default the available states are \"TODO\" and \"DONE\".
11491 So for this example: when the item starts with TODO, it is changed to DONE.
11492 When it starts with DONE, the DONE is removed. And when neither TODO nor
11493 DONE are present, add TODO at the beginning of the heading.
11495 With \\[universal-argument] prefix arg, use completion to determine the new \
11496 state.
11497 With numeric prefix arg, switch to that state.
11498 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11499 keywords (nextset).
11500 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11501 With a numeric prefix arg of 0, inhibit note taking for the change.
11503 For calling through lisp, arg is also interpreted in the following way:
11504 'none -> empty state
11505 \"\"(empty string) -> switch to empty state
11506 'done -> switch to DONE
11507 'nextset -> switch to the next set of keywords
11508 'previousset -> switch to the previous set of keywords
11509 \"WAITING\" -> switch to the specified keyword, but only if it
11510 really is a member of `org-todo-keywords'."
11511 (interactive "P")
11512 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11513 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11514 'region-start-level 'region))
11515 org-loop-over-headlines-in-active-region)
11516 (org-map-entries
11517 `(org-todo ,arg)
11518 org-loop-over-headlines-in-active-region
11519 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11520 (if (equal arg '(16)) (setq arg 'nextset))
11521 (let ((org-blocker-hook org-blocker-hook)
11522 (case-fold-search nil))
11523 (when (equal arg '(64))
11524 (setq arg nil org-blocker-hook nil))
11525 (when (and org-blocker-hook
11526 (or org-inhibit-blocking
11527 (org-entry-get nil "NOBLOCKING")))
11528 (setq org-blocker-hook nil))
11529 (save-excursion
11530 (catch 'exit
11531 (org-back-to-heading t)
11532 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11533 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11534 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11535 (let* ((match-data (match-data))
11536 (startpos (point-at-bol))
11537 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11538 (org-log-done org-log-done)
11539 (org-log-repeat org-log-repeat)
11540 (org-todo-log-states org-todo-log-states)
11541 (org-inhibit-logging
11542 (if (equal arg 0)
11543 (progn (setq arg nil) 'note) org-inhibit-logging))
11544 (this (match-string 1))
11545 (hl-pos (match-beginning 0))
11546 (head (org-get-todo-sequence-head this))
11547 (ass (assoc head org-todo-kwd-alist))
11548 (interpret (nth 1 ass))
11549 (done-word (nth 3 ass))
11550 (final-done-word (nth 4 ass))
11551 (org-last-state (or this ""))
11552 (completion-ignore-case t)
11553 (member (member this org-todo-keywords-1))
11554 (tail (cdr member))
11555 (org-state (cond
11556 ((and org-todo-key-trigger
11557 (or (and (equal arg '(4))
11558 (eq org-use-fast-todo-selection 'prefix))
11559 (and (not arg) org-use-fast-todo-selection
11560 (not (eq org-use-fast-todo-selection
11561 'prefix)))))
11562 ;; Use fast selection
11563 (org-fast-todo-selection))
11564 ((and (equal arg '(4))
11565 (or (not org-use-fast-todo-selection)
11566 (not org-todo-key-trigger)))
11567 ;; Read a state with completion
11568 (org-icompleting-read
11569 "State: " (mapcar (lambda(x) (list x))
11570 org-todo-keywords-1)
11571 nil t))
11572 ((eq arg 'right)
11573 (if this
11574 (if tail (car tail) nil)
11575 (car org-todo-keywords-1)))
11576 ((eq arg 'left)
11577 (if (equal member org-todo-keywords-1)
11579 (if this
11580 (nth (- (length org-todo-keywords-1)
11581 (length tail) 2)
11582 org-todo-keywords-1)
11583 (org-last org-todo-keywords-1))))
11584 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11585 (setq arg nil))) ; hack to fall back to cycling
11586 (arg
11587 ;; user or caller requests a specific state
11588 (cond
11589 ((equal arg "") nil)
11590 ((eq arg 'none) nil)
11591 ((eq arg 'done) (or done-word (car org-done-keywords)))
11592 ((eq arg 'nextset)
11593 (or (car (cdr (member head org-todo-heads)))
11594 (car org-todo-heads)))
11595 ((eq arg 'previousset)
11596 (let ((org-todo-heads (reverse org-todo-heads)))
11597 (or (car (cdr (member head org-todo-heads)))
11598 (car org-todo-heads))))
11599 ((car (member arg org-todo-keywords-1)))
11600 ((stringp arg)
11601 (error "State `%s' not valid in this file" arg))
11602 ((nth (1- (prefix-numeric-value arg))
11603 org-todo-keywords-1))))
11604 ((null member) (or head (car org-todo-keywords-1)))
11605 ((equal this final-done-word) nil) ;; -> make empty
11606 ((null tail) nil) ;; -> first entry
11607 ((memq interpret '(type priority))
11608 (if (eq this-command last-command)
11609 (car tail)
11610 (if (> (length tail) 0)
11611 (or done-word (car org-done-keywords))
11612 nil)))
11614 (car tail))))
11615 (org-state (or
11616 (run-hook-with-args-until-success
11617 'org-todo-get-default-hook org-state org-last-state)
11618 org-state))
11619 (next (if org-state (concat " " org-state " ") " "))
11620 (change-plist (list :type 'todo-state-change :from this :to org-state
11621 :position startpos))
11622 dolog now-done-p)
11623 (when org-blocker-hook
11624 (setq org-last-todo-state-is-todo
11625 (not (member this org-done-keywords)))
11626 (unless (save-excursion
11627 (save-match-data
11628 (org-with-wide-buffer
11629 (run-hook-with-args-until-failure
11630 'org-blocker-hook change-plist))))
11631 (if (org-called-interactively-p 'interactive)
11632 (error "TODO state change from %s to %s blocked" this org-state)
11633 ;; fail silently
11634 (message "TODO state change from %s to %s blocked" this org-state)
11635 (throw 'exit nil))))
11636 (store-match-data match-data)
11637 (replace-match next t t)
11638 (unless (pos-visible-in-window-p hl-pos)
11639 (message "TODO state changed to %s" (org-trim next)))
11640 (unless head
11641 (setq head (org-get-todo-sequence-head org-state)
11642 ass (assoc head org-todo-kwd-alist)
11643 interpret (nth 1 ass)
11644 done-word (nth 3 ass)
11645 final-done-word (nth 4 ass)))
11646 (when (memq arg '(nextset previousset))
11647 (message "Keyword-Set %d/%d: %s"
11648 (- (length org-todo-sets) -1
11649 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11650 (length org-todo-sets)
11651 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11652 (setq org-last-todo-state-is-todo
11653 (not (member org-state org-done-keywords)))
11654 (setq now-done-p (and (member org-state org-done-keywords)
11655 (not (member this org-done-keywords))))
11656 (and logging (org-local-logging logging))
11657 (when (and (or org-todo-log-states org-log-done)
11658 (not (eq org-inhibit-logging t))
11659 (not (memq arg '(nextset previousset))))
11660 ;; we need to look at recording a time and note
11661 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11662 (nth 2 (assoc this org-todo-log-states))))
11663 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11664 (setq dolog 'time))
11665 (when (and org-state
11666 (member org-state org-not-done-keywords)
11667 (not (member this org-not-done-keywords)))
11668 ;; This is now a todo state and was not one before
11669 ;; If there was a CLOSED time stamp, get rid of it.
11670 (org-add-planning-info nil nil 'closed))
11671 (when (and now-done-p org-log-done)
11672 ;; It is now done, and it was not done before
11673 (org-add-planning-info 'closed (org-current-effective-time))
11674 (if (and (not dolog) (eq 'note org-log-done))
11675 (org-add-log-setup 'done org-state this 'findpos 'note)))
11676 (when (and org-state dolog)
11677 ;; This is a non-nil state, and we need to log it
11678 (org-add-log-setup 'state org-state this 'findpos dolog)))
11679 ;; Fixup tag positioning
11680 (org-todo-trigger-tag-changes org-state)
11681 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11682 (when org-provide-todo-statistics
11683 (org-update-parent-todo-statistics))
11684 (run-hooks 'org-after-todo-state-change-hook)
11685 (if (and arg (not (member org-state org-done-keywords)))
11686 (setq head (org-get-todo-sequence-head org-state)))
11687 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11688 ;; Do we need to trigger a repeat?
11689 (when now-done-p
11690 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11691 ;; This is for the agenda, take a snapshot of the headline.
11692 (save-match-data
11693 (setq org-agenda-headline-snapshot-before-repeat
11694 (org-get-heading))))
11695 (org-auto-repeat-maybe org-state))
11696 ;; Fixup cursor location if close to the keyword
11697 (if (and (outline-on-heading-p)
11698 (not (bolp))
11699 (save-excursion (beginning-of-line 1)
11700 (looking-at org-todo-line-regexp))
11701 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11702 (progn
11703 (goto-char (or (match-end 2) (match-end 1)))
11704 (and (looking-at " ") (just-one-space))))
11705 (when org-trigger-hook
11706 (save-excursion
11707 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11709 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11710 "Block turning an entry into a TODO, using the hierarchy.
11711 This checks whether the current task should be blocked from state
11712 changes. Such blocking occurs when:
11714 1. The task has children which are not all in a completed state.
11716 2. A task has a parent with the property :ORDERED:, and there
11717 are siblings prior to the current task with incomplete
11718 status.
11720 3. The parent of the task is blocked because it has siblings that should
11721 be done first, or is child of a block grandparent TODO entry."
11723 (if (not org-enforce-todo-dependencies)
11724 t ; if locally turned off don't block
11725 (catch 'dont-block
11726 ;; If this is not a todo state change, or if this entry is already DONE,
11727 ;; do not block
11728 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11729 (member (plist-get change-plist :from)
11730 (cons 'done org-done-keywords))
11731 (member (plist-get change-plist :to)
11732 (cons 'todo org-not-done-keywords))
11733 (not (plist-get change-plist :to)))
11734 (throw 'dont-block t))
11735 ;; If this task has children, and any are undone, it's blocked
11736 (save-excursion
11737 (org-back-to-heading t)
11738 (let ((this-level (funcall outline-level)))
11739 (outline-next-heading)
11740 (let ((child-level (funcall outline-level)))
11741 (while (and (not (eobp))
11742 (> child-level this-level))
11743 ;; this todo has children, check whether they are all
11744 ;; completed
11745 (if (and (not (org-entry-is-done-p))
11746 (org-entry-is-todo-p))
11747 (throw 'dont-block nil))
11748 (outline-next-heading)
11749 (setq child-level (funcall outline-level))))))
11750 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11751 ;; any previous siblings are undone, it's blocked
11752 (save-excursion
11753 (org-back-to-heading t)
11754 (let* ((pos (point))
11755 (parent-pos (and (org-up-heading-safe) (point))))
11756 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11757 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11758 (forward-line 1)
11759 (re-search-forward org-not-done-heading-regexp pos t))
11760 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11761 ;; Search further up the hierarchy, to see if an ancestor is blocked
11762 (while t
11763 (goto-char parent-pos)
11764 (if (not (looking-at org-not-done-heading-regexp))
11765 (throw 'dont-block t)) ; do not block, parent is not a TODO
11766 (setq pos (point))
11767 (setq parent-pos (and (org-up-heading-safe) (point)))
11768 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11769 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11770 (forward-line 1)
11771 (re-search-forward org-not-done-heading-regexp pos t))
11772 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11774 (defcustom org-track-ordered-property-with-tag nil
11775 "Should the ORDERED property also be shown as a tag?
11776 The ORDERED property decides if an entry should require subtasks to be
11777 completed in sequence. Since a property is not very visible, setting
11778 this option means that toggling the ORDERED property with the command
11779 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11780 not relevant for the behavior, but it makes things more visible.
11782 Note that toggling the tag with tags commands will not change the property
11783 and therefore not influence behavior!
11785 This can be t, meaning the tag ORDERED should be used, It can also be a
11786 string to select a different tag for this task."
11787 :group 'org-todo
11788 :type '(choice
11789 (const :tag "No tracking" nil)
11790 (const :tag "Track with ORDERED tag" t)
11791 (string :tag "Use other tag")))
11793 (defun org-toggle-ordered-property ()
11794 "Toggle the ORDERED property of the current entry.
11795 For better visibility, you can track the value of this property with a tag.
11796 See variable `org-track-ordered-property-with-tag'."
11797 (interactive)
11798 (let* ((t1 org-track-ordered-property-with-tag)
11799 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11800 (save-excursion
11801 (org-back-to-heading)
11802 (if (org-entry-get nil "ORDERED")
11803 (progn
11804 (org-delete-property "ORDERED")
11805 (and tag (org-toggle-tag tag 'off))
11806 (message "Subtasks can be completed in arbitrary order"))
11807 (org-entry-put nil "ORDERED" "t")
11808 (and tag (org-toggle-tag tag 'on))
11809 (message "Subtasks must be completed in sequence")))))
11811 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11812 (defun org-block-todo-from-checkboxes (change-plist)
11813 "Block turning an entry into a TODO, using checkboxes.
11814 This checks whether the current task should be blocked from state
11815 changes because there are unchecked boxes in this entry."
11816 (if (not org-enforce-todo-checkbox-dependencies)
11817 t ; if locally turned off don't block
11818 (catch 'dont-block
11819 ;; If this is not a todo state change, or if this entry is already DONE,
11820 ;; do not block
11821 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11822 (member (plist-get change-plist :from)
11823 (cons 'done org-done-keywords))
11824 (member (plist-get change-plist :to)
11825 (cons 'todo org-not-done-keywords))
11826 (not (plist-get change-plist :to)))
11827 (throw 'dont-block t))
11828 ;; If this task has checkboxes that are not checked, it's blocked
11829 (save-excursion
11830 (org-back-to-heading t)
11831 (let ((beg (point)) end)
11832 (outline-next-heading)
11833 (setq end (point))
11834 (goto-char beg)
11835 (if (org-list-search-forward
11836 (concat (org-item-beginning-re)
11837 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11838 "\\[[- ]\\]")
11839 end t)
11840 (progn
11841 (if (boundp 'org-blocked-by-checkboxes)
11842 (setq org-blocked-by-checkboxes t))
11843 (throw 'dont-block nil)))))
11844 t))) ; do not block
11846 (defun org-entry-blocked-p ()
11847 "Is the current entry blocked?"
11848 (if (org-entry-get nil "NOBLOCKING")
11849 nil ;; Never block this entry
11850 (not
11851 (run-hook-with-args-until-failure
11852 'org-blocker-hook
11853 (list :type 'todo-state-change
11854 :position (point)
11855 :from 'todo
11856 :to 'done)))))
11858 (defun org-update-statistics-cookies (all)
11859 "Update the statistics cookie, either from TODO or from checkboxes.
11860 This should be called with the cursor in a line with a statistics cookie."
11861 (interactive "P")
11862 (if all
11863 (progn
11864 (org-update-checkbox-count 'all)
11865 (org-map-entries 'org-update-parent-todo-statistics))
11866 (if (not (org-at-heading-p))
11867 (org-update-checkbox-count)
11868 (let ((pos (move-marker (make-marker) (point)))
11869 end l1 l2)
11870 (ignore-errors (org-back-to-heading t))
11871 (if (not (org-at-heading-p))
11872 (org-update-checkbox-count)
11873 (setq l1 (org-outline-level))
11874 (setq end (save-excursion
11875 (outline-next-heading)
11876 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11877 (point)))
11878 (if (and (save-excursion
11879 (re-search-forward
11880 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11881 (not (save-excursion (re-search-forward
11882 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11883 (org-update-checkbox-count)
11884 (if (and l2 (> l2 l1))
11885 (progn
11886 (goto-char end)
11887 (org-update-parent-todo-statistics))
11888 (goto-char pos)
11889 (beginning-of-line 1)
11890 (while (re-search-forward
11891 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11892 (point-at-eol) t)
11893 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11894 (goto-char pos)
11895 (move-marker pos nil)))))
11897 (defvar org-entry-property-inherited-from) ;; defined below
11898 (defun org-update-parent-todo-statistics ()
11899 "Update any statistics cookie in the parent of the current headline.
11900 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11901 the entire subtree and this will travel up the hierarchy and update
11902 statistics everywhere."
11903 (let* ((prop (save-excursion (org-up-heading-safe)
11904 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11905 (recursive (or (not org-hierarchical-todo-statistics)
11906 (and prop (string-match "\\<recursive\\>" prop))))
11907 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11909 (first t)
11910 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11911 level ltoggle l1 new ndel
11912 (cnt-all 0) (cnt-done 0) is-percent kwd
11913 checkbox-beg ov ovs ove cookie-present)
11914 (catch 'exit
11915 (save-excursion
11916 (beginning-of-line 1)
11917 (setq ltoggle (funcall outline-level))
11918 ;; Three situations are to consider:
11920 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11921 ;; to the top-level ancestor on the headline;
11923 ;; 2. If parent has "recursive" property, repeat up to the
11924 ;; headline setting that property, taking inheritance into
11925 ;; account;
11927 ;; 3. Else, move up to direct parent and proceed only once.
11928 (while (and (setq level (org-up-heading-safe))
11929 (or recursive first)
11930 (>= (point) lim))
11931 (setq first nil cookie-present nil)
11932 (unless (and level
11933 (not (string-match
11934 "\\<checkbox\\>"
11935 (downcase (or (org-entry-get nil "COOKIE_DATA")
11936 "")))))
11937 (throw 'exit nil))
11938 (while (re-search-forward box-re (point-at-eol) t)
11939 (setq cnt-all 0 cnt-done 0 cookie-present t)
11940 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11941 (save-match-data
11942 (unless (outline-next-heading) (throw 'exit nil))
11943 (while (and (looking-at org-complex-heading-regexp)
11944 (> (setq l1 (length (match-string 1))) level))
11945 (setq kwd (and (or recursive (= l1 ltoggle))
11946 (match-string 2)))
11947 (if (or (eq org-provide-todo-statistics 'all-headlines)
11948 (and (listp org-provide-todo-statistics)
11949 (or (member kwd org-provide-todo-statistics)
11950 (member kwd org-done-keywords))))
11951 (setq cnt-all (1+ cnt-all))
11952 (if (eq org-provide-todo-statistics t)
11953 (and kwd (setq cnt-all (1+ cnt-all)))))
11954 (and (member kwd org-done-keywords)
11955 (setq cnt-done (1+ cnt-done)))
11956 (outline-next-heading)))
11957 (setq new
11958 (if is-percent
11959 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11960 (format "[%d/%d]" cnt-done cnt-all))
11961 ndel (- (match-end 0) checkbox-beg))
11962 ;; handle overlays when updating cookie from column view
11963 (when (setq ov (car (overlays-at checkbox-beg)))
11964 (setq ovs (overlay-start ov) ove (overlay-end ov))
11965 (delete-overlay ov))
11966 (goto-char checkbox-beg)
11967 (insert new)
11968 (delete-region (point) (+ (point) ndel))
11969 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11970 (when ov (move-overlay ov ovs ove)))
11971 (when cookie-present
11972 (run-hook-with-args 'org-after-todo-statistics-hook
11973 cnt-done (- cnt-all cnt-done))))))
11974 (run-hooks 'org-todo-statistics-hook)))
11976 (defvar org-after-todo-statistics-hook nil
11977 "Hook that is called after a TODO statistics cookie has been updated.
11978 Each function is called with two arguments: the number of not-done entries
11979 and the number of done entries.
11981 For example, the following function, when added to this hook, will switch
11982 an entry to DONE when all children are done, and back to TODO when new
11983 entries are set to a TODO status. Note that this hook is only called
11984 when there is a statistics cookie in the headline!
11986 (defun org-summary-todo (n-done n-not-done)
11987 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11988 (let (org-log-done org-log-states) ; turn off logging
11989 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11992 (defvar org-todo-statistics-hook nil
11993 "Hook that is run whenever Org thinks TODO statistics should be updated.
11994 This hook runs even if there is no statistics cookie present, in which case
11995 `org-after-todo-statistics-hook' would not run.")
11997 (defun org-todo-trigger-tag-changes (state)
11998 "Apply the changes defined in `org-todo-state-tags-triggers'."
11999 (let ((l org-todo-state-tags-triggers)
12000 changes)
12001 (when (or (not state) (equal state ""))
12002 (setq changes (append changes (cdr (assoc "" l)))))
12003 (when (and (stringp state) (> (length state) 0))
12004 (setq changes (append changes (cdr (assoc state l)))))
12005 (when (member state org-not-done-keywords)
12006 (setq changes (append changes (cdr (assoc 'todo l)))))
12007 (when (member state org-done-keywords)
12008 (setq changes (append changes (cdr (assoc 'done l)))))
12009 (dolist (c changes)
12010 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12012 (defun org-local-logging (value)
12013 "Get logging settings from a property VALUE."
12014 (let* (words w a)
12015 ;; directly set the variables, they are already local.
12016 (setq org-log-done nil
12017 org-log-repeat nil
12018 org-todo-log-states nil)
12019 (setq words (org-split-string value))
12020 (while (setq w (pop words))
12021 (cond
12022 ((setq a (assoc w org-startup-options))
12023 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12024 (set (nth 1 a) (nth 2 a))))
12025 ((setq a (org-extract-log-state-settings w))
12026 (and (member (car a) org-todo-keywords-1)
12027 (push a org-todo-log-states)))))))
12029 (defun org-get-todo-sequence-head (kwd)
12030 "Return the head of the TODO sequence to which KWD belongs.
12031 If KWD is not set, check if there is a text property remembering the
12032 right sequence."
12033 (let (p)
12034 (cond
12035 ((not kwd)
12036 (or (get-text-property (point-at-bol) 'org-todo-head)
12037 (progn
12038 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12039 nil (point-at-eol)))
12040 (get-text-property p 'org-todo-head))))
12041 ((not (member kwd org-todo-keywords-1))
12042 (car org-todo-keywords-1))
12043 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12045 (defun org-fast-todo-selection ()
12046 "Fast TODO keyword selection with single keys.
12047 Returns the new TODO keyword, or nil if no state change should occur."
12048 (let* ((fulltable org-todo-key-alist)
12049 (done-keywords org-done-keywords) ;; needed for the faces.
12050 (maxlen (apply 'max (mapcar
12051 (lambda (x)
12052 (if (stringp (car x)) (string-width (car x)) 0))
12053 fulltable)))
12054 (expert nil)
12055 (fwidth (+ maxlen 3 1 3))
12056 (ncol (/ (- (window-width) 4) fwidth))
12057 tg cnt e c tbl
12058 groups ingroup)
12059 (save-excursion
12060 (save-window-excursion
12061 (if expert
12062 (set-buffer (get-buffer-create " *Org todo*"))
12063 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12064 (erase-buffer)
12065 (org-set-local 'org-done-keywords done-keywords)
12066 (setq tbl fulltable cnt 0)
12067 (while (setq e (pop tbl))
12068 (cond
12069 ((equal e '(:startgroup))
12070 (push '() groups) (setq ingroup t)
12071 (when (not (= cnt 0))
12072 (setq cnt 0)
12073 (insert "\n"))
12074 (insert "{ "))
12075 ((equal e '(:endgroup))
12076 (setq ingroup nil cnt 0)
12077 (insert "}\n"))
12078 ((equal e '(:newline))
12079 (when (not (= cnt 0))
12080 (setq cnt 0)
12081 (insert "\n")
12082 (setq e (car tbl))
12083 (while (equal (car tbl) '(:newline))
12084 (insert "\n")
12085 (setq tbl (cdr tbl)))))
12087 (setq tg (car e) c (cdr e))
12088 (if ingroup (push tg (car groups)))
12089 (setq tg (org-add-props tg nil 'face
12090 (org-get-todo-face tg)))
12091 (if (and (= cnt 0) (not ingroup)) (insert " "))
12092 (insert "[" c "] " tg (make-string
12093 (- fwidth 4 (length tg)) ?\ ))
12094 (when (= (setq cnt (1+ cnt)) ncol)
12095 (insert "\n")
12096 (if ingroup (insert " "))
12097 (setq cnt 0)))))
12098 (insert "\n")
12099 (goto-char (point-min))
12100 (if (not expert) (org-fit-window-to-buffer))
12101 (message "[a-z..]:Set [SPC]:clear")
12102 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12103 (cond
12104 ((or (= c ?\C-g)
12105 (and (= c ?q) (not (rassoc c fulltable))))
12106 (setq quit-flag t))
12107 ((= c ?\ ) nil)
12108 ((setq e (rassoc c fulltable) tg (car e))
12110 (t (setq quit-flag t)))))))
12112 (defun org-entry-is-todo-p ()
12113 (member (org-get-todo-state) org-not-done-keywords))
12115 (defun org-entry-is-done-p ()
12116 (member (org-get-todo-state) org-done-keywords))
12118 (defun org-get-todo-state ()
12119 (save-excursion
12120 (org-back-to-heading t)
12121 (and (looking-at org-todo-line-regexp)
12122 (match-end 2)
12123 (match-string 2))))
12125 (defun org-at-date-range-p (&optional inactive-ok)
12126 "Is the cursor inside a date range?"
12127 (interactive)
12128 (save-excursion
12129 (catch 'exit
12130 (let ((pos (point)))
12131 (skip-chars-backward "^[<\r\n")
12132 (skip-chars-backward "<[")
12133 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12134 (>= (match-end 0) pos)
12135 (throw 'exit t))
12136 (skip-chars-backward "^<[\r\n")
12137 (skip-chars-backward "<[")
12138 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12139 (>= (match-end 0) pos)
12140 (throw 'exit t)))
12141 nil)))
12143 (defun org-get-repeat (&optional tagline)
12144 "Check if there is a deadline/schedule with repeater in this entry."
12145 (save-match-data
12146 (save-excursion
12147 (org-back-to-heading t)
12148 (and (re-search-forward (if tagline
12149 (concat tagline "\\s-*" org-repeat-re)
12150 org-repeat-re)
12151 (org-entry-end-position) t)
12152 (match-string-no-properties 1)))))
12154 (defvar org-last-changed-timestamp)
12155 (defvar org-last-inserted-timestamp)
12156 (defvar org-log-post-message)
12157 (defvar org-log-note-purpose)
12158 (defvar org-log-note-how)
12159 (defvar org-log-note-extra)
12160 (defun org-auto-repeat-maybe (done-word)
12161 "Check if the current headline contains a repeated deadline/schedule.
12162 If yes, set TODO state back to what it was and change the base date
12163 of repeating deadline/scheduled time stamps to new date.
12164 This function is run automatically after each state change to a DONE state."
12165 ;; last-state is dynamically scoped into this function
12166 (let* ((repeat (org-get-repeat))
12167 (aa (assoc org-last-state org-todo-kwd-alist))
12168 (interpret (nth 1 aa))
12169 (head (nth 2 aa))
12170 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12171 (msg "Entry repeats: ")
12172 (org-log-done nil)
12173 (org-todo-log-states nil)
12174 re type n what ts time to-state)
12175 (when repeat
12176 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12177 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12178 org-todo-repeat-to-state))
12179 (unless (and to-state (member to-state org-todo-keywords-1))
12180 (setq to-state (if (eq interpret 'type) org-last-state head)))
12181 (org-todo to-state)
12182 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12183 (org-entry-put nil "LAST_REPEAT" (format-time-string
12184 (org-time-stamp-format t t))))
12185 (when org-log-repeat
12186 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12187 (memq 'org-add-log-note post-command-hook))
12188 ;; OK, we are already setup for some record
12189 (if (eq org-log-repeat 'note)
12190 ;; make sure we take a note, not only a time stamp
12191 (setq org-log-note-how 'note))
12192 ;; Set up for taking a record
12193 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12194 org-last-state
12195 'findpos org-log-repeat)))
12196 (org-back-to-heading t)
12197 (org-add-planning-info nil nil 'closed)
12198 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12199 org-deadline-time-regexp "\\)\\|\\("
12200 org-ts-regexp "\\)"))
12201 (while (re-search-forward
12202 re (save-excursion (outline-next-heading) (point)) t)
12203 (setq type (if (match-end 1) org-scheduled-string
12204 (if (match-end 3) org-deadline-string "Plain:"))
12205 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12206 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12207 (setq n (string-to-number (match-string 2 ts))
12208 what (match-string 3 ts))
12209 (if (equal what "w") (setq n (* n 7) what "d"))
12210 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12211 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12212 ;; Preparation, see if we need to modify the start date for the change
12213 (when (match-end 1)
12214 (setq time (save-match-data (org-time-string-to-time ts)))
12215 (cond
12216 ((equal (match-string 1 ts) ".")
12217 ;; Shift starting date to today
12218 (org-timestamp-change
12219 (- (org-today) (time-to-days time))
12220 'day))
12221 ((equal (match-string 1 ts) "+")
12222 (let ((nshiftmax 10) (nshift 0))
12223 (while (or (= nshift 0)
12224 (<= (time-to-days time)
12225 (time-to-days (current-time))))
12226 (when (= (incf nshift) nshiftmax)
12227 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12228 (error "Abort")))
12229 (org-timestamp-change n (cdr (assoc what whata)))
12230 (org-at-timestamp-p t)
12231 (setq ts (match-string 1))
12232 (setq time (save-match-data (org-time-string-to-time ts)))))
12233 (org-timestamp-change (- n) (cdr (assoc what whata)))
12234 ;; rematch, so that we have everything in place for the real shift
12235 (org-at-timestamp-p t)
12236 (setq ts (match-string 1))
12237 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12238 (org-timestamp-change n (cdr (assoc what whata)))
12239 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12240 (setq org-log-post-message msg)
12241 (message "%s" msg))))
12243 (defun org-show-todo-tree (arg)
12244 "Make a compact tree which shows all headlines marked with TODO.
12245 The tree will show the lines where the regexp matches, and all higher
12246 headlines above the match.
12247 With a \\[universal-argument] prefix, prompt for a regexp to match.
12248 With a numeric prefix N, construct a sparse tree for the Nth element
12249 of `org-todo-keywords-1'."
12250 (interactive "P")
12251 (let ((case-fold-search nil)
12252 (kwd-re
12253 (cond ((null arg) org-not-done-regexp)
12254 ((equal arg '(4))
12255 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12256 (mapcar 'list org-todo-keywords-1))))
12257 (concat "\\("
12258 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12259 "\\)\\>")))
12260 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12261 (regexp-quote (nth (1- (prefix-numeric-value arg))
12262 org-todo-keywords-1)))
12263 (t (error "Invalid prefix argument: %s" arg)))))
12264 (message "%d TODO entries found"
12265 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12267 (defun org-deadline (&optional remove time)
12268 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12269 With argument REMOVE, remove any deadline from the item.
12270 With argument TIME, set the deadline at the corresponding date. TIME
12271 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12272 (interactive "P")
12273 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12274 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12275 'region-start-level 'region))
12276 org-loop-over-headlines-in-active-region)
12277 (org-map-entries
12278 `(org-deadline ',remove ,time)
12279 org-loop-over-headlines-in-active-region
12280 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12281 (let* ((old-date (org-entry-get nil "DEADLINE"))
12282 (repeater (and old-date
12283 (string-match
12284 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12285 old-date)
12286 (match-string 1 old-date))))
12287 (if remove
12288 (progn
12289 (when (and old-date org-log-redeadline)
12290 (org-add-log-setup 'deldeadline nil old-date 'findpos
12291 org-log-redeadline))
12292 (org-remove-timestamp-with-keyword org-deadline-string)
12293 (message "Item no longer has a deadline."))
12294 (org-add-planning-info 'deadline time 'closed)
12295 (when (and old-date org-log-redeadline
12296 (not (equal old-date
12297 (substring org-last-inserted-timestamp 1 -1))))
12298 (org-add-log-setup 'redeadline nil old-date 'findpos
12299 org-log-redeadline))
12300 (when repeater
12301 (save-excursion
12302 (org-back-to-heading t)
12303 (when (re-search-forward (concat org-deadline-string " "
12304 org-last-inserted-timestamp)
12305 (save-excursion
12306 (outline-next-heading) (point)) t)
12307 (goto-char (1- (match-end 0)))
12308 (insert " " repeater)
12309 (setq org-last-inserted-timestamp
12310 (concat (substring org-last-inserted-timestamp 0 -1)
12311 " " repeater
12312 (substring org-last-inserted-timestamp -1))))))
12313 (message "Deadline on %s" org-last-inserted-timestamp)))))
12315 (defun org-schedule (&optional remove time)
12316 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12317 With argument REMOVE, remove any scheduling date from the item.
12318 With argument TIME, scheduled at the corresponding date. TIME can
12319 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12320 (interactive "P")
12321 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12322 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12323 'region-start-level 'region))
12324 org-loop-over-headlines-in-active-region)
12325 (org-map-entries
12326 `(org-schedule ',remove ,time)
12327 org-loop-over-headlines-in-active-region
12328 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12329 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12330 (repeater (and old-date
12331 (string-match
12332 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12333 old-date)
12334 (match-string 1 old-date))))
12335 (if remove
12336 (progn
12337 (when (and old-date org-log-reschedule)
12338 (org-add-log-setup 'delschedule nil old-date 'findpos
12339 org-log-reschedule))
12340 (org-remove-timestamp-with-keyword org-scheduled-string)
12341 (message "Item is no longer scheduled."))
12342 (org-add-planning-info 'scheduled time 'closed)
12343 (when (and old-date org-log-reschedule
12344 (not (equal old-date
12345 (substring org-last-inserted-timestamp 1 -1))))
12346 (org-add-log-setup 'reschedule nil old-date 'findpos
12347 org-log-reschedule))
12348 (when repeater
12349 (save-excursion
12350 (org-back-to-heading t)
12351 (when (re-search-forward (concat org-scheduled-string " "
12352 org-last-inserted-timestamp)
12353 (save-excursion
12354 (outline-next-heading) (point)) t)
12355 (goto-char (1- (match-end 0)))
12356 (insert " " repeater)
12357 (setq org-last-inserted-timestamp
12358 (concat (substring org-last-inserted-timestamp 0 -1)
12359 " " repeater
12360 (substring org-last-inserted-timestamp -1))))))
12361 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12363 (defun org-get-scheduled-time (pom &optional inherit)
12364 "Get the scheduled time as a time tuple, of a format suitable
12365 for calling org-schedule with, or if there is no scheduling,
12366 returns nil."
12367 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12368 (when time
12369 (apply 'encode-time (org-parse-time-string time)))))
12371 (defun org-get-deadline-time (pom &optional inherit)
12372 "Get the deadline as a time tuple, of a format suitable for
12373 calling org-deadline with, or if there is no scheduling, returns
12374 nil."
12375 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12376 (when time
12377 (apply 'encode-time (org-parse-time-string time)))))
12379 (defun org-remove-timestamp-with-keyword (keyword)
12380 "Remove all time stamps with KEYWORD in the current entry."
12381 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12382 beg)
12383 (save-excursion
12384 (org-back-to-heading t)
12385 (setq beg (point))
12386 (outline-next-heading)
12387 (while (re-search-backward re beg t)
12388 (replace-match "")
12389 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12390 (equal (char-before) ?\ ))
12391 (backward-delete-char 1)
12392 (if (string-match "^[ \t]*$" (buffer-substring
12393 (point-at-bol) (point-at-eol)))
12394 (delete-region (point-at-bol)
12395 (min (point-max) (1+ (point-at-eol))))))))))
12397 (defun org-add-planning-info (what &optional time &rest remove)
12398 "Insert new timestamp with keyword in the line directly after the headline.
12399 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12400 If non is given, the user is prompted for a date.
12401 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12402 be removed."
12403 (interactive)
12404 (let (org-time-was-given org-end-time-was-given ts
12405 end default-time default-input)
12407 (catch 'exit
12408 (when (and (memq what '(scheduled deadline))
12409 (or (not time)
12410 (and (stringp time)
12411 (string-match "^[-+]+[0-9]" time))))
12412 ;; Try to get a default date/time from existing timestamp
12413 (save-excursion
12414 (org-back-to-heading t)
12415 (setq end (save-excursion (outline-next-heading) (point)))
12416 (when (re-search-forward (if (eq what 'scheduled)
12417 org-scheduled-time-regexp
12418 org-deadline-time-regexp)
12419 end t)
12420 (setq ts (match-string 1)
12421 default-time
12422 (apply 'encode-time (org-parse-time-string ts))
12423 default-input (and ts (org-get-compact-tod ts))))))
12424 (when what
12425 (setq time
12426 (if (stringp time)
12427 ;; This is a string (relative or absolute), set proper date
12428 (apply 'encode-time
12429 (org-read-date-analyze
12430 time default-time (decode-time default-time)))
12431 ;; If necessary, get the time from the user
12432 (or time (org-read-date nil 'to-time nil nil
12433 default-time default-input)))))
12435 (when (and org-insert-labeled-timestamps-at-point
12436 (member what '(scheduled deadline)))
12437 (insert
12438 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12439 (org-insert-time-stamp time org-time-was-given
12440 nil nil nil (list org-end-time-was-given))
12441 (setq what nil))
12442 (save-excursion
12443 (save-restriction
12444 (let (col list elt ts buffer-invisibility-spec)
12445 (org-back-to-heading t)
12446 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12447 (goto-char (match-end 1))
12448 (setq col (current-column))
12449 (goto-char (match-end 0))
12450 (if (eobp) (insert "\n") (forward-char 1))
12451 (when (and (not what)
12452 (not (looking-at
12453 (concat "[ \t]*"
12454 org-keyword-time-not-clock-regexp))))
12455 ;; Nothing to add, nothing to remove...... :-)
12456 (throw 'exit nil))
12457 (if (and (not (looking-at org-outline-regexp))
12458 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12459 "[^\r\n]*"))
12460 (not (equal (match-string 1) org-clock-string)))
12461 (narrow-to-region (match-beginning 0) (match-end 0))
12462 (insert-before-markers "\n")
12463 (backward-char 1)
12464 (narrow-to-region (point) (point))
12465 (and org-adapt-indentation (org-indent-to-column col)))
12466 ;; Check if we have to remove something.
12467 (setq list (cons what remove))
12468 (while list
12469 (setq elt (pop list))
12470 (when (or (and (eq elt 'scheduled)
12471 (re-search-forward org-scheduled-time-regexp nil t))
12472 (and (eq elt 'deadline)
12473 (re-search-forward org-deadline-time-regexp nil t))
12474 (and (eq elt 'closed)
12475 (re-search-forward org-closed-time-regexp nil t)))
12476 (replace-match "")
12477 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12478 (and (looking-at "[ \t]+") (replace-match ""))
12479 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12480 (when what
12481 (insert
12482 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12483 (cond ((eq what 'scheduled) org-scheduled-string)
12484 ((eq what 'deadline) org-deadline-string)
12485 ((eq what 'closed) org-closed-string))
12486 " ")
12487 (setq ts (org-insert-time-stamp
12488 time
12489 (or org-time-was-given
12490 (and (eq what 'closed) org-log-done-with-time))
12491 (eq what 'closed)
12492 nil nil (list org-end-time-was-given)))
12493 (insert
12494 (if (not (or (bolp) (eq (char-before) ?\ )
12495 (memq (char-after) '(32 10))
12496 (eobp))) " " ""))
12497 (end-of-line 1))
12498 (goto-char (point-min))
12499 (widen)
12500 (if (and (looking-at "[ \t]*\n")
12501 (equal (char-before) ?\n))
12502 (delete-region (1- (point)) (point-at-eol)))
12503 ts))))))
12505 (defvar org-log-note-marker (make-marker))
12506 (defvar org-log-note-purpose nil)
12507 (defvar org-log-note-state nil)
12508 (defvar org-log-note-previous-state nil)
12509 (defvar org-log-note-how nil)
12510 (defvar org-log-note-extra nil)
12511 (defvar org-log-note-window-configuration nil)
12512 (defvar org-log-note-return-to (make-marker))
12513 (defvar org-log-note-effective-time nil
12514 "Remembered current time so that dynamically scoped
12515 `org-extend-today-until' affects tha timestamps in state change
12516 log")
12518 (defvar org-log-post-message nil
12519 "Message to be displayed after a log note has been stored.
12520 The auto-repeater uses this.")
12522 (defun org-add-note ()
12523 "Add a note to the current entry.
12524 This is done in the same way as adding a state change note."
12525 (interactive)
12526 (org-add-log-setup 'note nil nil 'findpos nil))
12528 (defvar org-property-end-re)
12529 (defun org-add-log-setup (&optional purpose state prev-state
12530 findpos how extra)
12531 "Set up the post command hook to take a note.
12532 If this is about to TODO state change, the new state is expected in STATE.
12533 When FINDPOS is non-nil, find the correct position for the note in
12534 the current entry. If not, assume that it can be inserted at point.
12535 HOW is an indicator what kind of note should be created.
12536 EXTRA is additional text that will be inserted into the notes buffer."
12537 (let* ((org-log-into-drawer (org-log-into-drawer))
12538 (drawer (cond ((stringp org-log-into-drawer)
12539 org-log-into-drawer)
12540 (org-log-into-drawer "LOGBOOK")
12541 (t nil))))
12542 (save-restriction
12543 (save-excursion
12544 (when findpos
12545 (org-back-to-heading t)
12546 (narrow-to-region (point) (save-excursion
12547 (outline-next-heading) (point)))
12548 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12549 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12550 "[^\r\n]*\\)?"))
12551 (goto-char (match-end 0))
12552 (cond
12553 (drawer
12554 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12555 nil t)
12556 (progn
12557 (goto-char (match-end 0))
12558 (or org-log-states-order-reversed
12559 (and (re-search-forward org-property-end-re nil t)
12560 (goto-char (1- (match-beginning 0))))))
12561 (insert "\n:" drawer ":\n:END:")
12562 (beginning-of-line 0)
12563 (org-indent-line)
12564 (beginning-of-line 2)
12565 (org-indent-line)
12566 (end-of-line 0)))
12567 ((and org-log-state-notes-insert-after-drawers
12568 (save-excursion
12569 (forward-line) (looking-at org-drawer-regexp)))
12570 (forward-line)
12571 (while (looking-at org-drawer-regexp)
12572 (goto-char (match-end 0))
12573 (re-search-forward org-property-end-re (point-max) t)
12574 (forward-line))
12575 (forward-line -1)))
12576 (unless org-log-states-order-reversed
12577 (and (= (char-after) ?\n) (forward-char 1))
12578 (org-skip-over-state-notes)
12579 (skip-chars-backward " \t\n\r")))
12580 (move-marker org-log-note-marker (point))
12581 (setq org-log-note-purpose purpose
12582 org-log-note-state state
12583 org-log-note-previous-state prev-state
12584 org-log-note-how how
12585 org-log-note-extra extra
12586 org-log-note-effective-time (org-current-effective-time))
12587 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12589 (defun org-skip-over-state-notes ()
12590 "Skip past the list of State notes in an entry."
12591 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12592 (when (ignore-errors (goto-char (org-in-item-p)))
12593 (let* ((struct (org-list-struct))
12594 (prevs (org-list-prevs-alist struct)))
12595 (while (looking-at "[ \t]*- State")
12596 (goto-char (or (org-list-get-next-item (point) struct prevs)
12597 (org-list-get-item-end (point) struct)))))))
12599 (defun org-add-log-note (&optional purpose)
12600 "Pop up a window for taking a note, and add this note later at point."
12601 (remove-hook 'post-command-hook 'org-add-log-note)
12602 (setq org-log-note-window-configuration (current-window-configuration))
12603 (delete-other-windows)
12604 (move-marker org-log-note-return-to (point))
12605 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12606 (goto-char org-log-note-marker)
12607 (org-switch-to-buffer-other-window "*Org Note*")
12608 (erase-buffer)
12609 (if (memq org-log-note-how '(time state))
12610 (let (current-prefix-arg) (org-store-log-note))
12611 (let ((org-inhibit-startup t)) (org-mode))
12612 (insert (format "# Insert note for %s.
12613 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12614 (cond
12615 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12616 ((eq org-log-note-purpose 'done) "closed todo item")
12617 ((eq org-log-note-purpose 'state)
12618 (format "state change from \"%s\" to \"%s\""
12619 (or org-log-note-previous-state "")
12620 (or org-log-note-state "")))
12621 ((eq org-log-note-purpose 'reschedule)
12622 "rescheduling")
12623 ((eq org-log-note-purpose 'delschedule)
12624 "no longer scheduled")
12625 ((eq org-log-note-purpose 'redeadline)
12626 "changing deadline")
12627 ((eq org-log-note-purpose 'deldeadline)
12628 "removing deadline")
12629 ((eq org-log-note-purpose 'refile)
12630 "refiling")
12631 ((eq org-log-note-purpose 'note)
12632 "this entry")
12633 (t (error "This should not happen")))))
12634 (if org-log-note-extra (insert org-log-note-extra))
12635 (org-set-local 'org-finish-function 'org-store-log-note)
12636 (run-hooks 'org-log-buffer-setup-hook)))
12638 (defvar org-note-abort nil) ; dynamically scoped
12639 (defun org-store-log-note ()
12640 "Finish taking a log note, and insert it to where it belongs."
12641 (let ((txt (buffer-string))
12642 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12643 lines ind bul)
12644 (kill-buffer (current-buffer))
12645 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12646 (setq txt (replace-match "" t t txt)))
12647 (if (string-match "\\s-+\\'" txt)
12648 (setq txt (replace-match "" t t txt)))
12649 (setq lines (org-split-string txt "\n"))
12650 (when (and note (string-match "\\S-" note))
12651 (setq note
12652 (org-replace-escapes
12653 note
12654 (list (cons "%u" (user-login-name))
12655 (cons "%U" user-full-name)
12656 (cons "%t" (format-time-string
12657 (org-time-stamp-format 'long 'inactive)
12658 org-log-note-effective-time))
12659 (cons "%T" (format-time-string
12660 (org-time-stamp-format 'long nil)
12661 org-log-note-effective-time))
12662 (cons "%d" (format-time-string
12663 (org-time-stamp-format nil 'inactive)
12664 org-log-note-effective-time))
12665 (cons "%D" (format-time-string
12666 (org-time-stamp-format nil nil)
12667 org-log-note-effective-time))
12668 (cons "%s" (if org-log-note-state
12669 (concat "\"" org-log-note-state "\"")
12670 ""))
12671 (cons "%S" (if org-log-note-previous-state
12672 (concat "\"" org-log-note-previous-state "\"")
12673 "\"\"")))))
12674 (if lines (setq note (concat note " \\\\")))
12675 (push note lines))
12676 (when (or current-prefix-arg org-note-abort)
12677 (when org-log-into-drawer
12678 (org-remove-empty-drawer-at
12679 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12680 org-log-note-marker))
12681 (setq lines nil))
12682 (when lines
12683 (with-current-buffer (marker-buffer org-log-note-marker)
12684 (save-excursion
12685 (goto-char org-log-note-marker)
12686 (move-marker org-log-note-marker nil)
12687 (end-of-line 1)
12688 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12689 (setq ind (save-excursion
12690 (if (ignore-errors (goto-char (org-in-item-p)))
12691 (let ((struct (org-list-struct)))
12692 (org-list-get-ind
12693 (org-list-get-top-point struct) struct))
12694 (skip-chars-backward " \r\t\n")
12695 (cond
12696 ((and (org-at-heading-p)
12697 org-adapt-indentation)
12698 (1+ (org-current-level)))
12699 ((org-at-heading-p) 0)
12700 (t (org-get-indentation))))))
12701 (setq bul (org-list-bullet-string "-"))
12702 (org-indent-line-to ind)
12703 (insert bul (pop lines))
12704 (let ((ind-body (+ (length bul) ind)))
12705 (while lines
12706 (insert "\n")
12707 (org-indent-line-to ind-body)
12708 (insert (pop lines))))
12709 (message "Note stored")
12710 (org-back-to-heading t)
12711 (org-cycle-hide-drawers 'children)))))
12712 (set-window-configuration org-log-note-window-configuration)
12713 (with-current-buffer (marker-buffer org-log-note-return-to)
12714 (goto-char org-log-note-return-to))
12715 (move-marker org-log-note-return-to nil)
12716 (and org-log-post-message (message "%s" org-log-post-message)))
12718 (defun org-remove-empty-drawer-at (drawer pos)
12719 "Remove an empty drawer DRAWER at position POS.
12720 POS may also be a marker."
12721 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12722 (save-excursion
12723 (save-restriction
12724 (widen)
12725 (goto-char pos)
12726 (if (org-in-regexp
12727 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12728 (replace-match ""))))))
12730 (defvar org-ts-type nil)
12731 (defun org-sparse-tree (&optional arg type)
12732 "Create a sparse tree, prompt for the details.
12733 This command can create sparse trees. You first need to select the type
12734 of match used to create the tree:
12736 t Show all TODO entries.
12737 T Show entries with a specific TODO keyword.
12738 m Show entries selected by a tags/property match.
12739 p Enter a property name and its value (both with completion on existing
12740 names/values) and show entries with that property.
12741 r Show entries matching a regular expression (`/' can be used as well).
12742 b Show deadlines and scheduled items before a date.
12743 a Show deadlines and scheduled items after a date.
12744 d Show deadlines due within `org-deadline-warning-days'.
12745 D Show deadlines and scheduled items between a date range."
12746 (interactive "P")
12747 (let (ans kwd value ts-type)
12748 (setq type (or type org-sparse-tree-default-date-type))
12749 (setq org-ts-type type)
12750 (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"
12751 (cond ((eq type 'all) "all timestamps")
12752 ((eq type 'scheduled) "only scheduled")
12753 ((eq type 'deadline) "only deadline")
12754 ((eq type 'active) "only active timestamps")
12755 ((eq type 'inactive) "only inactive timestamps")
12756 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12757 (t "scheduled/deadline")))
12758 (setq ans (read-char-exclusive))
12759 (cond
12760 ((equal ans ?c)
12761 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12762 ((equal ans ?d)
12763 (call-interactively 'org-check-deadlines))
12764 ((equal ans ?b)
12765 (call-interactively 'org-check-before-date))
12766 ((equal ans ?a)
12767 (call-interactively 'org-check-after-date))
12768 ((equal ans ?D)
12769 (call-interactively 'org-check-dates-range))
12770 ((equal ans ?t)
12771 (org-show-todo-tree nil))
12772 ((equal ans ?T)
12773 (org-show-todo-tree '(4)))
12774 ((member ans '(?T ?m))
12775 (call-interactively 'org-match-sparse-tree))
12776 ((member ans '(?p ?P))
12777 (setq kwd (org-icompleting-read "Property: "
12778 (mapcar 'list (org-buffer-property-keys))))
12779 (setq value (org-icompleting-read "Value: "
12780 (mapcar 'list (org-property-values kwd))))
12781 (unless (string-match "\\`{.*}\\'" value)
12782 (setq value (concat "\"" value "\"")))
12783 (org-match-sparse-tree arg (concat kwd "=" value)))
12784 ((member ans '(?r ?R ?/))
12785 (call-interactively 'org-occur))
12786 (t (error "No such sparse tree command \"%c\"" ans)))))
12788 (defvar org-occur-highlights nil
12789 "List of overlays used for occur matches.")
12790 (make-variable-buffer-local 'org-occur-highlights)
12791 (defvar org-occur-parameters nil
12792 "Parameters of the active org-occur calls.
12793 This is a list, each call to org-occur pushes as cons cell,
12794 containing the regular expression and the callback, onto the list.
12795 The list can contain several entries if `org-occur' has been called
12796 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12797 will only contain one set of parameters. When the highlights are
12798 removed (for example with `C-c C-c', or with the next edit (depending
12799 on `org-remove-highlights-with-change'), this variable is emptied
12800 as well.")
12801 (make-variable-buffer-local 'org-occur-parameters)
12803 (defun org-occur (regexp &optional keep-previous callback)
12804 "Make a compact tree which shows all matches of REGEXP.
12805 The tree will show the lines where the regexp matches, and all higher
12806 headlines above the match. It will also show the heading after the match,
12807 to make sure editing the matching entry is easy.
12808 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12809 call to `org-occur' will be kept, to allow stacking of calls to this
12810 command.
12811 If CALLBACK is non-nil, it is a function which is called to confirm
12812 that the match should indeed be shown."
12813 (interactive "sRegexp: \nP")
12814 (when (equal regexp "")
12815 (error "Regexp cannot be empty"))
12816 (unless keep-previous
12817 (org-remove-occur-highlights nil nil t))
12818 (push (cons regexp callback) org-occur-parameters)
12819 (let ((cnt 0))
12820 (save-excursion
12821 (goto-char (point-min))
12822 (if (or (not keep-previous) ; do not want to keep
12823 (not org-occur-highlights)) ; no previous matches
12824 ;; hide everything
12825 (org-overview))
12826 (while (re-search-forward regexp nil t)
12827 (when (or (not callback)
12828 (save-match-data (funcall callback)))
12829 (setq cnt (1+ cnt))
12830 (when org-highlight-sparse-tree-matches
12831 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12832 (org-show-context 'occur-tree))))
12833 (when org-remove-highlights-with-change
12834 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12835 nil 'local))
12836 (unless org-sparse-tree-open-archived-trees
12837 (org-hide-archived-subtrees (point-min) (point-max)))
12838 (run-hooks 'org-occur-hook)
12839 (if (org-called-interactively-p 'interactive)
12840 (message "%d match(es) for regexp %s" cnt regexp))
12841 cnt))
12843 (defun org-occur-next-match (&optional n reset)
12844 "Function for `next-error-function' to find sparse tree matches.
12845 N is the number of matches to move, when negative move backwards.
12846 RESET is entirely ignored - this function always goes back to the
12847 starting point when no match is found."
12848 (let* ((limit (if (< n 0) (point-min) (point-max)))
12849 (search-func (if (< n 0)
12850 'previous-single-char-property-change
12851 'next-single-char-property-change))
12852 (n (abs n))
12853 (pos (point))
12855 (catch 'exit
12856 (while (setq p1 (funcall search-func (point) 'org-type))
12857 (when (equal p1 limit)
12858 (goto-char pos)
12859 (error "No more matches"))
12860 (when (equal (get-char-property p1 'org-type) 'org-occur)
12861 (setq n (1- n))
12862 (when (= n 0)
12863 (goto-char p1)
12864 (throw 'exit (point))))
12865 (goto-char p1))
12866 (goto-char p1)
12867 (error "No more matches"))))
12869 (defun org-show-context (&optional key)
12870 "Make sure point and context are visible.
12871 How much context is shown depends upon the variables
12872 `org-show-hierarchy-above', `org-show-following-heading',
12873 `org-show-entry-below' and `org-show-siblings'."
12874 (let ((heading-p (org-at-heading-p t))
12875 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12876 (following-p (org-get-alist-option org-show-following-heading key))
12877 (entry-p (org-get-alist-option org-show-entry-below key))
12878 (siblings-p (org-get-alist-option org-show-siblings key)))
12879 (catch 'exit
12880 ;; Show heading or entry text
12881 (if (and heading-p (not entry-p))
12882 (org-flag-heading nil) ; only show the heading
12883 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12884 (org-show-hidden-entry))) ; show entire entry
12885 (when following-p
12886 ;; Show next sibling, or heading below text
12887 (save-excursion
12888 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12889 (org-flag-heading nil))))
12890 (when siblings-p (org-show-siblings))
12891 (when hierarchy-p
12892 ;; show all higher headings, possibly with siblings
12893 (save-excursion
12894 (while (and (condition-case nil
12895 (progn (org-up-heading-all 1) t)
12896 (error nil))
12897 (not (bobp)))
12898 (org-flag-heading nil)
12899 (when siblings-p (org-show-siblings))))))))
12901 (defvar org-reveal-start-hook nil
12902 "Hook run before revealing a location.")
12904 (defun org-reveal (&optional siblings)
12905 "Show current entry, hierarchy above it, and the following headline.
12906 This can be used to show a consistent set of context around locations
12907 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12908 not t for the search context.
12910 With optional argument SIBLINGS, on each level of the hierarchy all
12911 siblings are shown. This repairs the tree structure to what it would
12912 look like when opened with hierarchical calls to `org-cycle'.
12913 With double optional argument \\[universal-argument] \\[universal-argument], \
12914 go to the parent and show the
12915 entire tree."
12916 (interactive "P")
12917 (run-hooks 'org-reveal-start-hook)
12918 (let ((org-show-hierarchy-above t)
12919 (org-show-following-heading t)
12920 (org-show-siblings (if siblings t org-show-siblings)))
12921 (org-show-context nil))
12922 (when (equal siblings '(16))
12923 (save-excursion
12924 (when (org-up-heading-safe)
12925 (org-show-subtree)
12926 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12928 (defun org-highlight-new-match (beg end)
12929 "Highlight from BEG to END and mark the highlight is an occur headline."
12930 (let ((ov (make-overlay beg end)))
12931 (overlay-put ov 'face 'secondary-selection)
12932 (overlay-put ov 'org-type 'org-occur)
12933 (push ov org-occur-highlights)))
12935 (defun org-remove-occur-highlights (&optional beg end noremove)
12936 "Remove the occur highlights from the buffer.
12937 BEG and END are ignored. If NOREMOVE is nil, remove this function
12938 from the `before-change-functions' in the current buffer."
12939 (interactive)
12940 (unless org-inhibit-highlight-removal
12941 (mapc 'delete-overlay org-occur-highlights)
12942 (setq org-occur-highlights nil)
12943 (setq org-occur-parameters nil)
12944 (unless noremove
12945 (remove-hook 'before-change-functions
12946 'org-remove-occur-highlights 'local))))
12948 ;;;; Priorities
12950 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12951 "Regular expression matching the priority indicator.")
12953 (defvar org-remove-priority-next-time nil)
12955 (defun org-priority-up ()
12956 "Increase the priority of the current item."
12957 (interactive)
12958 (org-priority 'up))
12960 (defun org-priority-down ()
12961 "Decrease the priority of the current item."
12962 (interactive)
12963 (org-priority 'down))
12965 (defun org-priority (&optional action)
12966 "Change the priority of an item.
12967 ACTION can be `set', `up', `down', or a character."
12968 (interactive)
12969 (unless org-enable-priority-commands
12970 (error "Priority commands are disabled"))
12971 (setq action (or action 'set))
12972 (let (current new news have remove)
12973 (save-excursion
12974 (org-back-to-heading t)
12975 (if (looking-at org-priority-regexp)
12976 (setq current (string-to-char (match-string 2))
12977 have t))
12978 (cond
12979 ((eq action 'remove)
12980 (setq remove t new ?\ ))
12981 ((or (eq action 'set)
12982 (if (featurep 'xemacs) (characterp action) (integerp action)))
12983 (if (not (eq action 'set))
12984 (setq new action)
12985 (message "Priority %c-%c, SPC to remove: "
12986 org-highest-priority org-lowest-priority)
12987 (save-match-data
12988 (setq new (read-char-exclusive))))
12989 (if (and (= (upcase org-highest-priority) org-highest-priority)
12990 (= (upcase org-lowest-priority) org-lowest-priority))
12991 (setq new (upcase new)))
12992 (cond ((equal new ?\ ) (setq remove t))
12993 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12994 (error "Priority must be between `%c' and `%c'"
12995 org-highest-priority org-lowest-priority))))
12996 ((eq action 'up)
12997 (setq new (if have
12998 (1- current) ; normal cycling
12999 ;; last priority was empty
13000 (if (eq last-command this-command)
13001 org-lowest-priority ; wrap around empty to lowest
13002 ;; default
13003 (if org-priority-start-cycle-with-default
13004 org-default-priority
13005 (1- org-default-priority))))))
13006 ((eq action 'down)
13007 (setq new (if have
13008 (1+ current) ; normal cycling
13009 ;; last priority was empty
13010 (if (eq last-command this-command)
13011 org-highest-priority ; wrap around empty to highest
13012 ;; default
13013 (if org-priority-start-cycle-with-default
13014 org-default-priority
13015 (1+ org-default-priority))))))
13016 (t (error "Invalid action")))
13017 (if (or (< (upcase new) org-highest-priority)
13018 (> (upcase new) org-lowest-priority))
13019 (if (and (memq action '(up down))
13020 (not have) (not (eq last-command this-command)))
13021 ;; `new' is from default priority
13022 (error
13023 "The default can not be set, see `org-default-priority' why")
13024 ;; normal cycling: `new' is beyond highest/lowest priority
13025 ;; and is wrapped around to the empty priority
13026 (setq remove t)))
13027 (setq news (format "%c" new))
13028 (if have
13029 (if remove
13030 (replace-match "" t t nil 1)
13031 (replace-match news t t nil 2))
13032 (if remove
13033 (error "No priority cookie found in line")
13034 (let ((case-fold-search nil))
13035 (looking-at org-todo-line-regexp))
13036 (if (match-end 2)
13037 (progn
13038 (goto-char (match-end 2))
13039 (insert " [#" news "]"))
13040 (goto-char (match-beginning 3))
13041 (insert "[#" news "] "))))
13042 (org-preserve-lc (org-set-tags nil 'align)))
13043 (if remove
13044 (message "Priority removed")
13045 (message "Priority of current item set to %s" news))))
13047 (defun org-get-priority (s)
13048 "Find priority cookie and return priority."
13049 (if (functionp org-get-priority-function)
13050 (funcall org-get-priority-function)
13051 (save-match-data
13052 (if (not (string-match org-priority-regexp s))
13053 (* 1000 (- org-lowest-priority org-default-priority))
13054 (* 1000 (- org-lowest-priority
13055 (string-to-char (match-string 2 s))))))))
13057 ;;;; Tags
13059 (defvar org-agenda-archives-mode)
13060 (defvar org-map-continue-from nil
13061 "Position from where mapping should continue.
13062 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13064 (defvar org-scanner-tags nil
13065 "The current tag list while the tags scanner is running.")
13066 (defvar org-trust-scanner-tags nil
13067 "Should `org-get-tags-at' use the tags for the scanner.
13068 This is for internal dynamical scoping only.
13069 When this is non-nil, the function `org-get-tags-at' will return the value
13070 of `org-scanner-tags' instead of building the list by itself. This
13071 can lead to large speed-ups when the tags scanner is used in a file with
13072 many entries, and when the list of tags is retrieved, for example to
13073 obtain a list of properties. Building the tags list for each entry in such
13074 a file becomes an N^2 operation - but with this variable set, it scales
13075 as N.")
13077 (defun org-scan-tags (action matcher todo-only &optional start-level)
13078 "Scan headline tags with inheritance and produce output ACTION.
13080 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13081 or `agenda' to produce an entry list for an agenda view. It can also be
13082 a Lisp form or a function that should be called at each matched headline, in
13083 this case the return value is a list of all return values from these calls.
13085 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13086 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13087 only lines with a not-done TODO keyword are included in the output.
13088 This should be the same variable that was scoped into
13089 and set by `org-make-tags-matcher' when it constructed MATCHER.
13091 START-LEVEL can be a string with asterisks, reducing the scope to
13092 headlines matching this string."
13093 (require 'org-agenda)
13094 (let* ((re (concat "^"
13095 (if start-level
13096 ;; Get the correct level to match
13097 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13098 org-outline-regexp)
13099 " *\\(\\<\\("
13100 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13101 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13102 (props (list 'face 'default
13103 'done-face 'org-agenda-done
13104 'undone-face 'default
13105 'mouse-face 'highlight
13106 'org-not-done-regexp org-not-done-regexp
13107 'org-todo-regexp org-todo-regexp
13108 'org-complex-heading-regexp org-complex-heading-regexp
13109 'help-echo
13110 (format "mouse-2 or RET jump to org file %s"
13111 (abbreviate-file-name
13112 (or (buffer-file-name (buffer-base-buffer))
13113 (buffer-name (buffer-base-buffer)))))))
13114 (case-fold-search nil)
13115 (org-map-continue-from nil)
13116 lspos tags tags-list
13117 (tags-alist (list (cons 0 org-file-tags)))
13118 (llast 0) rtn rtn1 level category i txt
13119 todo marker entry priority)
13120 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13121 (setq action (list 'lambda nil action)))
13122 (save-excursion
13123 (goto-char (point-min))
13124 (when (eq action 'sparse-tree)
13125 (org-overview)
13126 (org-remove-occur-highlights))
13127 (while (re-search-forward re nil t)
13128 (setq org-map-continue-from nil)
13129 (catch :skip
13130 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13131 tags (if (match-end 4) (org-match-string-no-properties 4)))
13132 (goto-char (setq lspos (match-beginning 0)))
13133 (setq level (org-reduced-level (funcall outline-level))
13134 category (org-get-category))
13135 (setq i llast llast level)
13136 ;; remove tag lists from same and sublevels
13137 (while (>= i level)
13138 (when (setq entry (assoc i tags-alist))
13139 (setq tags-alist (delete entry tags-alist)))
13140 (setq i (1- i)))
13141 ;; add the next tags
13142 (when tags
13143 (setq tags (org-split-string tags ":")
13144 tags-alist
13145 (cons (cons level tags) tags-alist)))
13146 ;; compile tags for current headline
13147 (setq tags-list
13148 (if org-use-tag-inheritance
13149 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13150 tags)
13151 org-scanner-tags tags-list)
13152 (when org-use-tag-inheritance
13153 (setcdr (car tags-alist)
13154 (mapcar (lambda (x)
13155 (setq x (copy-sequence x))
13156 (org-add-prop-inherited x))
13157 (cdar tags-alist))))
13158 (when (and tags org-use-tag-inheritance
13159 (or (not (eq t org-use-tag-inheritance))
13160 org-tags-exclude-from-inheritance))
13161 ;; selective inheritance, remove uninherited ones
13162 (setcdr (car tags-alist)
13163 (org-remove-uninherited-tags (cdar tags-alist))))
13164 (when (and
13166 ;; eval matcher only when the todo condition is OK
13167 (and (or (not todo-only) (member todo org-not-done-keywords))
13168 (let ((case-fold-search t) (org-trust-scanner-tags t))
13169 (eval matcher)))
13171 ;; Call the skipper, but return t if it does not skip,
13172 ;; so that the `and' form continues evaluating
13173 (progn
13174 (unless (eq action 'sparse-tree) (org-agenda-skip))
13177 ;; Check if timestamps are deselecting this entry
13178 (or (not todo-only)
13179 (and (member todo org-not-done-keywords)
13180 (or (not org-agenda-tags-todo-honor-ignore-options)
13181 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13183 ;; Extra check for the archive tag
13184 ;; FIXME: Does the skipper already do this????
13186 (not (member org-archive-tag tags-list))
13187 ;; we have an archive tag, should we use this anyway?
13188 (or (not org-agenda-skip-archived-trees)
13189 (and (eq action 'agenda) org-agenda-archives-mode))))
13191 ;; select this headline
13193 (cond
13194 ((eq action 'sparse-tree)
13195 (and org-highlight-sparse-tree-matches
13196 (org-get-heading) (match-end 0)
13197 (org-highlight-new-match
13198 (match-beginning 1) (match-end 1)))
13199 (org-show-context 'tags-tree))
13200 ((eq action 'agenda)
13201 (setq txt (org-agenda-format-item
13203 (concat
13204 (if (eq org-tags-match-list-sublevels 'indented)
13205 (make-string (1- level) ?.) "")
13206 (org-get-heading))
13207 category
13208 tags-list)
13209 priority (org-get-priority txt))
13210 (goto-char lspos)
13211 (setq marker (org-agenda-new-marker))
13212 (org-add-props txt props
13213 'org-marker marker 'org-hd-marker marker 'org-category category
13214 'todo-state todo
13215 'priority priority 'type "tagsmatch")
13216 (push txt rtn))
13217 ((functionp action)
13218 (setq org-map-continue-from nil)
13219 (save-excursion
13220 (setq rtn1 (funcall action))
13221 (push rtn1 rtn)))
13222 (t (error "Invalid action")))
13224 ;; if we are to skip sublevels, jump to end of subtree
13225 (unless org-tags-match-list-sublevels
13226 (org-end-of-subtree t)
13227 (backward-char 1))))
13228 ;; Get the correct position from where to continue
13229 (if org-map-continue-from
13230 (goto-char org-map-continue-from)
13231 (and (= (point) lspos) (end-of-line 1)))))
13232 (when (and (eq action 'sparse-tree)
13233 (not org-sparse-tree-open-archived-trees))
13234 (org-hide-archived-subtrees (point-min) (point-max)))
13235 (nreverse rtn)))
13237 (defun org-remove-uninherited-tags (tags)
13238 "Remove all tags that are not inherited from the list TAGS."
13239 (cond
13240 ((eq org-use-tag-inheritance t)
13241 (if org-tags-exclude-from-inheritance
13242 (org-delete-all org-tags-exclude-from-inheritance tags)
13243 tags))
13244 ((not org-use-tag-inheritance) nil)
13245 ((stringp org-use-tag-inheritance)
13246 (delq nil (mapcar
13247 (lambda (x)
13248 (if (and (string-match org-use-tag-inheritance x)
13249 (not (member x org-tags-exclude-from-inheritance)))
13250 x nil))
13251 tags)))
13252 ((listp org-use-tag-inheritance)
13253 (delq nil (mapcar
13254 (lambda (x)
13255 (if (member x org-use-tag-inheritance) x nil))
13256 tags)))))
13258 (defun org-match-sparse-tree (&optional todo-only match)
13259 "Create a sparse tree according to tags string MATCH.
13260 MATCH can contain positive and negative selection of tags, like
13261 \"+WORK+URGENT-WITHBOSS\".
13262 If optional argument TODO-ONLY is non-nil, only select lines that are
13263 also TODO lines."
13264 (interactive "P")
13265 (org-prepare-agenda-buffers (list (current-buffer)))
13266 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13268 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13270 (defvar org-cached-props nil)
13271 (defun org-cached-entry-get (pom property)
13272 (if (or (eq t org-use-property-inheritance)
13273 (and (stringp org-use-property-inheritance)
13274 (string-match org-use-property-inheritance property))
13275 (and (listp org-use-property-inheritance)
13276 (member property org-use-property-inheritance)))
13277 ;; Caching is not possible, check it directly
13278 (org-entry-get pom property 'inherit)
13279 ;; Get all properties, so that we can do complicated checks easily
13280 (cdr (assoc property (or org-cached-props
13281 (setq org-cached-props
13282 (org-entry-properties pom)))))))
13284 (defun org-global-tags-completion-table (&optional files)
13285 "Return the list of all tags in all agenda buffer/files.
13286 Optional FILES argument is a list of files which can be used
13287 instead of the agenda files."
13288 (save-excursion
13289 (org-uniquify
13290 (delq nil
13291 (apply 'append
13292 (mapcar
13293 (lambda (file)
13294 (set-buffer (find-file-noselect file))
13295 (append (org-get-buffer-tags)
13296 (mapcar (lambda (x) (if (stringp (car-safe x))
13297 (list (car-safe x)) nil))
13298 org-tag-alist)))
13299 (if (and files (car files))
13300 files
13301 (org-agenda-files))))))))
13303 (defun org-make-tags-matcher (match)
13304 "Create the TAGS/TODO matcher form for the selection string MATCH.
13306 The variable `todo-only' is scoped dynamically into this function; it will be
13307 set to t if the matcher restricts matching to TODO entries,
13308 otherwise will not be touched.
13310 Returns a cons of the selection string MATCH and the constructed
13311 lisp form implementing the matcher. The matcher is to be
13312 evaluated at an Org entry, with point on the headline,
13313 and returns t if the entry matches the
13314 selection string MATCH. The returned lisp form references
13315 two variables with information about the entry, which must be
13316 bound around the form's evaluation: todo, the TODO keyword at the
13317 entry (or nil of none); and tags-list, the list of all tags at the
13318 entry including inherited ones. Additionally, the category
13319 of the entry (if any) must be specified as the text property
13320 'org-category on the headline.
13322 See also `org-scan-tags'.
13324 (declare (special todo-only))
13325 (unless (boundp 'todo-only)
13326 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13327 (unless match
13328 ;; Get a new match request, with completion
13329 (let ((org-last-tags-completion-table
13330 (org-global-tags-completion-table)))
13331 (setq match (org-completing-read-no-i
13332 "Match: " 'org-tags-completion-function nil nil nil
13333 'org-tags-history))))
13335 ;; Parse the string and create a lisp form
13336 (let ((match0 match)
13337 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13338 minus tag mm
13339 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13340 orterms term orlist re-p str-p level-p level-op time-p
13341 prop-p pn pv po gv rest)
13342 (if (string-match "/+" match)
13343 ;; match contains also a todo-matching request
13344 (progn
13345 (setq tagsmatch (substring match 0 (match-beginning 0))
13346 todomatch (substring match (match-end 0)))
13347 (if (string-match "^!" todomatch)
13348 (setq todo-only t todomatch (substring todomatch 1)))
13349 (if (string-match "^\\s-*$" todomatch)
13350 (setq todomatch nil)))
13351 ;; only matching tags
13352 (setq tagsmatch match todomatch nil))
13354 ;; Make the tags matcher
13355 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13356 (setq tagsmatcher t)
13357 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13358 (while (setq term (pop orterms))
13359 (while (and (equal (substring term -1) "\\") orterms)
13360 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13361 (while (string-match re term)
13362 (setq rest (substring term (match-end 0))
13363 minus (and (match-end 1)
13364 (equal (match-string 1 term) "-"))
13365 tag (save-match-data (replace-regexp-in-string
13366 "\\\\-" "-"
13367 (match-string 2 term)))
13368 re-p (equal (string-to-char tag) ?{)
13369 level-p (match-end 4)
13370 prop-p (match-end 5)
13371 mm (cond
13372 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13373 (level-p
13374 (setq level-op (org-op-to-function (match-string 3 term)))
13375 `(,level-op level ,(string-to-number
13376 (match-string 4 term))))
13377 (prop-p
13378 (setq pn (match-string 5 term)
13379 po (match-string 6 term)
13380 pv (match-string 7 term)
13381 re-p (equal (string-to-char pv) ?{)
13382 str-p (equal (string-to-char pv) ?\")
13383 time-p (save-match-data
13384 (string-match "^\"[[<].*[]>]\"$" pv))
13385 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13386 (if time-p (setq pv (org-matcher-time pv)))
13387 (setq po (org-op-to-function po (if time-p 'time str-p)))
13388 (cond
13389 ((equal pn "CATEGORY")
13390 (setq gv '(get-text-property (point) 'org-category)))
13391 ((equal pn "TODO")
13392 (setq gv 'todo))
13394 (setq gv `(org-cached-entry-get nil ,pn))))
13395 (if re-p
13396 (if (eq po 'org<>)
13397 `(not (string-match ,pv (or ,gv "")))
13398 `(string-match ,pv (or ,gv "")))
13399 (if str-p
13400 `(,po (or ,gv "") ,pv)
13401 `(,po (string-to-number (or ,gv ""))
13402 ,(string-to-number pv) ))))
13403 (t `(member ,tag tags-list)))
13404 mm (if minus (list 'not mm) mm)
13405 term rest)
13406 (push mm tagsmatcher))
13407 (push (if (> (length tagsmatcher) 1)
13408 (cons 'and tagsmatcher)
13409 (car tagsmatcher))
13410 orlist)
13411 (setq tagsmatcher nil))
13412 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13413 (setq tagsmatcher
13414 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13415 ;; Make the todo matcher
13416 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13417 (setq todomatcher t)
13418 (setq orterms (org-split-string todomatch "|") orlist nil)
13419 (while (setq term (pop orterms))
13420 (while (string-match re term)
13421 (setq minus (and (match-end 1)
13422 (equal (match-string 1 term) "-"))
13423 kwd (match-string 2 term)
13424 re-p (equal (string-to-char kwd) ?{)
13425 term (substring term (match-end 0))
13426 mm (if re-p
13427 `(string-match ,(substring kwd 1 -1) todo)
13428 (list 'equal 'todo kwd))
13429 mm (if minus (list 'not mm) mm))
13430 (push mm todomatcher))
13431 (push (if (> (length todomatcher) 1)
13432 (cons 'and todomatcher)
13433 (car todomatcher))
13434 orlist)
13435 (setq todomatcher nil))
13436 (setq todomatcher (if (> (length orlist) 1)
13437 (cons 'or orlist) (car orlist))))
13439 ;; Return the string and lisp forms of the matcher
13440 (setq matcher (if todomatcher
13441 (list 'and tagsmatcher todomatcher)
13442 tagsmatcher))
13443 (when todo-only
13444 (setq matcher (list 'and '(member todo org-not-done-keywords)
13445 matcher)))
13446 (cons match0 matcher)))
13448 (defun org-op-to-function (op &optional stringp)
13449 "Turn an operator into the appropriate function."
13450 (setq op
13451 (cond
13452 ((equal op "<" ) '(< string< org-time<))
13453 ((equal op ">" ) '(> org-string> org-time>))
13454 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13455 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13456 ((member op '("=" "==")) '(= string= org-time=))
13457 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13458 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13460 (defun org<> (a b) (not (= a b)))
13461 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13462 (defun org-string>= (a b) (not (string< a b)))
13463 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13464 (defun org-string<> (a b) (not (string= a b)))
13465 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13466 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13467 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13468 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13469 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13470 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13471 (defun org-2ft (s)
13472 "Convert S to a floating point time.
13473 If S is already a number, just return it. If it is a string, parse
13474 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13475 (cond
13476 ((numberp s) s)
13477 ((stringp s)
13478 (condition-case nil
13479 (float-time (apply 'encode-time (org-parse-time-string s)))
13480 (error 0.)))
13481 (t 0.)))
13483 (defun org-time-today ()
13484 "Time in seconds today at 0:00.
13485 Returns the float number of seconds since the beginning of the
13486 epoch to the beginning of today (00:00)."
13487 (float-time (apply 'encode-time
13488 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13490 (defun org-matcher-time (s)
13491 "Interpret a time comparison value."
13492 (save-match-data
13493 (cond
13494 ((string= s "<now>") (float-time))
13495 ((string= s "<today>") (org-time-today))
13496 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13497 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13498 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13499 (+ (org-time-today)
13500 (* (string-to-number (match-string 1 s))
13501 (cdr (assoc (match-string 2 s)
13502 '(("d" . 86400.0) ("w" . 604800.0)
13503 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13504 (t (org-2ft s)))))
13506 (defun org-match-any-p (re list)
13507 "Does re match any element of list?"
13508 (setq list (mapcar (lambda (x) (string-match re x)) list))
13509 (delq nil list))
13511 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13512 (defvar org-tags-overlay (make-overlay 1 1))
13513 (org-detach-overlay org-tags-overlay)
13515 (defun org-get-local-tags-at (&optional pos)
13516 "Get a list of tags defined in the current headline."
13517 (org-get-tags-at pos 'local))
13519 (defun org-get-local-tags ()
13520 "Get a list of tags defined in the current headline."
13521 (org-get-tags-at nil 'local))
13523 (defun org-get-tags-at (&optional pos local)
13524 "Get a list of all headline tags applicable at POS.
13525 POS defaults to point. If tags are inherited, the list contains
13526 the targets in the same sequence as the headlines appear, i.e.
13527 the tags of the current headline come last.
13528 When LOCAL is non-nil, only return tags from the current headline,
13529 ignore inherited ones."
13530 (interactive)
13531 (if (and org-trust-scanner-tags
13532 (or (not pos) (equal pos (point)))
13533 (not local))
13534 org-scanner-tags
13535 (let (tags ltags lastpos parent)
13536 (save-excursion
13537 (save-restriction
13538 (widen)
13539 (goto-char (or pos (point)))
13540 (save-match-data
13541 (catch 'done
13542 (condition-case nil
13543 (progn
13544 (org-back-to-heading t)
13545 (while (not (equal lastpos (point)))
13546 (setq lastpos (point))
13547 (when (looking-at
13548 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13549 (setq ltags (org-split-string
13550 (org-match-string-no-properties 1) ":"))
13551 (when parent
13552 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13553 (setq tags (append
13554 (if parent
13555 (org-remove-uninherited-tags ltags)
13556 ltags)
13557 tags)))
13558 (or org-use-tag-inheritance (throw 'done t))
13559 (if local (throw 'done t))
13560 (or (org-up-heading-safe) (error nil))
13561 (setq parent t)))
13562 (error nil)))))
13563 (if local
13564 tags
13565 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13567 (defun org-add-prop-inherited (s)
13568 (add-text-properties 0 (length s) '(inherited t) s)
13571 (defun org-toggle-tag (tag &optional onoff)
13572 "Toggle the tag TAG for the current line.
13573 If ONOFF is `on' or `off', don't toggle but set to this state."
13574 (let (res current)
13575 (save-excursion
13576 (org-back-to-heading t)
13577 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13578 (point-at-eol) t)
13579 (progn
13580 (setq current (match-string 1))
13581 (replace-match ""))
13582 (setq current ""))
13583 (setq current (nreverse (org-split-string current ":")))
13584 (cond
13585 ((eq onoff 'on)
13586 (setq res t)
13587 (or (member tag current) (push tag current)))
13588 ((eq onoff 'off)
13589 (or (not (member tag current)) (setq current (delete tag current))))
13590 (t (if (member tag current)
13591 (setq current (delete tag current))
13592 (setq res t)
13593 (push tag current))))
13594 (end-of-line 1)
13595 (if current
13596 (progn
13597 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13598 (org-set-tags nil t))
13599 (delete-horizontal-space))
13600 (run-hooks 'org-after-tags-change-hook))
13601 res))
13603 (defun org-align-tags-here (to-col)
13604 ;; Assumes that this is a headline
13605 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13606 (beginning-of-line 1)
13607 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13608 (< pos (match-beginning 2)))
13609 (progn
13610 (setq tags-l (- (match-end 2) (match-beginning 2)))
13611 (goto-char (match-beginning 1))
13612 (insert " ")
13613 (delete-region (point) (1+ (match-beginning 2)))
13614 (setq ncol (max (current-column)
13615 (1+ col)
13616 (if (> to-col 0)
13617 to-col
13618 (- (abs to-col) tags-l))))
13619 (setq p (point))
13620 (insert (make-string (- ncol (current-column)) ?\ ))
13621 (setq ncol (current-column))
13622 (when indent-tabs-mode (tabify p (point-at-eol)))
13623 (org-move-to-column (min ncol col) t))
13624 (goto-char pos))))
13626 (defun org-set-tags-command (&optional arg just-align)
13627 "Call the set-tags command for the current entry."
13628 (interactive "P")
13629 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13630 (org-set-tags arg just-align)
13631 (save-excursion
13632 (org-back-to-heading t)
13633 (org-set-tags arg just-align))))
13635 (defun org-set-tags-to (data)
13636 "Set the tags of the current entry to DATA, replacing the current tags.
13637 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13638 If DATA is nil or the empty string, any tags will be removed."
13639 (interactive "sTags: ")
13640 (setq data
13641 (cond
13642 ((eq data nil) "")
13643 ((equal data "") "")
13644 ((stringp data)
13645 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13646 ":"))
13647 ((listp data)
13648 (concat ":" (mapconcat 'identity data ":") ":"))
13649 (t nil)))
13650 (when data
13651 (save-excursion
13652 (org-back-to-heading t)
13653 (when (looking-at org-complex-heading-regexp)
13654 (if (match-end 5)
13655 (progn
13656 (goto-char (match-beginning 5))
13657 (insert data)
13658 (delete-region (point) (point-at-eol))
13659 (org-set-tags nil 'align))
13660 (goto-char (point-at-eol))
13661 (insert " " data)
13662 (org-set-tags nil 'align)))
13663 (beginning-of-line 1)
13664 (if (looking-at ".*?\\([ \t]+\\)$")
13665 (delete-region (match-beginning 1) (match-end 1))))))
13667 (defun org-align-all-tags ()
13668 "Align the tags i all headings."
13669 (interactive)
13670 (save-excursion
13671 (or (ignore-errors (org-back-to-heading t))
13672 (outline-next-heading))
13673 (if (org-at-heading-p)
13674 (org-set-tags t)
13675 (message "No headings"))))
13677 (defvar org-indent-indentation-per-level)
13678 (defun org-set-tags (&optional arg just-align)
13679 "Set the tags for the current headline.
13680 With prefix ARG, realign all tags in headings in the current buffer."
13681 (interactive "P")
13682 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13683 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13684 'region-start-level 'region))
13685 org-loop-over-headlines-in-active-region)
13686 (org-map-entries
13687 ;; We don't use ARG and JUST-ALIGN here these args are not
13688 ;; useful when looping over headlines
13689 `(org-set-tags)
13690 org-loop-over-headlines-in-active-region
13691 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13692 (let* ((re org-outline-regexp-bol)
13693 (current (unless arg (org-get-tags-string)))
13694 (col (current-column))
13695 (org-setting-tags t)
13696 table current-tags inherited-tags ; computed below when needed
13697 tags p0 c0 c1 rpl di tc level)
13698 (if arg
13699 (save-excursion
13700 (goto-char (point-min))
13701 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13702 (while (re-search-forward re nil t)
13703 (org-set-tags nil t)
13704 (end-of-line 1)))
13705 (message "All tags realigned to column %d" org-tags-column))
13706 (if just-align
13707 (setq tags current)
13708 ;; Get a new set of tags from the user
13709 (save-excursion
13710 (setq table (append org-tag-persistent-alist
13711 (or org-tag-alist (org-get-buffer-tags))
13712 (and
13713 org-complete-tags-always-offer-all-agenda-tags
13714 (org-global-tags-completion-table
13715 (org-agenda-files))))
13716 org-last-tags-completion-table table
13717 current-tags (org-split-string current ":")
13718 inherited-tags (nreverse
13719 (nthcdr (length current-tags)
13720 (nreverse (org-get-tags-at))))
13721 tags
13722 (if (or (eq t org-use-fast-tag-selection)
13723 (and org-use-fast-tag-selection
13724 (delq nil (mapcar 'cdr table))))
13725 (org-fast-tag-selection
13726 current-tags inherited-tags table
13727 (if org-fast-tag-selection-include-todo
13728 org-todo-key-alist))
13729 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13730 (org-trim
13731 (org-icompleting-read "Tags: "
13732 'org-tags-completion-function
13733 nil nil current 'org-tags-history))))))
13734 (while (string-match "[-+&]+" tags)
13735 ;; No boolean logic, just a list
13736 (setq tags (replace-match ":" t t tags))))
13738 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13740 (if org-tags-sort-function
13741 (setq tags (mapconcat 'identity
13742 (sort (org-split-string
13743 tags (org-re "[^[:alnum:]_@#%]+"))
13744 org-tags-sort-function) ":")))
13746 (if (string-match "\\`[\t ]*\\'" tags)
13747 (setq tags "")
13748 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13749 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13751 ;; Insert new tags at the correct column
13752 (beginning-of-line 1)
13753 (setq level (or (and (looking-at org-outline-regexp)
13754 (- (match-end 0) (point) 1))
13756 (cond
13757 ((and (equal current "") (equal tags "")))
13758 ((re-search-forward
13759 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13760 (point-at-eol) t)
13761 (if (equal tags "")
13762 (setq rpl "")
13763 (goto-char (match-beginning 0))
13764 (setq c0 (current-column)
13765 ;; compute offset for the case of org-indent-mode active
13766 di (if org-indent-mode
13767 (* (1- org-indent-indentation-per-level) (1- level))
13769 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13770 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13771 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13772 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13773 (replace-match rpl t t)
13774 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13775 tags)
13776 (t (error "Tags alignment failed")))
13777 (org-move-to-column col)
13778 (unless just-align
13779 (run-hooks 'org-after-tags-change-hook))))))
13781 (defun org-change-tag-in-region (beg end tag off)
13782 "Add or remove TAG for each entry in the region.
13783 This works in the agenda, and also in an org-mode buffer."
13784 (interactive
13785 (list (region-beginning) (region-end)
13786 (let ((org-last-tags-completion-table
13787 (if (derived-mode-p 'org-mode)
13788 (org-get-buffer-tags)
13789 (org-global-tags-completion-table))))
13790 (org-icompleting-read
13791 "Tag: " 'org-tags-completion-function nil nil nil
13792 'org-tags-history))
13793 (progn
13794 (message "[s]et or [r]emove? ")
13795 (equal (read-char-exclusive) ?r))))
13796 (if (fboundp 'deactivate-mark) (deactivate-mark))
13797 (let ((agendap (equal major-mode 'org-agenda-mode))
13798 l1 l2 m buf pos newhead (cnt 0))
13799 (goto-char end)
13800 (setq l2 (1- (org-current-line)))
13801 (goto-char beg)
13802 (setq l1 (org-current-line))
13803 (loop for l from l1 to l2 do
13804 (org-goto-line l)
13805 (setq m (get-text-property (point) 'org-hd-marker))
13806 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13807 (and agendap m))
13808 (setq buf (if agendap (marker-buffer m) (current-buffer))
13809 pos (if agendap m (point)))
13810 (with-current-buffer buf
13811 (save-excursion
13812 (save-restriction
13813 (goto-char pos)
13814 (setq cnt (1+ cnt))
13815 (org-toggle-tag tag (if off 'off 'on))
13816 (setq newhead (org-get-heading)))))
13817 (and agendap (org-agenda-change-all-lines newhead m))))
13818 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13820 (defun org-tags-completion-function (string predicate &optional flag)
13821 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13822 (confirm (lambda (x) (stringp (car x)))))
13823 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13824 (setq s1 (match-string 1 string)
13825 s2 (match-string 2 string))
13826 (setq s1 "" s2 string))
13827 (cond
13828 ((eq flag nil)
13829 ;; try completion
13830 (setq rtn (try-completion s2 ctable confirm))
13831 (if (stringp rtn)
13832 (setq rtn
13833 (concat s1 s2 (substring rtn (length s2))
13834 (if (and org-add-colon-after-tag-completion
13835 (assoc rtn ctable))
13836 ":" ""))))
13837 rtn)
13838 ((eq flag t)
13839 ;; all-completions
13840 (all-completions s2 ctable confirm)
13842 ((eq flag 'lambda)
13843 ;; exact match?
13844 (assoc s2 ctable)))
13847 (defun org-fast-tag-insert (kwd tags face &optional end)
13848 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13849 (insert (format "%-12s" (concat kwd ":"))
13850 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13851 (or end "")))
13853 (defun org-fast-tag-show-exit (flag)
13854 (save-excursion
13855 (org-goto-line 3)
13856 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13857 (replace-match ""))
13858 (when flag
13859 (end-of-line 1)
13860 (org-move-to-column (- (window-width) 19) t)
13861 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13863 (defun org-set-current-tags-overlay (current prefix)
13864 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13865 (if (featurep 'xemacs)
13866 (org-overlay-display org-tags-overlay (concat prefix s)
13867 'secondary-selection)
13868 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13869 (org-overlay-display org-tags-overlay (concat prefix s)))))
13871 (defvar org-last-tag-selection-key nil)
13872 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13873 "Fast tag selection with single keys.
13874 CURRENT is the current list of tags in the headline, INHERITED is the
13875 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13876 possibly with grouping information. TODO-TABLE is a similar table with
13877 TODO keywords, should these have keys assigned to them.
13878 If the keys are nil, a-z are automatically assigned.
13879 Returns the new tags string, or nil to not change the current settings."
13880 (let* ((fulltable (append table todo-table))
13881 (maxlen (apply 'max (mapcar
13882 (lambda (x)
13883 (if (stringp (car x)) (string-width (car x)) 0))
13884 fulltable)))
13885 (buf (current-buffer))
13886 (expert (eq org-fast-tag-selection-single-key 'expert))
13887 (buffer-tags nil)
13888 (fwidth (+ maxlen 3 1 3))
13889 (ncol (/ (- (window-width) 4) fwidth))
13890 (i-face 'org-done)
13891 (c-face 'org-todo)
13892 tg cnt e c char c1 c2 ntable tbl rtn
13893 ov-start ov-end ov-prefix
13894 (exit-after-next org-fast-tag-selection-single-key)
13895 (done-keywords org-done-keywords)
13896 groups ingroup)
13897 (save-excursion
13898 (beginning-of-line 1)
13899 (if (looking-at
13900 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13901 (setq ov-start (match-beginning 1)
13902 ov-end (match-end 1)
13903 ov-prefix "")
13904 (setq ov-start (1- (point-at-eol))
13905 ov-end (1+ ov-start))
13906 (skip-chars-forward "^\n\r")
13907 (setq ov-prefix
13908 (concat
13909 (buffer-substring (1- (point)) (point))
13910 (if (> (current-column) org-tags-column)
13912 (make-string (- org-tags-column (current-column)) ?\ ))))))
13913 (move-overlay org-tags-overlay ov-start ov-end)
13914 (save-window-excursion
13915 (if expert
13916 (set-buffer (get-buffer-create " *Org tags*"))
13917 (delete-other-windows)
13918 (split-window-vertically)
13919 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13920 (erase-buffer)
13921 (org-set-local 'org-done-keywords done-keywords)
13922 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13923 (org-fast-tag-insert "Current" current c-face "\n\n")
13924 (org-fast-tag-show-exit exit-after-next)
13925 (org-set-current-tags-overlay current ov-prefix)
13926 (setq tbl fulltable char ?a cnt 0)
13927 (while (setq e (pop tbl))
13928 (cond
13929 ((equal (car e) :startgroup)
13930 (push '() groups) (setq ingroup t)
13931 (when (not (= cnt 0))
13932 (setq cnt 0)
13933 (insert "\n"))
13934 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13935 ((equal (car e) :endgroup)
13936 (setq ingroup nil cnt 0)
13937 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13938 ((equal e '(:newline))
13939 (when (not (= cnt 0))
13940 (setq cnt 0)
13941 (insert "\n")
13942 (setq e (car tbl))
13943 (while (equal (car tbl) '(:newline))
13944 (insert "\n")
13945 (setq tbl (cdr tbl)))))
13947 (setq tg (copy-sequence (car e)) c2 nil)
13948 (if (cdr e)
13949 (setq c (cdr e))
13950 ;; automatically assign a character.
13951 (setq c1 (string-to-char
13952 (downcase (substring
13953 tg (if (= (string-to-char tg) ?@) 1 0)))))
13954 (if (or (rassoc c1 ntable) (rassoc c1 table))
13955 (while (or (rassoc char ntable) (rassoc char table))
13956 (setq char (1+ char)))
13957 (setq c2 c1))
13958 (setq c (or c2 char)))
13959 (if ingroup (push tg (car groups)))
13960 (setq tg (org-add-props tg nil 'face
13961 (cond
13962 ((not (assoc tg table))
13963 (org-get-todo-face tg))
13964 ((member tg current) c-face)
13965 ((member tg inherited) i-face)
13966 (t nil))))
13967 (if (and (= cnt 0) (not ingroup)) (insert " "))
13968 (insert "[" c "] " tg (make-string
13969 (- fwidth 4 (length tg)) ?\ ))
13970 (push (cons tg c) ntable)
13971 (when (= (setq cnt (1+ cnt)) ncol)
13972 (insert "\n")
13973 (if ingroup (insert " "))
13974 (setq cnt 0)))))
13975 (setq ntable (nreverse ntable))
13976 (insert "\n")
13977 (goto-char (point-min))
13978 (if (not expert) (org-fit-window-to-buffer))
13979 (setq rtn
13980 (catch 'exit
13981 (while t
13982 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13983 (if (not groups) "no " "")
13984 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13985 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13986 (setq org-last-tag-selection-key c)
13987 (cond
13988 ((= c ?\r) (throw 'exit t))
13989 ((= c ?!)
13990 (setq groups (not groups))
13991 (goto-char (point-min))
13992 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13993 ((= c ?\C-c)
13994 (if (not expert)
13995 (org-fast-tag-show-exit
13996 (setq exit-after-next (not exit-after-next)))
13997 (setq expert nil)
13998 (delete-other-windows)
13999 (set-window-buffer (split-window-vertically) " *Org tags*")
14000 (org-switch-to-buffer-other-window " *Org tags*")
14001 (org-fit-window-to-buffer)))
14002 ((or (= c ?\C-g)
14003 (and (= c ?q) (not (rassoc c ntable))))
14004 (org-detach-overlay org-tags-overlay)
14005 (setq quit-flag t))
14006 ((= c ?\ )
14007 (setq current nil)
14008 (if exit-after-next (setq exit-after-next 'now)))
14009 ((= c ?\t)
14010 (condition-case nil
14011 (setq tg (org-icompleting-read
14012 "Tag: "
14013 (or buffer-tags
14014 (with-current-buffer buf
14015 (org-get-buffer-tags)))))
14016 (quit (setq tg "")))
14017 (when (string-match "\\S-" tg)
14018 (add-to-list 'buffer-tags (list tg))
14019 (if (member tg current)
14020 (setq current (delete tg current))
14021 (push tg current)))
14022 (if exit-after-next (setq exit-after-next 'now)))
14023 ((setq e (rassoc c todo-table) tg (car e))
14024 (with-current-buffer buf
14025 (save-excursion (org-todo tg)))
14026 (if exit-after-next (setq exit-after-next 'now)))
14027 ((setq e (rassoc c ntable) tg (car e))
14028 (if (member tg current)
14029 (setq current (delete tg current))
14030 (loop for g in groups do
14031 (if (member tg g)
14032 (mapc (lambda (x)
14033 (setq current (delete x current)))
14034 g)))
14035 (push tg current))
14036 (if exit-after-next (setq exit-after-next 'now))))
14038 ;; Create a sorted list
14039 (setq current
14040 (sort current
14041 (lambda (a b)
14042 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14043 (if (eq exit-after-next 'now) (throw 'exit t))
14044 (goto-char (point-min))
14045 (beginning-of-line 2)
14046 (delete-region (point) (point-at-eol))
14047 (org-fast-tag-insert "Current" current c-face)
14048 (org-set-current-tags-overlay current ov-prefix)
14049 (while (re-search-forward
14050 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14051 (setq tg (match-string 1))
14052 (add-text-properties
14053 (match-beginning 1) (match-end 1)
14054 (list 'face
14055 (cond
14056 ((member tg current) c-face)
14057 ((member tg inherited) i-face)
14058 (t (get-text-property (match-beginning 1) 'face))))))
14059 (goto-char (point-min)))))
14060 (org-detach-overlay org-tags-overlay)
14061 (if rtn
14062 (mapconcat 'identity current ":")
14063 nil))))
14065 (defun org-get-tags-string ()
14066 "Get the TAGS string in the current headline."
14067 (unless (org-at-heading-p t)
14068 (error "Not on a heading"))
14069 (save-excursion
14070 (beginning-of-line 1)
14071 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14072 (org-match-string-no-properties 1)
14073 "")))
14075 (defun org-get-tags ()
14076 "Get the list of tags specified in the current headline."
14077 (org-split-string (org-get-tags-string) ":"))
14079 (defun org-get-buffer-tags ()
14080 "Get a table of all tags used in the buffer, for completion."
14081 (let (tags)
14082 (save-excursion
14083 (goto-char (point-min))
14084 (while (re-search-forward
14085 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14086 (when (equal (char-after (point-at-bol 0)) ?*)
14087 (mapc (lambda (x) (add-to-list 'tags x))
14088 (org-split-string (org-match-string-no-properties 1) ":")))))
14089 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14090 (mapcar 'list tags)))
14092 ;;;; The mapping API
14094 ;;;###autoload
14095 (defun org-map-entries (func &optional match scope &rest skip)
14096 "Call FUNC at each headline selected by MATCH in SCOPE.
14098 FUNC is a function or a lisp form. The function will be called without
14099 arguments, with the cursor positioned at the beginning of the headline.
14100 The return values of all calls to the function will be collected and
14101 returned as a list.
14103 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14104 does not need to preserve point. After evaluation, the cursor will be
14105 moved to the end of the line (presumably of the headline of the
14106 processed entry) and search continues from there. Under some
14107 circumstances, this may not produce the wanted results. For example,
14108 if you have removed (e.g. archived) the current (sub)tree it could
14109 mean that the next entry will be skipped entirely. In such cases, you
14110 can specify the position from where search should continue by making
14111 FUNC set the variable `org-map-continue-from' to the desired buffer
14112 position.
14114 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14115 Only headlines that are matched by this query will be considered during
14116 the iteration. When MATCH is nil or t, all headlines will be
14117 visited by the iteration.
14119 SCOPE determines the scope of this command. It can be any of:
14121 nil The current buffer, respecting the restriction if any
14122 tree The subtree started with the entry at point
14123 region The entries within the active region, if any
14124 region-start-level
14125 The entries within the active region, but only those at
14126 the same level than the first one.
14127 file The current buffer, without restriction
14128 file-with-archives
14129 The current buffer, and any archives associated with it
14130 agenda All agenda files
14131 agenda-with-archives
14132 All agenda files with any archive files associated with them
14133 \(file1 file2 ...)
14134 If this is a list, all files in the list will be scanned
14136 The remaining args are treated as settings for the skipping facilities of
14137 the scanner. The following items can be given here:
14139 archive skip trees with the archive tag.
14140 comment skip trees with the COMMENT keyword
14141 function or Emacs Lisp form:
14142 will be used as value for `org-agenda-skip-function', so whenever
14143 the function returns t, FUNC will not be called for that
14144 entry and search will continue from the point where the
14145 function leaves it.
14147 If your function needs to retrieve the tags including inherited tags
14148 at the *current* entry, you can use the value of the variable
14149 `org-scanner-tags' which will be much faster than getting the value
14150 with `org-get-tags-at'. If your function gets properties with
14151 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14152 to t around the call to `org-entry-properties' to get the same speedup.
14153 Note that if your function moves around to retrieve tags and properties at
14154 a *different* entry, you cannot use these techniques."
14155 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14156 (not (org-region-active-p)))
14157 (let* ((org-agenda-archives-mode nil) ; just to make sure
14158 (org-agenda-skip-archived-trees (memq 'archive skip))
14159 (org-agenda-skip-comment-trees (memq 'comment skip))
14160 (org-agenda-skip-function
14161 (car (org-delete-all '(comment archive) skip)))
14162 (org-tags-match-list-sublevels t)
14163 (start-level (eq scope 'region-start-level))
14164 matcher file res
14165 org-todo-keywords-for-agenda
14166 org-done-keywords-for-agenda
14167 org-todo-keyword-alist-for-agenda
14168 org-drawers-for-agenda
14169 org-tag-alist-for-agenda
14170 todo-only)
14172 (cond
14173 ((eq match t) (setq matcher t))
14174 ((eq match nil) (setq matcher t))
14175 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14177 (save-excursion
14178 (save-restriction
14179 (cond ((eq scope 'tree)
14180 (org-back-to-heading t)
14181 (org-narrow-to-subtree)
14182 (setq scope nil))
14183 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14184 (org-region-active-p))
14185 ;; If needed, set start-level to a string like "2"
14186 (when start-level
14187 (save-excursion
14188 (goto-char (region-beginning))
14189 (unless (org-at-heading-p) (outline-next-heading))
14190 (setq start-level (org-current-level))))
14191 (narrow-to-region (region-beginning)
14192 (save-excursion
14193 (goto-char (region-end))
14194 (unless (and (bolp) (org-at-heading-p))
14195 (outline-next-heading))
14196 (point)))
14197 (setq scope nil)))
14199 (if (not scope)
14200 (progn
14201 (org-prepare-agenda-buffers
14202 (list (buffer-file-name (current-buffer))))
14203 (setq res (org-scan-tags func matcher todo-only start-level)))
14204 ;; Get the right scope
14205 (cond
14206 ((and scope (listp scope) (symbolp (car scope)))
14207 (setq scope (eval scope)))
14208 ((eq scope 'agenda)
14209 (setq scope (org-agenda-files t)))
14210 ((eq scope 'agenda-with-archives)
14211 (setq scope (org-agenda-files t))
14212 (setq scope (org-add-archive-files scope)))
14213 ((eq scope 'file)
14214 (setq scope (list (buffer-file-name))))
14215 ((eq scope 'file-with-archives)
14216 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14217 (org-prepare-agenda-buffers scope)
14218 (while (setq file (pop scope))
14219 (with-current-buffer (org-find-base-buffer-visiting file)
14220 (save-excursion
14221 (save-restriction
14222 (widen)
14223 (goto-char (point-min))
14224 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14225 res)))
14227 ;;;; Properties
14229 ;;; Setting and retrieving properties
14231 (defconst org-special-properties
14232 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14233 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14234 "The special properties valid in Org-mode.
14236 These are properties that are not defined in the property drawer,
14237 but in some other way.")
14239 (defconst org-default-properties
14240 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14241 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14242 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14243 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14244 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14245 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14246 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14247 "Some properties that are used by Org-mode for various purposes.
14248 Being in this list makes sure that they are offered for completion.")
14250 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14251 "Regular expression matching the first line of a property drawer.")
14253 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14254 "Regular expression matching the last line of a property drawer.")
14256 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14257 "Regular expression matching the first line of a property drawer.")
14259 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14260 "Regular expression matching the first line of a property drawer.")
14262 (defconst org-property-drawer-re
14263 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14264 org-property-end-re "\\)\n?")
14265 "Matches an entire property drawer.")
14267 (defconst org-clock-drawer-re
14268 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14269 org-property-end-re "\\)\n?")
14270 "Matches an entire clock drawer.")
14272 (defsubst org-re-property (property)
14273 "Return a regexp matching a PROPERTY line.
14274 Match group 1 will be set to the value."
14275 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14277 (defsubst org-re-property-keyword (property)
14278 "Return a regexp matching a PROPERTY line, possibly with no
14279 value for the property."
14280 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14282 (defun org-property-action ()
14283 "Do an action on properties."
14284 (interactive)
14285 (let (c)
14286 (org-at-property-p)
14287 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14288 (setq c (read-char-exclusive))
14289 (cond
14290 ((equal c ?s)
14291 (call-interactively 'org-set-property))
14292 ((equal c ?d)
14293 (call-interactively 'org-delete-property))
14294 ((equal c ?D)
14295 (call-interactively 'org-delete-property-globally))
14296 ((equal c ?c)
14297 (call-interactively 'org-compute-property-at-point))
14298 (t (error "No such property action %c" c)))))
14300 (defun org-inc-effort ()
14301 "Increment the value of the effort property in the current entry."
14302 (interactive)
14303 (org-set-effort nil t))
14305 (defun org-set-effort (&optional value increment)
14306 "Set the effort property of the current entry.
14307 With numerical prefix arg, use the nth allowed value, 0 stands for the
14308 10th allowed value.
14310 When INCREMENT is non-nil, set the property to the next allowed value."
14311 (interactive "P")
14312 (if (equal value 0) (setq value 10))
14313 (let* ((completion-ignore-case t)
14314 (prop org-effort-property)
14315 (cur (org-entry-get nil prop))
14316 (allowed (org-property-get-allowed-values nil prop 'table))
14317 (existing (mapcar 'list (org-property-values prop)))
14319 (val (cond
14320 ((stringp value) value)
14321 ((and allowed (integerp value))
14322 (or (car (nth (1- value) allowed))
14323 (car (org-last allowed))))
14324 ((and allowed increment)
14325 (or (caadr (member (list cur) allowed))
14326 (error "Allowed effort values are not set")))
14327 (allowed
14328 (message "Select 1-9,0, [RET%s]: %s"
14329 (if cur (concat "=" cur) "")
14330 (mapconcat 'car allowed " "))
14331 (setq rpl (read-char-exclusive))
14332 (if (equal rpl ?\r)
14334 (setq rpl (- rpl ?0))
14335 (if (equal rpl 0) (setq rpl 10))
14336 (if (and (> rpl 0) (<= rpl (length allowed)))
14337 (car (nth (1- rpl) allowed))
14338 (org-completing-read "Effort: " allowed nil))))
14340 (let (org-completion-use-ido org-completion-use-iswitchb)
14341 (org-completing-read
14342 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14343 (concat "[" cur "]") "")
14344 ": ")
14345 existing nil nil "" nil cur))))))
14346 (unless (equal (org-entry-get nil prop) val)
14347 (org-entry-put nil prop val))
14348 (message "%s is now %s" prop val)))
14350 (defun org-at-property-p ()
14351 "Is cursor inside a property drawer?"
14352 (save-excursion
14353 (beginning-of-line 1)
14354 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14355 (save-match-data ;; Used by calling procedures
14356 (let ((p (point))
14357 (range (unless (org-before-first-heading-p)
14358 (org-get-property-block))))
14359 (and range (<= (car range) p) (< p (cdr range))))))))
14361 (defun org-get-property-block (&optional beg end force)
14362 "Return the (beg . end) range of the body of the property drawer.
14363 BEG and END are the beginning and end of the current subtree, or of
14364 the part before the first headline. If they are not given, they will
14365 be found. If the drawer does not exist and FORCE is non-nil, create
14366 the drawer."
14367 (catch 'exit
14368 (save-excursion
14369 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14370 (progn (org-back-to-heading t) (point))))
14371 (end (or end (and (not (outline-next-heading)) (point-max))
14372 (point))))
14373 (goto-char beg)
14374 (if (re-search-forward org-property-start-re end t)
14375 (setq beg (1+ (match-end 0)))
14376 (if force
14377 (save-excursion
14378 (org-insert-property-drawer)
14379 (setq end (progn (outline-next-heading) (point))))
14380 (throw 'exit nil))
14381 (goto-char beg)
14382 (if (re-search-forward org-property-start-re end t)
14383 (setq beg (1+ (match-end 0)))))
14384 (if (re-search-forward org-property-end-re end t)
14385 (setq end (match-beginning 0))
14386 (or force (throw 'exit nil))
14387 (goto-char beg)
14388 (setq end beg)
14389 (org-indent-line)
14390 (insert ":END:\n"))
14391 (cons beg end)))))
14393 (defun org-entry-properties (&optional pom which specific)
14394 "Get all properties of the entry at point-or-marker POM.
14395 This includes the TODO keyword, the tags, time strings for deadline,
14396 scheduled, and clocking, and any additional properties defined in the
14397 entry. The return value is an alist, keys may occur multiple times
14398 if the property key was used several times.
14399 POM may also be nil, in which case the current entry is used.
14400 If WHICH is nil or `all', get all properties. If WHICH is
14401 `special' or `standard', only get that subclass. If WHICH
14402 is a string only get exactly this property. SPECIFIC can be a string, the
14403 specific property we are interested in. Specifying it can speed
14404 things up because then unnecessary parsing is avoided."
14405 (setq which (or which 'all))
14406 (org-with-point-at pom
14407 (let ((clockstr (substring org-clock-string 0 -1))
14408 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14409 (case-fold-search nil)
14410 beg end range props sum-props key key1 value string clocksum clocksumt)
14411 (save-excursion
14412 (when (condition-case nil
14413 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14414 (error nil))
14415 (setq beg (point))
14416 (setq sum-props (get-text-property (point) 'org-summaries))
14417 (setq clocksum (get-text-property (point) :org-clock-minutes)
14418 clocksumt (get-text-property (point) :org-clock-minutes-today))
14419 (outline-next-heading)
14420 (setq end (point))
14421 (when (memq which '(all special))
14422 ;; Get the special properties, like TODO and tags
14423 (goto-char beg)
14424 (when (and (or (not specific) (string= specific "TODO"))
14425 (looking-at org-todo-line-regexp) (match-end 2))
14426 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14427 (when (and (or (not specific) (string= specific "PRIORITY"))
14428 (looking-at org-priority-regexp))
14429 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14430 (when (or (not specific) (string= specific "FILE"))
14431 (push (cons "FILE" buffer-file-name) props))
14432 (when (and (or (not specific) (string= specific "TAGS"))
14433 (setq value (org-get-tags-string))
14434 (string-match "\\S-" value))
14435 (push (cons "TAGS" value) props))
14436 (when (and (or (not specific) (string= specific "ALLTAGS"))
14437 (setq value (org-get-tags-at)))
14438 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14439 ":"))
14440 props))
14441 (when (or (not specific) (string= specific "BLOCKED"))
14442 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14443 (when (or (not specific)
14444 (member specific
14445 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14446 "TIMESTAMP" "TIMESTAMP_IA")))
14447 (catch 'match
14448 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14449 (setq key (if (match-end 1)
14450 (substring (org-match-string-no-properties 1)
14451 0 -1))
14452 string (if (equal key clockstr)
14453 (org-trim
14454 (buffer-substring-no-properties
14455 (match-beginning 3) (goto-char
14456 (point-at-eol))))
14457 (substring (org-match-string-no-properties 3)
14458 1 -1)))
14459 ;; Get the correct property name from the key. This is
14460 ;; necessary if the user has configured time keywords.
14461 (setq key1 (concat key ":"))
14462 (cond
14463 ((not key)
14464 (setq key
14465 (if (= (char-after (match-beginning 3)) ?\[)
14466 "TIMESTAMP_IA" "TIMESTAMP")))
14467 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14468 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14469 ((equal key1 org-closed-string) (setq key "CLOSED"))
14470 ((equal key1 org-clock-string) (setq key "CLOCK")))
14471 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14472 (progn
14473 (push (cons key string) props)
14474 ;; no need to search further if match is found
14475 (throw 'match t))
14476 (when (or (equal key "CLOCK") (not (assoc key props)))
14477 (push (cons key string) props)))))))
14479 (when (memq which '(all standard))
14480 ;; Get the standard properties, like :PROP: ...
14481 (setq range (org-get-property-block beg end))
14482 (when range
14483 (goto-char (car range))
14484 (while (re-search-forward
14485 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14486 (cdr range) t)
14487 (setq key (org-match-string-no-properties 1)
14488 value (org-trim (or (org-match-string-no-properties 2) "")))
14489 (unless (member key excluded)
14490 (push (cons key (or value "")) props)))))
14491 (if clocksum
14492 (push (cons "CLOCKSUM"
14493 (org-columns-number-to-string (/ (float clocksum) 60.)
14494 'add_times))
14495 props))
14496 (if clocksumt
14497 (push (cons "CLOCKSUM_T"
14498 (org-columns-number-to-string (/ (float clocksumt) 60.)
14499 'add_times))
14500 props))
14501 (unless (assoc "CATEGORY" props)
14502 (push (cons "CATEGORY" (org-get-category)) props))
14503 (append sum-props (nreverse props)))))))
14505 (defun org-entry-get (pom property &optional inherit literal-nil)
14506 "Get value of PROPERTY for entry or content at point-or-marker POM.
14507 If INHERIT is non-nil and the entry does not have the property,
14508 then also check higher levels of the hierarchy.
14509 If INHERIT is the symbol `selective', use inheritance only if the setting
14510 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14511 If the property is present but empty, the return value is the empty string.
14512 If the property is not present at all, nil is returned.
14514 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14515 do not interpret it as the list atom nil. This is used for inheritance
14516 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14517 (org-with-point-at pom
14518 (if (and inherit (if (eq inherit 'selective)
14519 (org-property-inherit-p property)
14521 (org-entry-get-with-inheritance property literal-nil)
14522 (if (member property org-special-properties)
14523 ;; We need a special property. Use `org-entry-properties' to
14524 ;; retrieve it, but specify the wanted property
14525 (cdr (assoc property (org-entry-properties nil 'special property)))
14526 (let* ((range (org-get-property-block))
14527 (props (list (or (assoc property org-file-properties)
14528 (assoc property org-global-properties)
14529 (assoc property org-global-properties-fixed))))
14530 (ap (lambda (key)
14531 (when (re-search-forward
14532 (org-re-property key) (cdr range) t)
14533 (setq props
14534 (org-update-property-plist
14536 (if (match-end 1)
14537 (org-match-string-no-properties 1) "")
14538 props)))))
14539 val)
14540 (when (and range (goto-char (car range)))
14541 (funcall ap property)
14542 (goto-char (car range))
14543 (while (funcall ap (concat property "+")))
14544 (setq val (cdr (assoc property props)))
14545 (when val (if literal-nil val (org-not-nil val)))))))))
14547 (defun org-property-or-variable-value (var &optional inherit)
14548 "Check if there is a property fixing the value of VAR.
14549 If yes, return this value. If not, return the current value of the variable."
14550 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14551 (if (and prop (stringp prop) (string-match "\\S-" prop))
14552 (read prop)
14553 (symbol-value var))))
14555 (defun org-entry-delete (pom property)
14556 "Delete the property PROPERTY from entry at point-or-marker POM."
14557 (org-with-point-at pom
14558 (if (member property org-special-properties)
14559 nil ; cannot delete these properties.
14560 (let ((range (org-get-property-block)))
14561 (if (and range
14562 (goto-char (car range))
14563 (re-search-forward
14564 (org-re-property property)
14565 (cdr range) t))
14566 (progn
14567 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14569 nil)))))
14571 ;; Multi-values properties are properties that contain multiple values
14572 ;; These values are assumed to be single words, separated by whitespace.
14573 (defun org-entry-add-to-multivalued-property (pom property value)
14574 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14575 (let* ((old (org-entry-get pom property))
14576 (values (and old (org-split-string old "[ \t]"))))
14577 (setq value (org-entry-protect-space value))
14578 (unless (member value values)
14579 (setq values (cons value values))
14580 (org-entry-put pom property
14581 (mapconcat 'identity values " ")))))
14583 (defun org-entry-remove-from-multivalued-property (pom property value)
14584 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14585 (let* ((old (org-entry-get pom property))
14586 (values (and old (org-split-string old "[ \t]"))))
14587 (setq value (org-entry-protect-space value))
14588 (when (member value values)
14589 (setq values (delete value values))
14590 (org-entry-put pom property
14591 (mapconcat 'identity values " ")))))
14593 (defun org-entry-member-in-multivalued-property (pom property value)
14594 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14595 (let* ((old (org-entry-get pom property))
14596 (values (and old (org-split-string old "[ \t]"))))
14597 (setq value (org-entry-protect-space value))
14598 (member value values)))
14600 (defun org-entry-get-multivalued-property (pom property)
14601 "Return a list of values in a multivalued property."
14602 (let* ((value (org-entry-get pom property))
14603 (values (and value (org-split-string value "[ \t]"))))
14604 (mapcar 'org-entry-restore-space values)))
14606 (defun org-entry-put-multivalued-property (pom property &rest values)
14607 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14608 VALUES should be a list of strings. Spaces will be protected."
14609 (org-entry-put pom property
14610 (mapconcat 'org-entry-protect-space values " "))
14611 (let* ((value (org-entry-get pom property))
14612 (values (and value (org-split-string value "[ \t]"))))
14613 (mapcar 'org-entry-restore-space values)))
14615 (defun org-entry-protect-space (s)
14616 "Protect spaces and newline in string S."
14617 (while (string-match " " s)
14618 (setq s (replace-match "%20" t t s)))
14619 (while (string-match "\n" s)
14620 (setq s (replace-match "%0A" t t s)))
14623 (defun org-entry-restore-space (s)
14624 "Restore spaces and newline in string S."
14625 (while (string-match "%20" s)
14626 (setq s (replace-match " " t t s)))
14627 (while (string-match "%0A" s)
14628 (setq s (replace-match "\n" t t s)))
14631 (defvar org-entry-property-inherited-from (make-marker)
14632 "Marker pointing to the entry from where a property was inherited.
14633 Each call to `org-entry-get-with-inheritance' will set this marker to the
14634 location of the entry where the inheritance search matched. If there was
14635 no match, the marker will point nowhere.
14636 Note that also `org-entry-get' calls this function, if the INHERIT flag
14637 is set.")
14639 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14640 "Get PROPERTY of entry or content at point, search higher levels if needed.
14641 The search will stop at the first ancestor which has the property defined.
14642 If the value found is \"nil\", return nil to show that the property
14643 should be considered as undefined (this is the meaning of nil here).
14644 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14645 (move-marker org-entry-property-inherited-from nil)
14646 (let (tmp)
14647 (save-excursion
14648 (save-restriction
14649 (widen)
14650 (catch 'ex
14651 (while t
14652 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14653 (or (ignore-errors (org-back-to-heading t))
14654 (goto-char (point-min)))
14655 (move-marker org-entry-property-inherited-from (point))
14656 (throw 'ex tmp))
14657 (or (ignore-errors (org-up-heading-safe))
14658 (throw 'ex nil))))))
14659 (setq tmp (or tmp
14660 (cdr (assoc property org-file-properties))
14661 (cdr (assoc property org-global-properties))
14662 (cdr (assoc property org-global-properties-fixed))))
14663 (if literal-nil tmp (org-not-nil tmp))))
14665 (defvar org-property-changed-functions nil
14666 "Hook called when the value of a property has changed.
14667 Each hook function should accept two arguments, the name of the property
14668 and the new value.")
14670 (defun org-entry-put (pom property value)
14671 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14672 (org-with-point-at pom
14673 (org-back-to-heading t)
14674 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14675 range)
14676 (cond
14677 ((equal property "TODO")
14678 (when (and (stringp value) (string-match "\\S-" value)
14679 (not (member value org-todo-keywords-1)))
14680 (error "\"%s\" is not a valid TODO state" value))
14681 (if (or (not value)
14682 (not (string-match "\\S-" value)))
14683 (setq value 'none))
14684 (org-todo value)
14685 (org-set-tags nil 'align))
14686 ((equal property "PRIORITY")
14687 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14688 (string-to-char value) ?\ ))
14689 (org-set-tags nil 'align))
14690 ((equal property "SCHEDULED")
14691 (if (re-search-forward org-scheduled-time-regexp end t)
14692 (cond
14693 ((eq value 'earlier) (org-timestamp-change -1 'day))
14694 ((eq value 'later) (org-timestamp-change 1 'day))
14695 (t (call-interactively 'org-schedule)))
14696 (call-interactively 'org-schedule)))
14697 ((equal property "DEADLINE")
14698 (if (re-search-forward org-deadline-time-regexp end t)
14699 (cond
14700 ((eq value 'earlier) (org-timestamp-change -1 'day))
14701 ((eq value 'later) (org-timestamp-change 1 'day))
14702 (t (call-interactively 'org-deadline)))
14703 (call-interactively 'org-deadline)))
14704 ((member property org-special-properties)
14705 (error "The %s property can not yet be set with `org-entry-put'"
14706 property))
14707 (t ; a non-special property
14708 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14709 (setq range (org-get-property-block beg end 'force))
14710 (goto-char (car range))
14711 (if (re-search-forward
14712 (org-re-property-keyword property) (cdr range) t)
14713 (progn
14714 (delete-region (match-beginning 0) (match-end 0))
14715 (goto-char (match-beginning 0)))
14716 (goto-char (cdr range))
14717 (insert "\n")
14718 (backward-char 1)
14719 (org-indent-line))
14720 (insert ":" property ":")
14721 (and value (insert " " value))
14722 (org-indent-line)))))
14723 (run-hook-with-args 'org-property-changed-functions property value)))
14725 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14726 "Get all property keys in the current buffer.
14727 With INCLUDE-SPECIALS, also list the special properties that reflect things
14728 like tags and TODO state.
14729 With INCLUDE-DEFAULTS, also include properties that has special meaning
14730 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14731 and others.
14732 With INCLUDE-COLUMNS, also include property names given in COLUMN
14733 formats in the current buffer."
14734 (let (rtn range cfmt s p)
14735 (save-excursion
14736 (save-restriction
14737 (widen)
14738 (goto-char (point-min))
14739 (while (re-search-forward org-property-start-re nil t)
14740 (setq range (org-get-property-block))
14741 (goto-char (car range))
14742 (while (re-search-forward
14743 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14744 (cdr range) t)
14745 (add-to-list 'rtn (org-match-string-no-properties 1)))
14746 (outline-next-heading))))
14748 (when include-specials
14749 (setq rtn (append org-special-properties rtn)))
14751 (when include-defaults
14752 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14753 (add-to-list 'rtn org-effort-property))
14755 (when include-columns
14756 (save-excursion
14757 (save-restriction
14758 (widen)
14759 (goto-char (point-min))
14760 (while (re-search-forward
14761 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14762 nil t)
14763 (setq cfmt (match-string 2) s 0)
14764 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14765 cfmt s)
14766 (setq s (match-end 0)
14767 p (match-string 1 cfmt))
14768 (unless (or (equal p "ITEM")
14769 (member p org-special-properties))
14770 (add-to-list 'rtn (match-string 1 cfmt))))))))
14772 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14774 (defun org-property-values (key)
14775 "Return a list of all values of property KEY in the current buffer."
14776 (save-excursion
14777 (save-restriction
14778 (widen)
14779 (goto-char (point-min))
14780 (let ((re (org-re-property key))
14781 values)
14782 (while (re-search-forward re nil t)
14783 (add-to-list 'values (org-trim (match-string 1))))
14784 (delete "" values)))))
14786 (defun org-insert-property-drawer ()
14787 "Insert a property drawer into the current entry."
14788 (org-back-to-heading t)
14789 (looking-at org-outline-regexp)
14790 (let ((indent (if org-adapt-indentation
14791 (- (match-end 0) (match-beginning 0))
14793 (beg (point))
14794 (re (concat "^[ \t]*" org-keyword-time-regexp))
14795 end hiddenp)
14796 (outline-next-heading)
14797 (setq end (point))
14798 (goto-char beg)
14799 (while (re-search-forward re end t))
14800 (setq hiddenp (outline-invisible-p))
14801 (end-of-line 1)
14802 (and (equal (char-after) ?\n) (forward-char 1))
14803 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14804 (if (member (match-string 1) '("CLOCK:" ":END:"))
14805 ;; just skip this line
14806 (beginning-of-line 2)
14807 ;; Drawer start, find the end
14808 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14809 (beginning-of-line 1)))
14810 (org-skip-over-state-notes)
14811 (skip-chars-backward " \t\n\r")
14812 (if (eq (char-before) ?*) (forward-char 1))
14813 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14814 (beginning-of-line 0)
14815 (org-indent-to-column indent)
14816 (beginning-of-line 2)
14817 (org-indent-to-column indent)
14818 (beginning-of-line 0)
14819 (if hiddenp
14820 (save-excursion
14821 (org-back-to-heading t)
14822 (hide-entry))
14823 (org-flag-drawer t))))
14825 (defun org-insert-drawer (&optional arg drawer)
14826 "Insert a drawer at point.
14828 Optional argument DRAWER, when non-nil, is a string representing
14829 drawer's name. Otherwise, the user is prompted for a name.
14831 If a region is active, insert the drawer around that region
14832 instead.
14834 Point is left between drawer's boundaries."
14835 (interactive "P")
14836 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14837 "LOGBOOK"))
14838 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14839 ;; internally by Org. They are meant to be inserted
14840 ;; automatically.
14841 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14842 ;; Remove system drawers from list. Note: For some reason,
14843 ;; `org-completing-read' ignores the predicate while
14844 ;; `completing-read' handles it fine.
14845 (drawer (if arg "PROPERTIES"
14846 (or drawer
14847 (completing-read
14848 "Drawer: " org-drawers
14849 (lambda (d) (not (member d system-drawers))))))))
14850 (cond
14851 ;; With C-u, fall back on `org-insert-property-drawer'
14852 (arg (org-insert-property-drawer))
14853 ;; With an active region, insert a drawer at point.
14854 ((not (org-region-active-p))
14855 (progn
14856 (unless (bolp) (insert "\n"))
14857 (insert (format ":%s:\n\n:END:\n" drawer))
14858 (forward-line -2)))
14859 ;; Otherwise, insert the drawer at point
14861 (let ((rbeg (region-beginning))
14862 (rend (copy-marker (region-end))))
14863 (unwind-protect
14864 (progn
14865 (goto-char rbeg)
14866 (beginning-of-line)
14867 (when (save-excursion
14868 (re-search-forward org-outline-regexp-bol rend t))
14869 (error "Drawers cannot contain headlines"))
14870 ;; Position point at the beginning of the first
14871 ;; non-blank line in region. Insert drawer's opening
14872 ;; there, then indent it.
14873 (org-skip-whitespace)
14874 (beginning-of-line)
14875 (insert ":" drawer ":\n")
14876 (forward-line -1)
14877 (indent-for-tab-command)
14878 ;; Move point to the beginning of the first blank line
14879 ;; after the last non-blank line in region. Insert
14880 ;; drawer's closing, then indent it.
14881 (goto-char rend)
14882 (skip-chars-backward " \r\t\n")
14883 (insert "\n:END:")
14884 (indent-for-tab-command)
14885 (unless (eolp) (insert "\n")))
14886 ;; Clear marker, whatever the outcome of insertion is.
14887 (set-marker rend nil)))))))
14889 (defvar org-property-set-functions-alist nil
14890 "Property set function alist.
14891 Each entry should have the following format:
14893 (PROPERTY . READ-FUNCTION)
14895 The read function will be called with the same argument as
14896 `org-completing-read'.")
14898 (defun org-set-property-function (property)
14899 "Get the function that should be used to set PROPERTY.
14900 This is computed according to `org-property-set-functions-alist'."
14901 (or (cdr (assoc property org-property-set-functions-alist))
14902 'org-completing-read))
14904 (defun org-read-property-value (property)
14905 "Read PROPERTY value from user."
14906 (let* ((completion-ignore-case t)
14907 (allowed (org-property-get-allowed-values nil property 'table))
14908 (cur (org-entry-get nil property))
14909 (prompt (concat property " value"
14910 (if (and cur (string-match "\\S-" cur))
14911 (concat " [" cur "]") "") ": "))
14912 (set-function (org-set-property-function property))
14913 (val (if allowed
14914 (funcall set-function prompt allowed nil
14915 (not (get-text-property 0 'org-unrestricted
14916 (caar allowed))))
14917 (let (org-completion-use-ido org-completion-use-iswitchb)
14918 (funcall set-function prompt
14919 (mapcar 'list (org-property-values property))
14920 nil nil "" nil cur)))))
14921 (if (equal val "")
14923 val)))
14925 (defvar org-last-set-property nil)
14926 (defun org-read-property-name ()
14927 "Read a property name."
14928 (let* ((completion-ignore-case t)
14929 (keys (org-buffer-property-keys nil t t))
14930 (default-prop (or (save-excursion
14931 (save-match-data
14932 (beginning-of-line)
14933 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14934 (null (string= (match-string 1) "END"))
14935 (match-string 1))))
14936 org-last-set-property))
14937 (property (org-icompleting-read
14938 (concat "Property"
14939 (if default-prop (concat " [" default-prop "]") "")
14940 ": ")
14941 (mapcar 'list keys)
14942 nil nil nil nil
14943 default-prop
14945 (if (member property keys)
14946 property
14947 (or (cdr (assoc (downcase property)
14948 (mapcar (lambda (x) (cons (downcase x) x))
14949 keys)))
14950 property))))
14952 (defun org-set-property (property value)
14953 "In the current entry, set PROPERTY to VALUE.
14954 When called interactively, this will prompt for a property name, offering
14955 completion on existing and default properties. And then it will prompt
14956 for a value, offering completion either on allowed values (via an inherited
14957 xxx_ALL property) or on existing values in other instances of this property
14958 in the current file."
14959 (interactive (list nil nil))
14960 (let* ((property (or property (org-read-property-name)))
14961 (value (or value (org-read-property-value property)))
14962 (fn (cdr (assoc property org-properties-postprocess-alist))))
14963 (setq org-last-set-property property)
14964 ;; Possibly postprocess the inserted value:
14965 (when fn (setq value (funcall fn value)))
14966 (unless (equal (org-entry-get nil property) value)
14967 (org-entry-put nil property value))))
14969 (defun org-delete-property (property)
14970 "In the current entry, delete PROPERTY."
14971 (interactive
14972 (let* ((completion-ignore-case t)
14973 (prop (org-icompleting-read "Property: "
14974 (org-entry-properties nil 'standard))))
14975 (list prop)))
14976 (message "Property %s %s" property
14977 (if (org-entry-delete nil property)
14978 "deleted"
14979 "was not present in the entry")))
14981 (defun org-delete-property-globally (property)
14982 "Remove PROPERTY globally, from all entries."
14983 (interactive
14984 (let* ((completion-ignore-case t)
14985 (prop (org-icompleting-read
14986 "Globally remove property: "
14987 (mapcar 'list (org-buffer-property-keys)))))
14988 (list prop)))
14989 (save-excursion
14990 (save-restriction
14991 (widen)
14992 (goto-char (point-min))
14993 (let ((cnt 0))
14994 (while (re-search-forward
14995 (org-re-property property)
14996 nil t)
14997 (setq cnt (1+ cnt))
14998 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14999 (message "Property \"%s\" removed from %d entries" property cnt)))))
15001 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15003 (defun org-compute-property-at-point ()
15004 "Compute the property at point.
15005 This looks for an enclosing column format, extracts the operator and
15006 then applies it to the property in the column format's scope."
15007 (interactive)
15008 (unless (org-at-property-p)
15009 (error "Not at a property"))
15010 (let ((prop (org-match-string-no-properties 2)))
15011 (org-columns-get-format-and-top-level)
15012 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15013 (error "No operator defined for property %s" prop))
15014 (org-columns-compute prop)))
15016 (defvar org-property-allowed-value-functions nil
15017 "Hook for functions supplying allowed values for a specific property.
15018 The functions must take a single argument, the name of the property, and
15019 return a flat list of allowed values. If \":ETC\" is one of
15020 the values, this means that these values are intended as defaults for
15021 completion, but that other values should be allowed too.
15022 The functions must return nil if they are not responsible for this
15023 property.")
15025 (defun org-property-get-allowed-values (pom property &optional table)
15026 "Get allowed values for the property PROPERTY.
15027 When TABLE is non-nil, return an alist that can directly be used for
15028 completion."
15029 (let (vals)
15030 (cond
15031 ((equal property "TODO")
15032 (setq vals (org-with-point-at pom
15033 (append org-todo-keywords-1 '("")))))
15034 ((equal property "PRIORITY")
15035 (let ((n org-lowest-priority))
15036 (while (>= n org-highest-priority)
15037 (push (char-to-string n) vals)
15038 (setq n (1- n)))))
15039 ((member property org-special-properties))
15040 ((setq vals (run-hook-with-args-until-success
15041 'org-property-allowed-value-functions property)))
15043 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15044 (when (and vals (string-match "\\S-" vals))
15045 (setq vals (car (read-from-string (concat "(" vals ")"))))
15046 (setq vals (mapcar (lambda (x)
15047 (cond ((stringp x) x)
15048 ((numberp x) (number-to-string x))
15049 ((symbolp x) (symbol-name x))
15050 (t "???")))
15051 vals)))))
15052 (when (member ":ETC" vals)
15053 (setq vals (remove ":ETC" vals))
15054 (org-add-props (car vals) '(org-unrestricted t)))
15055 (if table (mapcar 'list vals) vals)))
15057 (defun org-property-previous-allowed-value (&optional previous)
15058 "Switch to the next allowed value for this property."
15059 (interactive)
15060 (org-property-next-allowed-value t))
15062 (defun org-property-next-allowed-value (&optional previous)
15063 "Switch to the next allowed value for this property."
15064 (interactive)
15065 (unless (org-at-property-p)
15066 (error "Not at a property"))
15067 (let* ((key (match-string 2))
15068 (value (match-string 3))
15069 (allowed (or (org-property-get-allowed-values (point) key)
15070 (and (member value '("[ ]" "[-]" "[X]"))
15071 '("[ ]" "[X]"))))
15072 nval)
15073 (unless allowed
15074 (error "Allowed values for this property have not been defined"))
15075 (if previous (setq allowed (reverse allowed)))
15076 (if (member value allowed)
15077 (setq nval (car (cdr (member value allowed)))))
15078 (setq nval (or nval (car allowed)))
15079 (if (equal nval value)
15080 (error "Only one allowed value for this property"))
15081 (org-at-property-p)
15082 (replace-match (concat " :" key ": " nval) t t)
15083 (org-indent-line)
15084 (beginning-of-line 1)
15085 (skip-chars-forward " \t")
15086 (run-hook-with-args 'org-property-changed-functions key nval)))
15088 (defun org-find-olp (path &optional this-buffer)
15089 "Return a marker pointing to the entry at outline path OLP.
15090 If anything goes wrong, throw an error.
15091 You can wrap this call to catch the error like this:
15093 (condition-case msg
15094 (org-mobile-locate-entry (match-string 4))
15095 (error (nth 1 msg)))
15097 The return value will then be either a string with the error message,
15098 or a marker if everything is OK.
15100 If THIS-BUFFER is set, the outline path does not contain a file,
15101 only headings."
15102 (let* ((file (if this-buffer buffer-file-name (pop path)))
15103 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15104 (level 1)
15105 (lmin 1)
15106 (lmax 1)
15107 limit re end found pos heading cnt flevel)
15108 (unless buffer (error "File not found :%s" file))
15109 (with-current-buffer buffer
15110 (save-excursion
15111 (save-restriction
15112 (widen)
15113 (setq limit (point-max))
15114 (goto-char (point-min))
15115 (while (setq heading (pop path))
15116 (setq re (format org-complex-heading-regexp-format
15117 (regexp-quote heading)))
15118 (setq cnt 0 pos (point))
15119 (while (re-search-forward re end t)
15120 (setq level (- (match-end 1) (match-beginning 1)))
15121 (if (and (>= level lmin) (<= level lmax))
15122 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15123 (when (= cnt 0) (error "Heading not found on level %d: %s"
15124 lmax heading))
15125 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15126 lmax heading))
15127 (goto-char found)
15128 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15129 (setq end (save-excursion (org-end-of-subtree t t))))
15130 (when (org-at-heading-p)
15131 (move-marker (make-marker) (point))))))))
15133 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15134 "Find node HEADING in BUFFER.
15135 Return a marker to the heading if it was found, or nil if not.
15136 If POS-ONLY is set, return just the position instead of a marker.
15138 The heading text must match exact, but it may have a TODO keyword,
15139 a priority cookie and tags in the standard locations."
15140 (with-current-buffer (or buffer (current-buffer))
15141 (save-excursion
15142 (save-restriction
15143 (widen)
15144 (goto-char (point-min))
15145 (let (case-fold-search)
15146 (if (re-search-forward
15147 (format org-complex-heading-regexp-format
15148 (regexp-quote heading)) nil t)
15149 (if pos-only
15150 (match-beginning 0)
15151 (move-marker (make-marker) (match-beginning 0)))))))))
15153 (defun org-find-exact-heading-in-directory (heading &optional dir)
15154 "Find Org node headline HEADING in all .org files in directory DIR.
15155 When the target headline is found, return a marker to this location."
15156 (let ((files (directory-files (or dir default-directory)
15157 nil "\\`[^.#].*\\.org\\'"))
15158 file visiting m buffer)
15159 (catch 'found
15160 (while (setq file (pop files))
15161 (message "trying %s" file)
15162 (setq visiting (org-find-base-buffer-visiting file))
15163 (setq buffer (or visiting (find-file-noselect file)))
15164 (setq m (org-find-exact-headline-in-buffer
15165 heading buffer))
15166 (when (and (not m) (not visiting)) (kill-buffer buffer))
15167 (and m (throw 'found m))))))
15169 (defun org-find-entry-with-id (ident)
15170 "Locate the entry that contains the ID property with exact value IDENT.
15171 IDENT can be a string, a symbol or a number, this function will search for
15172 the string representation of it.
15173 Return the position where this entry starts, or nil if there is no such entry."
15174 (interactive "sID: ")
15175 (let ((id (cond
15176 ((stringp ident) ident)
15177 ((symbol-name ident) (symbol-name ident))
15178 ((numberp ident) (number-to-string ident))
15179 (t (error "IDENT %s must be a string, symbol or number" ident))))
15180 (case-fold-search nil))
15181 (save-excursion
15182 (save-restriction
15183 (widen)
15184 (goto-char (point-min))
15185 (when (re-search-forward
15186 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15187 nil t)
15188 (org-back-to-heading t)
15189 (point))))))
15191 ;;;; Timestamps
15193 (defvar org-last-changed-timestamp nil)
15194 (defvar org-last-inserted-timestamp nil
15195 "The last time stamp inserted with `org-insert-time-stamp'.")
15196 (defvar org-time-was-given) ; dynamically scoped parameter
15197 (defvar org-end-time-was-given) ; dynamically scoped parameter
15198 (defvar org-ts-what) ; dynamically scoped parameter
15200 (defun org-time-stamp (arg &optional inactive)
15201 "Prompt for a date/time and insert a time stamp.
15202 If the user specifies a time like HH:MM or if this command is
15203 called with at least one prefix argument, the time stamp contains
15204 the date and the time. Otherwise, only the date is be included.
15206 All parts of a date not specified by the user is filled in from
15207 the current date/time. So if you just press return without
15208 typing anything, the time stamp will represent the current
15209 date/time.
15211 If there is already a timestamp at the cursor, it will be
15212 modified.
15214 With two universal prefix arguments, insert an active timestamp
15215 with the current time without prompting the user."
15216 (interactive "P")
15217 (let* ((ts nil)
15218 (default-time
15219 ;; Default time is either today, or, when entering a range,
15220 ;; the range start.
15221 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15222 (save-excursion
15223 (re-search-backward
15224 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15225 (- (point) 20) t)))
15226 (apply 'encode-time (org-parse-time-string (match-string 1)))
15227 (current-time)))
15228 (default-input (and ts (org-get-compact-tod ts)))
15229 (repeater (save-excursion
15230 (save-match-data
15231 (beginning-of-line)
15232 (when (re-search-forward
15233 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15234 (save-excursion (progn (end-of-line) (point))) t)
15235 (match-string 0)))))
15236 org-time-was-given org-end-time-was-given time)
15237 (cond
15238 ((and (org-at-timestamp-p t)
15239 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15240 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15241 (insert "--")
15242 (setq time (let ((this-command this-command))
15243 (org-read-date arg 'totime nil nil
15244 default-time default-input inactive)))
15245 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15246 ((org-at-timestamp-p t)
15247 (setq time (let ((this-command this-command))
15248 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15249 (when (org-at-timestamp-p t) ; just to get the match data
15250 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15251 (replace-match "")
15252 (setq org-last-changed-timestamp
15253 (org-insert-time-stamp
15254 time (or org-time-was-given arg)
15255 inactive nil nil (list org-end-time-was-given)))
15256 (when repeater (goto-char (1- (point))) (insert " " repeater)
15257 (setq org-last-changed-timestamp
15258 (concat (substring org-last-inserted-timestamp 0 -1)
15259 " " repeater ">"))))
15260 (message "Timestamp updated"))
15261 ((equal arg '(16))
15262 (org-insert-time-stamp (current-time) t))
15264 (setq time (let ((this-command this-command))
15265 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15266 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15267 nil nil (list org-end-time-was-given))))))
15269 ;; FIXME: can we use this for something else, like computing time differences?
15270 (defun org-get-compact-tod (s)
15271 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15272 (let* ((t1 (match-string 1 s))
15273 (h1 (string-to-number (match-string 2 s)))
15274 (m1 (string-to-number (match-string 3 s)))
15275 (t2 (and (match-end 4) (match-string 5 s)))
15276 (h2 (and t2 (string-to-number (match-string 6 s))))
15277 (m2 (and t2 (string-to-number (match-string 7 s))))
15278 dh dm)
15279 (if (not t2)
15281 (setq dh (- h2 h1) dm (- m2 m1))
15282 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15283 (concat t1 "+" (number-to-string dh)
15284 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15286 (defun org-time-stamp-inactive (&optional arg)
15287 "Insert an inactive time stamp.
15288 An inactive time stamp is enclosed in square brackets instead of angle
15289 brackets. It is inactive in the sense that it does not trigger agenda entries,
15290 does not link to the calendar and cannot be changed with the S-cursor keys.
15291 So these are more for recording a certain time/date."
15292 (interactive "P")
15293 (org-time-stamp arg 'inactive))
15295 (defvar org-date-ovl (make-overlay 1 1))
15296 (overlay-put org-date-ovl 'face 'org-date-selected)
15297 (org-detach-overlay org-date-ovl)
15299 (defvar org-ans1) ; dynamically scoped parameter
15300 (defvar org-ans2) ; dynamically scoped parameter
15302 (defvar org-plain-time-of-day-regexp) ; defined below
15304 (defvar org-overriding-default-time nil) ; dynamically scoped
15305 (defvar org-read-date-overlay nil)
15306 (defvar org-dcst nil) ; dynamically scoped
15307 (defvar org-read-date-history nil)
15308 (defvar org-read-date-final-answer nil)
15309 (defvar org-read-date-analyze-futurep nil)
15310 (defvar org-read-date-analyze-forced-year nil)
15311 (defvar org-read-date-inactive)
15313 (defun org-read-date (&optional org-with-time to-time from-string prompt
15314 default-time default-input inactive)
15315 "Read a date, possibly a time, and make things smooth for the user.
15316 The prompt will suggest to enter an ISO date, but you can also enter anything
15317 which will at least partially be understood by `parse-time-string'.
15318 Unrecognized parts of the date will default to the current day, month, year,
15319 hour and minute. If this command is called to replace a timestamp at point,
15320 or to enter the second timestamp of a range, the default time is taken
15321 from the existing stamp. Furthermore, the command prefers the future,
15322 so if you are giving a date where the year is not given, and the day-month
15323 combination is already past in the current year, it will assume you
15324 mean next year. For details, see the manual. A few examples:
15326 3-2-5 --> 2003-02-05
15327 feb 15 --> currentyear-02-15
15328 2/15 --> currentyear-02-15
15329 sep 12 9 --> 2009-09-12
15330 12:45 --> today 12:45
15331 22 sept 0:34 --> currentyear-09-22 0:34
15332 12 --> currentyear-currentmonth-12
15333 Fri --> nearest Friday (today or later)
15334 etc.
15336 Furthermore you can specify a relative date by giving, as the *first* thing
15337 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15338 change in days weeks, months, years.
15339 With a single plus or minus, the date is relative to today. With a double
15340 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15341 +4d --> four days from today
15342 +4 --> same as above
15343 +2w --> two weeks from today
15344 ++5 --> five days from default date
15346 The function understands only English month and weekday abbreviations.
15348 While prompting, a calendar is popped up - you can also select the
15349 date with the mouse (button 1). The calendar shows a period of three
15350 months. To scroll it to other months, use the keys `>' and `<'.
15351 If you don't like the calendar, turn it off with
15352 \(setq org-read-date-popup-calendar nil)
15354 With optional argument TO-TIME, the date will immediately be converted
15355 to an internal time.
15356 With an optional argument WITH-TIME, the prompt will suggest to also
15357 insert a time. Note that when WITH-TIME is not set, you can still
15358 enter a time, and this function will inform the calling routine about
15359 this change. The calling routine may then choose to change the format
15360 used to insert the time stamp into the buffer to include the time.
15361 With optional argument FROM-STRING, read from this string instead from
15362 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15363 the time/date that is used for everything that is not specified by the
15364 user."
15365 (require 'parse-time)
15366 (let* ((org-time-stamp-rounding-minutes
15367 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15368 (org-dcst org-display-custom-times)
15369 (ct (org-current-time))
15370 (org-def (or org-overriding-default-time default-time ct))
15371 (org-defdecode (decode-time org-def))
15372 (dummy (progn
15373 (when (< (nth 2 org-defdecode) org-extend-today-until)
15374 (setcar (nthcdr 2 org-defdecode) -1)
15375 (setcar (nthcdr 1 org-defdecode) 59)
15376 (setq org-def (apply 'encode-time org-defdecode)
15377 org-defdecode (decode-time org-def)))))
15378 (calendar-frame-setup nil)
15379 (calendar-setup nil)
15380 (calendar-move-hook nil)
15381 (calendar-view-diary-initially-flag nil)
15382 (calendar-view-holidays-initially-flag nil)
15383 (timestr (format-time-string
15384 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15385 (prompt (concat (if prompt (concat prompt " ") "")
15386 (format "Date+time [%s]: " timestr)))
15387 ans (org-ans0 "") org-ans1 org-ans2 final)
15389 (cond
15390 (from-string (setq ans from-string))
15391 (org-read-date-popup-calendar
15392 (save-excursion
15393 (save-window-excursion
15394 (calendar)
15395 (org-eval-in-calendar '(setq cursor-type nil) t)
15396 (unwind-protect
15397 (progn
15398 (calendar-forward-day (- (time-to-days org-def)
15399 (calendar-absolute-from-gregorian
15400 (calendar-current-date))))
15401 (org-eval-in-calendar nil t)
15402 (let* ((old-map (current-local-map))
15403 (map (copy-keymap calendar-mode-map))
15404 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15405 (org-defkey map (kbd "RET") 'org-calendar-select)
15406 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15407 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15408 (org-defkey minibuffer-local-map [(meta shift left)]
15409 (lambda () (interactive)
15410 (org-eval-in-calendar '(calendar-backward-month 1))))
15411 (org-defkey minibuffer-local-map [(meta shift right)]
15412 (lambda () (interactive)
15413 (org-eval-in-calendar '(calendar-forward-month 1))))
15414 (org-defkey minibuffer-local-map [(meta shift up)]
15415 (lambda () (interactive)
15416 (org-eval-in-calendar '(calendar-backward-year 1))))
15417 (org-defkey minibuffer-local-map [(meta shift down)]
15418 (lambda () (interactive)
15419 (org-eval-in-calendar '(calendar-forward-year 1))))
15420 (org-defkey minibuffer-local-map [?\e (shift left)]
15421 (lambda () (interactive)
15422 (org-eval-in-calendar '(calendar-backward-month 1))))
15423 (org-defkey minibuffer-local-map [?\e (shift right)]
15424 (lambda () (interactive)
15425 (org-eval-in-calendar '(calendar-forward-month 1))))
15426 (org-defkey minibuffer-local-map [?\e (shift up)]
15427 (lambda () (interactive)
15428 (org-eval-in-calendar '(calendar-backward-year 1))))
15429 (org-defkey minibuffer-local-map [?\e (shift down)]
15430 (lambda () (interactive)
15431 (org-eval-in-calendar '(calendar-forward-year 1))))
15432 (org-defkey minibuffer-local-map [(shift up)]
15433 (lambda () (interactive)
15434 (org-eval-in-calendar '(calendar-backward-week 1))))
15435 (org-defkey minibuffer-local-map [(shift down)]
15436 (lambda () (interactive)
15437 (org-eval-in-calendar '(calendar-forward-week 1))))
15438 (org-defkey minibuffer-local-map [(shift left)]
15439 (lambda () (interactive)
15440 (org-eval-in-calendar '(calendar-backward-day 1))))
15441 (org-defkey minibuffer-local-map [(shift right)]
15442 (lambda () (interactive)
15443 (org-eval-in-calendar '(calendar-forward-day 1))))
15444 (org-defkey minibuffer-local-map ">"
15445 (lambda () (interactive)
15446 (org-eval-in-calendar '(scroll-calendar-left 1))))
15447 (org-defkey minibuffer-local-map "<"
15448 (lambda () (interactive)
15449 (org-eval-in-calendar '(scroll-calendar-right 1))))
15450 (org-defkey minibuffer-local-map "\C-v"
15451 (lambda () (interactive)
15452 (org-eval-in-calendar
15453 '(calendar-scroll-left-three-months 1))))
15454 (org-defkey minibuffer-local-map "\M-v"
15455 (lambda () (interactive)
15456 (org-eval-in-calendar
15457 '(calendar-scroll-right-three-months 1))))
15458 (run-hooks 'org-read-date-minibuffer-setup-hook)
15459 (unwind-protect
15460 (progn
15461 (use-local-map map)
15462 (setq org-read-date-inactive inactive)
15463 (add-hook 'post-command-hook 'org-read-date-display)
15464 (setq org-ans0 (read-string prompt default-input
15465 'org-read-date-history nil))
15466 ;; org-ans0: from prompt
15467 ;; org-ans1: from mouse click
15468 ;; org-ans2: from calendar motion
15469 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15470 (remove-hook 'post-command-hook 'org-read-date-display)
15471 (use-local-map old-map)
15472 (when org-read-date-overlay
15473 (delete-overlay org-read-date-overlay)
15474 (setq org-read-date-overlay nil)))))
15475 (bury-buffer "*Calendar*")))))
15477 (t ; Naked prompt only
15478 (unwind-protect
15479 (setq ans (read-string prompt default-input
15480 'org-read-date-history timestr))
15481 (when org-read-date-overlay
15482 (delete-overlay org-read-date-overlay)
15483 (setq org-read-date-overlay nil)))))
15485 (setq final (org-read-date-analyze ans org-def org-defdecode))
15487 (when org-read-date-analyze-forced-year
15488 (message "Year was forced into %s"
15489 (if org-read-date-force-compatible-dates
15490 "compatible range (1970-2037)"
15491 "range representable on this machine"))
15492 (ding))
15494 ;; One round trip to get rid of 34th of August and stuff like that....
15495 (setq final (decode-time (apply 'encode-time final)))
15497 (setq org-read-date-final-answer ans)
15499 (if to-time
15500 (apply 'encode-time final)
15501 (if (and (boundp 'org-time-was-given) org-time-was-given)
15502 (format "%04d-%02d-%02d %02d:%02d"
15503 (nth 5 final) (nth 4 final) (nth 3 final)
15504 (nth 2 final) (nth 1 final))
15505 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15507 (defvar org-def)
15508 (defvar org-defdecode)
15509 (defvar org-with-time)
15510 (defun org-read-date-display ()
15511 "Display the current date prompt interpretation in the minibuffer."
15512 (when org-read-date-display-live
15513 (when org-read-date-overlay
15514 (delete-overlay org-read-date-overlay))
15515 (when (minibufferp (current-buffer))
15516 (save-excursion
15517 (end-of-line 1)
15518 (while (not (equal (buffer-substring
15519 (max (point-min) (- (point) 4)) (point))
15520 " "))
15521 (insert " ")))
15522 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15523 " " (or org-ans1 org-ans2)))
15524 (org-end-time-was-given nil)
15525 (f (org-read-date-analyze ans org-def org-defdecode))
15526 (fmts (if org-dcst
15527 org-time-stamp-custom-formats
15528 org-time-stamp-formats))
15529 (fmt (if (or org-with-time
15530 (and (boundp 'org-time-was-given) org-time-was-given))
15531 (cdr fmts)
15532 (car fmts)))
15533 (txt (format-time-string fmt (apply 'encode-time f)))
15534 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15535 (txt (concat "=> " txt)))
15536 (when (and org-end-time-was-given
15537 (string-match org-plain-time-of-day-regexp txt))
15538 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15539 org-end-time-was-given
15540 (substring txt (match-end 0)))))
15541 (when org-read-date-analyze-futurep
15542 (setq txt (concat txt " (=>F)")))
15543 (setq org-read-date-overlay
15544 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15545 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15547 (defun org-read-date-analyze (ans org-def org-defdecode)
15548 "Analyze the combined answer of the date prompt."
15549 ;; FIXME: cleanup and comment
15550 (let ((nowdecode (decode-time (current-time)))
15551 delta deltan deltaw deltadef year month day
15552 hour minute second wday pm h2 m2 tl wday1
15553 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15554 (setq org-read-date-analyze-futurep nil
15555 org-read-date-analyze-forced-year nil)
15556 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15557 (setq ans "+0"))
15559 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15560 (setq ans (replace-match "" t t ans)
15561 deltan (car delta)
15562 deltaw (nth 1 delta)
15563 deltadef (nth 2 delta)))
15565 ;; Check if there is an iso week date in there
15566 ;; If yes, store the info and postpone interpreting it until the rest
15567 ;; of the parsing is done
15568 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15569 (setq iso-year (if (match-end 1)
15570 (org-small-year-to-year
15571 (string-to-number (match-string 1 ans))))
15572 iso-weekday (if (match-end 3)
15573 (string-to-number (match-string 3 ans)))
15574 iso-week (string-to-number (match-string 2 ans)))
15575 (setq ans (replace-match "" t t ans)))
15577 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15578 (when (string-match
15579 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15580 (setq year (if (match-end 2)
15581 (string-to-number (match-string 2 ans))
15582 (progn (setq kill-year t)
15583 (string-to-number (format-time-string "%Y"))))
15584 month (string-to-number (match-string 3 ans))
15585 day (string-to-number (match-string 4 ans)))
15586 (if (< year 100) (setq year (+ 2000 year)))
15587 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15588 t nil ans)))
15590 ;; Help matching dotted european dates
15591 (when (string-match
15592 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15593 (setq year (if (match-end 3)
15594 (string-to-number (match-string 3 ans))
15595 (progn (setq kill-year t)
15596 (string-to-number (format-time-string "%Y"))))
15597 day (string-to-number (match-string 1 ans))
15598 month (string-to-number (match-string 2 ans))
15599 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15600 t nil ans)))
15602 ;; Help matching american dates, like 5/30 or 5/30/7
15603 (when (string-match
15604 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15605 (setq year (if (match-end 4)
15606 (string-to-number (match-string 4 ans))
15607 (progn (setq kill-year t)
15608 (string-to-number (format-time-string "%Y"))))
15609 month (string-to-number (match-string 1 ans))
15610 day (string-to-number (match-string 2 ans)))
15611 (if (< year 100) (setq year (+ 2000 year)))
15612 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15613 t nil ans)))
15614 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15615 ;; If there is a time with am/pm, and *no* time without it, we convert
15616 ;; so that matching will be successful.
15617 (loop for i from 1 to 2 do ; twice, for end time as well
15618 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15619 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15620 (setq hour (string-to-number (match-string 1 ans))
15621 minute (if (match-end 3)
15622 (string-to-number (match-string 3 ans))
15624 pm (equal ?p
15625 (string-to-char (downcase (match-string 4 ans)))))
15626 (if (and (= hour 12) (not pm))
15627 (setq hour 0)
15628 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15629 (setq ans (replace-match (format "%02d:%02d" hour minute)
15630 t t ans))))
15632 ;; Check if a time range is given as a duration
15633 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15634 (setq hour (string-to-number (match-string 1 ans))
15635 h2 (+ hour (string-to-number (match-string 3 ans)))
15636 minute (string-to-number (match-string 2 ans))
15637 m2 (+ minute (if (match-end 5) (string-to-number
15638 (match-string 5 ans))0)))
15639 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15640 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15641 t t ans)))
15643 ;; Check if there is a time range
15644 (when (boundp 'org-end-time-was-given)
15645 (setq org-time-was-given nil)
15646 (when (and (string-match org-plain-time-of-day-regexp ans)
15647 (match-end 8))
15648 (setq org-end-time-was-given (match-string 8 ans))
15649 (setq ans (concat (substring ans 0 (match-beginning 7))
15650 (substring ans (match-end 7))))))
15652 (setq tl (parse-time-string ans)
15653 day (or (nth 3 tl) (nth 3 org-defdecode))
15654 month (or (nth 4 tl)
15655 (if (and org-read-date-prefer-future
15656 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15657 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15658 (nth 4 org-defdecode)))
15659 year (or (and (not kill-year) (nth 5 tl))
15660 (if (and org-read-date-prefer-future
15661 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15662 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15663 (nth 5 org-defdecode)))
15664 hour (or (nth 2 tl) (nth 2 org-defdecode))
15665 minute (or (nth 1 tl) (nth 1 org-defdecode))
15666 second (or (nth 0 tl) 0)
15667 wday (nth 6 tl))
15669 (when (and (eq org-read-date-prefer-future 'time)
15670 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15671 (equal day (nth 3 nowdecode))
15672 (equal month (nth 4 nowdecode))
15673 (equal year (nth 5 nowdecode))
15674 (nth 2 tl)
15675 (or (< (nth 2 tl) (nth 2 nowdecode))
15676 (and (= (nth 2 tl) (nth 2 nowdecode))
15677 (nth 1 tl)
15678 (< (nth 1 tl) (nth 1 nowdecode)))))
15679 (setq day (1+ day)
15680 futurep t))
15682 ;; Special date definitions below
15683 (cond
15684 (iso-week
15685 ;; There was an iso week
15686 (require 'cal-iso)
15687 (setq futurep nil)
15688 (setq year (or iso-year year)
15689 day (or iso-weekday wday 1)
15690 wday nil ; to make sure that the trigger below does not match
15691 iso-date (calendar-gregorian-from-absolute
15692 (calendar-absolute-from-iso
15693 (list iso-week day year))))
15694 ; FIXME: Should we also push ISO weeks into the future?
15695 ; (when (and org-read-date-prefer-future
15696 ; (not iso-year)
15697 ; (< (calendar-absolute-from-gregorian iso-date)
15698 ; (time-to-days (current-time))))
15699 ; (setq year (1+ year)
15700 ; iso-date (calendar-gregorian-from-absolute
15701 ; (calendar-absolute-from-iso
15702 ; (list iso-week day year)))))
15703 (setq month (car iso-date)
15704 year (nth 2 iso-date)
15705 day (nth 1 iso-date)))
15706 (deltan
15707 (setq futurep nil)
15708 (unless deltadef
15709 (let ((now (decode-time (current-time))))
15710 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15711 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15712 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15713 ((equal deltaw "m") (setq month (+ month deltan)))
15714 ((equal deltaw "y") (setq year (+ year deltan)))))
15715 ((and wday (not (nth 3 tl)))
15716 (setq futurep nil)
15717 ;; Weekday was given, but no day, so pick that day in the week
15718 ;; on or after the derived date.
15719 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15720 (unless (equal wday wday1)
15721 (setq day (+ day (% (- wday wday1 -7) 7))))))
15722 (if (and (boundp 'org-time-was-given)
15723 (nth 2 tl))
15724 (setq org-time-was-given t))
15725 (if (< year 100) (setq year (+ 2000 year)))
15726 ;; Check of the date is representable
15727 (if org-read-date-force-compatible-dates
15728 (progn
15729 (if (< year 1970)
15730 (setq year 1970 org-read-date-analyze-forced-year t))
15731 (if (> year 2037)
15732 (setq year 2037 org-read-date-analyze-forced-year t)))
15733 (condition-case nil
15734 (ignore (encode-time second minute hour day month year))
15735 (error
15736 (setq year (nth 5 org-defdecode))
15737 (setq org-read-date-analyze-forced-year t))))
15738 (setq org-read-date-analyze-futurep futurep)
15739 (list second minute hour day month year)))
15741 (defvar parse-time-weekdays)
15742 (defun org-read-date-get-relative (s today default)
15743 "Check string S for special relative date string.
15744 TODAY and DEFAULT are internal times, for today and for a default.
15745 Return shift list (N what def-flag)
15746 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15747 N is the number of WHATs to shift.
15748 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15749 the DEFAULT date rather than TODAY."
15750 (require 'parse-time)
15751 (when (and
15752 (string-match
15753 (concat
15754 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15755 "\\([0-9]+\\)?"
15756 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15757 "\\([ \t]\\|$\\)") s)
15758 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15759 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15760 (string-to-char (substring (match-string 1 s) -1))
15761 ?+))
15762 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15763 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15764 (what (if (match-end 3) (match-string 3 s) "d"))
15765 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15766 (date (if rel default today))
15767 (wday (nth 6 (decode-time date)))
15768 delta)
15769 (if wday1
15770 (progn
15771 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15772 (if (= dir ?-) (setq delta (- delta 7)))
15773 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15774 (list delta "d" rel))
15775 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15777 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15778 "Turn a user-specified date into the internal representation.
15779 The internal representation needed by the calendar is (month day year).
15780 This is a wrapper to handle the brain-dead convention in calendar that
15781 user function argument order change dependent on argument order."
15782 (if (boundp 'calendar-date-style)
15783 (cond
15784 ((eq calendar-date-style 'american)
15785 (list arg1 arg2 arg3))
15786 ((eq calendar-date-style 'european)
15787 (list arg2 arg1 arg3))
15788 ((eq calendar-date-style 'iso)
15789 (list arg2 arg3 arg1)))
15790 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15791 (if (org-bound-and-true-p european-calendar-style)
15792 (list arg2 arg1 arg3)
15793 (list arg1 arg2 arg3)))))
15795 (defun org-eval-in-calendar (form &optional keepdate)
15796 "Eval FORM in the calendar window and return to current window.
15797 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15798 otherwise stick to the current value of `org-ans2'."
15799 (let ((sf (selected-frame))
15800 (sw (selected-window)))
15801 (select-window (get-buffer-window "*Calendar*" t))
15802 (eval form)
15803 (when (and (not keepdate) (calendar-cursor-to-date))
15804 (let* ((date (calendar-cursor-to-date))
15805 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15806 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15807 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15808 (select-window sw)
15809 (org-select-frame-set-input-focus sf)))
15811 (defun org-calendar-select ()
15812 "Return to `org-read-date' with the date currently selected.
15813 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15814 (interactive)
15815 (when (calendar-cursor-to-date)
15816 (let* ((date (calendar-cursor-to-date))
15817 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15818 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15819 (if (active-minibuffer-window) (exit-minibuffer))))
15821 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15822 "Insert a date stamp for the date given by the internal TIME.
15823 WITH-HM means use the stamp format that includes the time of the day.
15824 INACTIVE means use square brackets instead of angular ones, so that the
15825 stamp will not contribute to the agenda.
15826 PRE and POST are optional strings to be inserted before and after the
15827 stamp.
15828 The command returns the inserted time stamp."
15829 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15830 stamp)
15831 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15832 (insert-before-markers (or pre ""))
15833 (when (listp extra)
15834 (setq extra (car extra))
15835 (if (and (stringp extra)
15836 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15837 (setq extra (format "-%02d:%02d"
15838 (string-to-number (match-string 1 extra))
15839 (string-to-number (match-string 2 extra))))
15840 (setq extra nil)))
15841 (when extra
15842 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15843 (insert-before-markers (setq stamp (format-time-string fmt time)))
15844 (insert-before-markers (or post ""))
15845 (setq org-last-inserted-timestamp stamp)))
15847 (defun org-toggle-time-stamp-overlays ()
15848 "Toggle the use of custom time stamp formats."
15849 (interactive)
15850 (setq org-display-custom-times (not org-display-custom-times))
15851 (unless org-display-custom-times
15852 (let ((p (point-min)) (bmp (buffer-modified-p)))
15853 (while (setq p (next-single-property-change p 'display))
15854 (if (and (get-text-property p 'display)
15855 (eq (get-text-property p 'face) 'org-date))
15856 (remove-text-properties
15857 p (setq p (next-single-property-change p 'display))
15858 '(display t))))
15859 (set-buffer-modified-p bmp)))
15860 (if (featurep 'xemacs)
15861 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15862 (org-restart-font-lock)
15863 (setq org-table-may-need-update t)
15864 (if org-display-custom-times
15865 (message "Time stamps are overlaid with custom format")
15866 (message "Time stamp overlays removed")))
15868 (defun org-display-custom-time (beg end)
15869 "Overlay modified time stamp format over timestamp between BEG and END."
15870 (let* ((ts (buffer-substring beg end))
15871 t1 w1 with-hm tf time str w2 (off 0))
15872 (save-match-data
15873 (setq t1 (org-parse-time-string ts t))
15874 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15875 (setq off (- (match-end 0) (match-beginning 0)))))
15876 (setq end (- end off))
15877 (setq w1 (- end beg)
15878 with-hm (and (nth 1 t1) (nth 2 t1))
15879 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15880 time (org-fix-decoded-time t1)
15881 str (org-add-props
15882 (format-time-string
15883 (substring tf 1 -1) (apply 'encode-time time))
15884 nil 'mouse-face 'highlight)
15885 w2 (length str))
15886 (if (not (= w2 w1))
15887 (add-text-properties (1+ beg) (+ 2 beg)
15888 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15889 (if (featurep 'xemacs)
15890 (progn
15891 (put-text-property beg end 'invisible t)
15892 (put-text-property beg end 'end-glyph (make-glyph str)))
15893 (put-text-property beg end 'display str))))
15895 (defun org-translate-time (string)
15896 "Translate all timestamps in STRING to custom format.
15897 But do this only if the variable `org-display-custom-times' is set."
15898 (when org-display-custom-times
15899 (save-match-data
15900 (let* ((start 0)
15901 (re org-ts-regexp-both)
15902 t1 with-hm inactive tf time str beg end)
15903 (while (setq start (string-match re string start))
15904 (setq beg (match-beginning 0)
15905 end (match-end 0)
15906 t1 (save-match-data
15907 (org-parse-time-string (substring string beg end) t))
15908 with-hm (and (nth 1 t1) (nth 2 t1))
15909 inactive (equal (substring string beg (1+ beg)) "[")
15910 tf (funcall (if with-hm 'cdr 'car)
15911 org-time-stamp-custom-formats)
15912 time (org-fix-decoded-time t1)
15913 str (format-time-string
15914 (concat
15915 (if inactive "[" "<") (substring tf 1 -1)
15916 (if inactive "]" ">"))
15917 (apply 'encode-time time))
15918 string (replace-match str t t string)
15919 start (+ start (length str)))))))
15920 string)
15922 (defun org-fix-decoded-time (time)
15923 "Set 0 instead of nil for the first 6 elements of time.
15924 Don't touch the rest."
15925 (let ((n 0))
15926 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15928 (defun org-days-to-time (timestamp-string)
15929 "Difference between TIMESTAMP-STRING and now in days."
15930 (- (time-to-days (org-time-string-to-time timestamp-string))
15931 (time-to-days (current-time))))
15933 (defun org-deadline-close (timestamp-string &optional ndays)
15934 "Is the time in TIMESTAMP-STRING close to the current date?"
15935 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15936 (and (< (org-days-to-time timestamp-string) ndays)
15937 (not (org-entry-is-done-p))))
15939 (defun org-get-wdays (ts)
15940 "Get the deadline lead time appropriate for timestring TS."
15941 (cond
15942 ((<= org-deadline-warning-days 0)
15943 ;; 0 or negative, enforce this value no matter what
15944 (- org-deadline-warning-days))
15945 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15946 ;; lead time is specified.
15947 (floor (* (string-to-number (match-string 1 ts))
15948 (cdr (assoc (match-string 2 ts)
15949 '(("d" . 1) ("w" . 7)
15950 ("m" . 30.4) ("y" . 365.25)))))))
15951 ;; go for the default.
15952 (t org-deadline-warning-days)))
15954 (defun org-calendar-select-mouse (ev)
15955 "Return to `org-read-date' with the date currently selected.
15956 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15957 (interactive "e")
15958 (mouse-set-point ev)
15959 (when (calendar-cursor-to-date)
15960 (let* ((date (calendar-cursor-to-date))
15961 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15962 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15963 (if (active-minibuffer-window) (exit-minibuffer))))
15965 (defun org-check-deadlines (ndays)
15966 "Check if there are any deadlines due or past due.
15967 A deadline is considered due if it happens within `org-deadline-warning-days'
15968 days from today's date. If the deadline appears in an entry marked DONE,
15969 it is not shown. The prefix arg NDAYS can be used to test that many
15970 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15971 (interactive "P")
15972 (let* ((org-warn-days
15973 (cond
15974 ((equal ndays '(4)) 100000)
15975 (ndays (prefix-numeric-value ndays))
15976 (t (abs org-deadline-warning-days))))
15977 (case-fold-search nil)
15978 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15979 (callback
15980 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15982 (message "%d deadlines past-due or due within %d days"
15983 (org-occur regexp nil callback)
15984 org-warn-days)))
15986 (defsubst org-re-timestamp (type)
15987 "Return a regexp for timestamp TYPE.
15988 Allowed values for TYPE are:
15990 all: all timestamps
15991 active: only active timestamps (<...>)
15992 inactive: only inactive timestamps ([...])
15993 scheduled: only scheduled timestamps
15994 deadline: only deadline timestamps
15996 When TYPE is nil, fall back on returning a regexp that matches
15997 both scheduled and deadline timestamps."
15998 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15999 ((eq type 'active) org-ts-regexp)
16000 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16001 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16002 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16003 ((eq type 'scheduled-or-deadline)
16004 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16006 (defun org-check-before-date (date)
16007 "Check if there are deadlines or scheduled entries before DATE."
16008 (interactive (list (org-read-date)))
16009 (let ((case-fold-search nil)
16010 (regexp (org-re-timestamp org-ts-type))
16011 (callback
16012 (lambda () (time-less-p
16013 (org-time-string-to-time (match-string 1))
16014 (org-time-string-to-time date)))))
16015 (message "%d entries before %s"
16016 (org-occur regexp nil callback) date)))
16018 (defun org-check-after-date (date)
16019 "Check if there are deadlines or scheduled entries after DATE."
16020 (interactive (list (org-read-date)))
16021 (let ((case-fold-search nil)
16022 (regexp (org-re-timestamp org-ts-type))
16023 (callback
16024 (lambda () (not
16025 (time-less-p
16026 (org-time-string-to-time (match-string 1))
16027 (org-time-string-to-time date))))))
16028 (message "%d entries after %s"
16029 (org-occur regexp nil callback) date)))
16031 (defun org-check-dates-range (start-date end-date)
16032 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16033 (interactive (list (org-read-date nil nil nil "Range starts")
16034 (org-read-date nil nil nil "Range end")))
16035 (let ((case-fold-search nil)
16036 (regexp (org-re-timestamp org-ts-type))
16037 (callback
16038 (lambda ()
16039 (let ((match (match-string 1)))
16040 (and
16041 (not (time-less-p
16042 (org-time-string-to-time match)
16043 (org-time-string-to-time start-date)))
16044 (time-less-p
16045 (org-time-string-to-time match)
16046 (org-time-string-to-time end-date)))))))
16047 (message "%d entries between %s and %s"
16048 (org-occur regexp nil callback) start-date end-date)))
16050 (defun org-evaluate-time-range (&optional to-buffer)
16051 "Evaluate a time range by computing the difference between start and end.
16052 Normally the result is just printed in the echo area, but with prefix arg
16053 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16054 If the time range is actually in a table, the result is inserted into the
16055 next column.
16056 For time difference computation, a year is assumed to be exactly 365
16057 days in order to avoid rounding problems."
16058 (interactive "P")
16060 (org-clock-update-time-maybe)
16061 (save-excursion
16062 (unless (org-at-date-range-p t)
16063 (goto-char (point-at-bol))
16064 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16065 (if (not (org-at-date-range-p t))
16066 (error "Not at a time-stamp range, and none found in current line")))
16067 (let* ((ts1 (match-string 1))
16068 (ts2 (match-string 2))
16069 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16070 (match-end (match-end 0))
16071 (time1 (org-time-string-to-time ts1))
16072 (time2 (org-time-string-to-time ts2))
16073 (t1 (org-float-time time1))
16074 (t2 (org-float-time time2))
16075 (diff (abs (- t2 t1)))
16076 (negative (< (- t2 t1) 0))
16077 ;; (ys (floor (* 365 24 60 60)))
16078 (ds (* 24 60 60))
16079 (hs (* 60 60))
16080 (fy "%dy %dd %02d:%02d")
16081 (fy1 "%dy %dd")
16082 (fd "%dd %02d:%02d")
16083 (fd1 "%dd")
16084 (fh "%02d:%02d")
16085 y d h m align)
16086 (if havetime
16087 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16089 d (floor (/ diff ds)) diff (mod diff ds)
16090 h (floor (/ diff hs)) diff (mod diff hs)
16091 m (floor (/ diff 60)))
16092 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16094 d (floor (+ (/ diff ds) 0.5))
16095 h 0 m 0))
16096 (if (not to-buffer)
16097 (message "%s" (org-make-tdiff-string y d h m))
16098 (if (org-at-table-p)
16099 (progn
16100 (goto-char match-end)
16101 (setq align t)
16102 (and (looking-at " *|") (goto-char (match-end 0))))
16103 (goto-char match-end))
16104 (if (looking-at
16105 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16106 (replace-match ""))
16107 (if negative (insert " -"))
16108 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16109 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16110 (insert " " (format fh h m))))
16111 (if align (org-table-align))
16112 (message "Time difference inserted")))))
16114 (defun org-make-tdiff-string (y d h m)
16115 (let ((fmt "")
16116 (l nil))
16117 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16118 l (push y l)))
16119 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16120 l (push d l)))
16121 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16122 l (push h l)))
16123 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16124 l (push m l)))
16125 (apply 'format fmt (nreverse l))))
16127 (defun org-time-string-to-time (s &optional buffer pos)
16128 (condition-case errdata
16129 (apply 'encode-time (org-parse-time-string s))
16130 (error (error "Bad timestamp `%s'%s\nError was: %s"
16131 s (if (not (and buffer pos))
16133 (format " at %d in buffer `%s'" pos buffer))
16134 (cdr errdata)))))
16136 (defun org-time-string-to-seconds (s)
16137 (org-float-time (org-time-string-to-time s)))
16139 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16140 "Convert a time stamp to an absolute day number.
16141 If there is a specifier for a cyclic time stamp, get the closest date to
16142 DAYNR.
16143 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16144 The variable date is bound by the calendar when this is called."
16145 (cond
16146 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16147 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16148 daynr
16149 (+ daynr 1000)))
16150 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16151 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16152 (time-to-days (current-time))) (match-string 0 s)
16153 prefer show-all))
16154 (t (time-to-days
16155 (condition-case errdata
16156 (apply 'encode-time (org-parse-time-string s))
16157 (error (error "Bad timestamp `%s'%s\nError was: %s"
16158 s (if (not (and buffer pos))
16160 (format " at %d in buffer `%s'" pos buffer))
16161 (cdr errdata))))))))
16163 (defun org-days-to-iso-week (days)
16164 "Return the iso week number."
16165 (require 'cal-iso)
16166 (car (calendar-iso-from-absolute days)))
16168 (defun org-small-year-to-year (year)
16169 "Convert 2-digit years into 4-digit years.
16170 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16171 The year 2000 cannot be abbreviated. Any year larger than 99
16172 is returned unchanged."
16173 (if (< year 38)
16174 (setq year (+ 2000 year))
16175 (if (< year 100)
16176 (setq year (+ 1900 year))))
16177 year)
16179 (defun org-time-from-absolute (d)
16180 "Return the time corresponding to date D.
16181 D may be an absolute day number, or a calendar-type list (month day year)."
16182 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16183 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16185 (defun org-calendar-holiday ()
16186 "List of holidays, for Diary display in Org-mode."
16187 (require 'holidays)
16188 (let ((hl (funcall
16189 (if (fboundp 'calendar-check-holidays)
16190 'calendar-check-holidays 'check-calendar-holidays) date)))
16191 (if hl (mapconcat 'identity hl "; "))))
16193 (defun org-diary-sexp-entry (sexp entry date)
16194 "Process a SEXP diary ENTRY for DATE."
16195 (require 'diary-lib)
16196 (let ((result (if calendar-debug-sexp
16197 (let ((stack-trace-on-error t))
16198 (eval (car (read-from-string sexp))))
16199 (condition-case nil
16200 (eval (car (read-from-string sexp)))
16201 (error
16202 (beep)
16203 (message "Bad sexp at line %d in %s: %s"
16204 (org-current-line)
16205 (buffer-file-name) sexp)
16206 (sleep-for 2))))))
16207 (cond ((stringp result) (split-string result "; "))
16208 ((and (consp result)
16209 (not (consp (cdr result)))
16210 (stringp (cdr result))) (cdr result))
16211 ((and (consp result)
16212 (stringp (car result))) result)
16213 (result entry)
16214 (t nil))))
16216 (defun org-diary-to-ical-string (frombuf)
16217 "Get iCalendar entries from diary entries in buffer FROMBUF.
16218 This uses the icalendar.el library."
16219 (let* ((tmpdir (if (featurep 'xemacs)
16220 (temp-directory)
16221 temporary-file-directory))
16222 (tmpfile (make-temp-name
16223 (expand-file-name "orgics" tmpdir)))
16224 buf rtn b e)
16225 (with-current-buffer frombuf
16226 (icalendar-export-region (point-min) (point-max) tmpfile)
16227 (setq buf (find-buffer-visiting tmpfile))
16228 (set-buffer buf)
16229 (goto-char (point-min))
16230 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16231 (setq b (match-beginning 0)))
16232 (goto-char (point-max))
16233 (if (re-search-backward "^END:VEVENT" nil t)
16234 (setq e (match-end 0)))
16235 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16236 (kill-buffer buf)
16237 (delete-file tmpfile)
16238 rtn))
16240 (defun org-closest-date (start current change prefer show-all)
16241 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16242 When PREFER is `past', return a date that is either CURRENT or past.
16243 When PREFER is `future', return a date that is either CURRENT or future.
16244 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16245 ;; Make the proper lists from the dates
16246 (catch 'exit
16247 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16248 dn dw sday cday n1 n2 n0
16249 d m y y1 y2 date1 date2 nmonths nm ny m2)
16251 (setq start (org-date-to-gregorian start)
16252 current (org-date-to-gregorian
16253 (if show-all
16254 current
16255 (time-to-days (current-time))))
16256 sday (calendar-absolute-from-gregorian start)
16257 cday (calendar-absolute-from-gregorian current))
16259 (if (<= cday sday) (throw 'exit sday))
16261 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16262 (setq dn (string-to-number (match-string 1 change))
16263 dw (cdr (assoc (match-string 2 change) a1)))
16264 (error "Invalid change specifier: %s" change))
16265 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16266 (cond
16267 ((eq dw 'day)
16268 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16269 n2 (+ n1 dn)))
16270 ((eq dw 'year)
16271 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16272 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16273 (setq date1 (list m d y1)
16274 n1 (calendar-absolute-from-gregorian date1)
16275 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16276 n2 (calendar-absolute-from-gregorian date2)))
16277 ((eq dw 'month)
16278 ;; approx number of month between the two dates
16279 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16280 ;; How often does dn fit in there?
16281 (setq d (nth 1 start) m (car start) y (nth 2 start)
16282 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16283 m (+ m nm)
16284 ny (floor (/ m 12))
16285 y (+ y ny)
16286 m (- m (* ny 12)))
16287 (while (> m 12) (setq m (- m 12) y (1+ y)))
16288 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16289 (setq m2 (+ m dn) y2 y)
16290 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16291 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16292 (while (<= n2 cday)
16293 (setq n1 n2 m m2 y y2)
16294 (setq m2 (+ m dn) y2 y)
16295 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16296 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16297 ;; Make sure n1 is the earlier date
16298 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16299 (if show-all
16300 (cond
16301 ((eq prefer 'past) (if (= cday n2) n2 n1))
16302 ((eq prefer 'future) (if (= cday n1) n1 n2))
16303 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16304 (cond
16305 ((eq prefer 'past) (if (= cday n2) n2 n1))
16306 ((eq prefer 'future) (if (= cday n1) n1 n2))
16307 (t (if (= cday n1) n1 n2)))))))
16309 (defun org-date-to-gregorian (date)
16310 "Turn any specification of DATE into a Gregorian date for the calendar."
16311 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16312 ((and (listp date) (= (length date) 3)) date)
16313 ((stringp date)
16314 (setq date (org-parse-time-string date))
16315 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16316 ((listp date)
16317 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16319 (defun org-parse-time-string (s &optional nodefault)
16320 "Parse the standard Org-mode time string.
16321 This should be a lot faster than the normal `parse-time-string'.
16322 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16323 hour and minute fields will be nil if not given."
16324 (if (string-match org-ts-regexp0 s)
16325 (list 0
16326 (if (or (match-beginning 8) (not nodefault))
16327 (string-to-number (or (match-string 8 s) "0")))
16328 (if (or (match-beginning 7) (not nodefault))
16329 (string-to-number (or (match-string 7 s) "0")))
16330 (string-to-number (match-string 4 s))
16331 (string-to-number (match-string 3 s))
16332 (string-to-number (match-string 2 s))
16333 nil nil nil)
16334 (error "Not a standard Org-mode time string: %s" s)))
16336 (defun org-timestamp-up (&optional arg)
16337 "Increase the date item at the cursor by one.
16338 If the cursor is on the year, change the year. If it is on the month,
16339 the day or the time, change that.
16340 With prefix ARG, change by that many units."
16341 (interactive "p")
16342 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16344 (defun org-timestamp-down (&optional arg)
16345 "Decrease the date item at the cursor by one.
16346 If the cursor is on the year, change the year. If it is on the month,
16347 the day or the time, change that.
16348 With prefix ARG, change by that many units."
16349 (interactive "p")
16350 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16352 (defun org-timestamp-up-day (&optional arg)
16353 "Increase the date in the time stamp by one day.
16354 With prefix ARG, change that many days."
16355 (interactive "p")
16356 (if (and (not (org-at-timestamp-p t))
16357 (org-at-heading-p))
16358 (org-todo 'up)
16359 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16361 (defun org-timestamp-down-day (&optional arg)
16362 "Decrease the date in the time stamp by one day.
16363 With prefix ARG, change that many days."
16364 (interactive "p")
16365 (if (and (not (org-at-timestamp-p t))
16366 (org-at-heading-p))
16367 (org-todo 'down)
16368 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16370 (defun org-at-timestamp-p (&optional inactive-ok)
16371 "Determine if the cursor is in or at a timestamp."
16372 (interactive)
16373 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16374 (pos (point))
16375 (ans (or (looking-at tsr)
16376 (save-excursion
16377 (skip-chars-backward "^[<\n\r\t")
16378 (if (> (point) (point-min)) (backward-char 1))
16379 (and (looking-at tsr)
16380 (> (- (match-end 0) pos) -1))))))
16381 (and ans
16382 (boundp 'org-ts-what)
16383 (setq org-ts-what
16384 (cond
16385 ((= pos (match-beginning 0)) 'bracket)
16386 ;; Point is considered to be "on the bracket" whether
16387 ;; it's really on it or right after it.
16388 ((= pos (1- (match-end 0))) 'bracket)
16389 ((= pos (match-end 0)) 'after)
16390 ((org-pos-in-match-range pos 2) 'year)
16391 ((org-pos-in-match-range pos 3) 'month)
16392 ((org-pos-in-match-range pos 7) 'hour)
16393 ((org-pos-in-match-range pos 8) 'minute)
16394 ((or (org-pos-in-match-range pos 4)
16395 (org-pos-in-match-range pos 5)) 'day)
16396 ((and (> pos (or (match-end 8) (match-end 5)))
16397 (< pos (match-end 0)))
16398 (- pos (or (match-end 8) (match-end 5))))
16399 (t 'day))))
16400 ans))
16402 (defun org-toggle-timestamp-type ()
16403 "Toggle the type (<active> or [inactive]) of a time stamp."
16404 (interactive)
16405 (when (org-at-timestamp-p t)
16406 (let ((beg (match-beginning 0)) (end (match-end 0))
16407 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16408 (save-excursion
16409 (goto-char beg)
16410 (while (re-search-forward "[][<>]" end t)
16411 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16412 t t)))
16413 (message "Timestamp is now %sactive"
16414 (if (equal (char-after beg) ?<) "" "in")))))
16416 (defvar org-clock-history) ; defined in org-clock.el
16417 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16418 (defun org-timestamp-change (n &optional what updown)
16419 "Change the date in the time stamp at point.
16420 The date will be changed by N times WHAT. WHAT can be `day', `month',
16421 `year', `minute', `second'. If WHAT is not given, the cursor position
16422 in the timestamp determines what will be changed."
16423 (let ((origin (point)) origin-cat
16424 with-hm inactive
16425 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16426 org-ts-what
16427 extra rem
16428 ts time time0 fixnext clrgx)
16429 (if (not (org-at-timestamp-p t))
16430 (error "Not at a timestamp"))
16431 (if (and (not what) (eq org-ts-what 'bracket))
16432 (org-toggle-timestamp-type)
16433 ;; Point isn't on brackets. Remember the part of the time-stamp
16434 ;; the point was in. Indeed, size of time-stamps may change,
16435 ;; but point must be kept in the same category nonetheless.
16436 (setq origin-cat org-ts-what)
16437 (if (and (not what) (not (eq org-ts-what 'day))
16438 org-display-custom-times
16439 (get-text-property (point) 'display)
16440 (not (get-text-property (1- (point)) 'display)))
16441 (setq org-ts-what 'day))
16442 (setq org-ts-what (or what org-ts-what)
16443 inactive (= (char-after (match-beginning 0)) ?\[)
16444 ts (match-string 0))
16445 (replace-match "")
16446 (if (string-match
16447 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16449 (setq extra (match-string 1 ts)))
16450 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16451 (setq with-hm t))
16452 (setq time0 (org-parse-time-string ts))
16453 (when (and updown
16454 (eq org-ts-what 'minute)
16455 (not current-prefix-arg))
16456 ;; This looks like s-up and s-down. Change by one rounding step.
16457 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16458 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16459 (setcar (cdr time0) (+ (nth 1 time0)
16460 (if (> n 0) (- rem) (- dm rem))))))
16461 (setq time
16462 (encode-time (or (car time0) 0)
16463 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16464 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16465 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16466 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16467 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16468 (nthcdr 6 time0)))
16469 (when (and (member org-ts-what '(hour minute))
16470 extra
16471 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16472 (setq extra (org-modify-ts-extra
16473 extra
16474 (if (eq org-ts-what 'hour) 2 5)
16475 n dm)))
16476 (when (integerp org-ts-what)
16477 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16478 (if (eq what 'calendar)
16479 (let ((cal-date (org-get-date-from-calendar)))
16480 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16481 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16482 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16483 (setcar time0 (or (car time0) 0))
16484 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16485 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16486 (setq time (apply 'encode-time time0))))
16487 ;; Insert the new time-stamp, and ensure point stays in the same
16488 ;; category as before (i.e. not after the last position in that
16489 ;; category).
16490 (let ((pos (point)))
16491 ;; Stay before inserted string. `save-excursion' is of no use.
16492 (setq org-last-changed-timestamp
16493 (org-insert-time-stamp time with-hm inactive nil nil extra))
16494 (goto-char pos))
16495 (save-match-data
16496 (looking-at org-ts-regexp3)
16497 (goto-char (cond
16498 ;; `day' category ends before `hour' if any, or at
16499 ;; the end of the day name.
16500 ((eq origin-cat 'day)
16501 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16502 ((eq origin-cat 'hour) (min (match-end 7) origin))
16503 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16504 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16505 ;; `year' and `month' have both fixed size: point
16506 ;; couldn't have moved into another part.
16507 (t origin))))
16508 ;; Update clock if on a CLOCK line.
16509 (org-clock-update-time-maybe)
16510 ;; Maybe adjust the closest clock in `org-clock-history'
16511 (when org-clock-adjust-closest
16512 (if (not (and (org-at-clock-log-p)
16513 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16514 org-clock-history))))))
16515 (message "No clock to adjust")
16516 (cond ((save-excursion ; fix previous clock?
16517 (re-search-backward org-ts-regexp0 nil t)
16518 (org-looking-back (concat org-clock-string " \\[")))
16519 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16520 ((save-excursion ; fix next clock?
16521 (re-search-backward org-ts-regexp0 nil t)
16522 (looking-at (concat org-ts-regexp0 "\\] =>")))
16523 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16524 (save-window-excursion
16525 ;; Find closest clock to point, adjust the previous/next one in history
16526 (let* ((p (save-excursion (org-back-to-heading t)))
16527 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16528 (clfixnth
16529 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16530 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16531 (if (not clfixpos)
16532 (message "No clock to adjust")
16533 (save-excursion
16534 (org-goto-marker-or-bmk clfixpos)
16535 (org-show-subtree)
16536 (when (re-search-forward clrgx nil t)
16537 (goto-char (match-beginning 1))
16538 (let (org-clock-adjust-closest)
16539 (org-timestamp-change n org-ts-what updown))
16540 (message "Clock adjusted in %s for heading: %s"
16541 (file-name-nondirectory (buffer-file-name))
16542 (org-get-heading t t)))))))))
16543 ;; Try to recenter the calendar window, if any.
16544 (if (and org-calendar-follow-timestamp-change
16545 (get-buffer-window "*Calendar*" t)
16546 (memq org-ts-what '(day month year)))
16547 (org-recenter-calendar (time-to-days time))))))
16549 (defun org-modify-ts-extra (s pos n dm)
16550 "Change the different parts of the lead-time and repeat fields in timestamp."
16551 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16552 ng h m new rem)
16553 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16554 (cond
16555 ((or (org-pos-in-match-range pos 2)
16556 (org-pos-in-match-range pos 3))
16557 (setq m (string-to-number (match-string 3 s))
16558 h (string-to-number (match-string 2 s)))
16559 (if (org-pos-in-match-range pos 2)
16560 (setq h (+ h n))
16561 (setq n (* dm (org-no-warnings (signum n))))
16562 (when (not (= 0 (setq rem (% m dm))))
16563 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16564 (setq m (+ m n)))
16565 (if (< m 0) (setq m (+ m 60) h (1- h)))
16566 (if (> m 59) (setq m (- m 60) h (1+ h)))
16567 (setq h (min 24 (max 0 h)))
16568 (setq ng 1 new (format "-%02d:%02d" h m)))
16569 ((org-pos-in-match-range pos 6)
16570 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16571 ((org-pos-in-match-range pos 5)
16572 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16574 ((org-pos-in-match-range pos 9)
16575 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16576 ((org-pos-in-match-range pos 8)
16577 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16579 (when ng
16580 (setq s (concat
16581 (substring s 0 (match-beginning ng))
16583 (substring s (match-end ng))))))
16586 (defun org-recenter-calendar (date)
16587 "If the calendar is visible, recenter it to DATE."
16588 (let ((cwin (get-buffer-window "*Calendar*" t)))
16589 (when cwin
16590 (let ((calendar-move-hook nil))
16591 (with-selected-window cwin
16592 (calendar-goto-date (if (listp date) date
16593 (calendar-gregorian-from-absolute date))))))))
16595 (defun org-goto-calendar (&optional arg)
16596 "Go to the Emacs calendar at the current date.
16597 If there is a time stamp in the current line, go to that date.
16598 A prefix ARG can be used to force the current date."
16599 (interactive "P")
16600 (let ((tsr org-ts-regexp) diff
16601 (calendar-move-hook nil)
16602 (calendar-view-holidays-initially-flag nil)
16603 (calendar-view-diary-initially-flag nil))
16604 (if (or (org-at-timestamp-p)
16605 (save-excursion
16606 (beginning-of-line 1)
16607 (looking-at (concat ".*" tsr))))
16608 (let ((d1 (time-to-days (current-time)))
16609 (d2 (time-to-days
16610 (org-time-string-to-time (match-string 1)))))
16611 (setq diff (- d2 d1))))
16612 (calendar)
16613 (calendar-goto-today)
16614 (if (and diff (not arg)) (calendar-forward-day diff))))
16616 (defun org-get-date-from-calendar ()
16617 "Return a list (month day year) of date at point in calendar."
16618 (with-current-buffer "*Calendar*"
16619 (save-match-data
16620 (calendar-cursor-to-date))))
16622 (defun org-date-from-calendar ()
16623 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16624 If there is already a time stamp at the cursor position, update it."
16625 (interactive)
16626 (if (org-at-timestamp-p t)
16627 (org-timestamp-change 0 'calendar)
16628 (let ((cal-date (org-get-date-from-calendar)))
16629 (org-insert-time-stamp
16630 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16632 (defun org-minutes-to-hh:mm-string (m)
16633 "Compute H:MM from a number of minutes."
16634 (let ((h (/ m 60)))
16635 (setq m (- m (* 60 h)))
16636 (format org-time-clocksum-format h m)))
16638 (defun org-hh:mm-string-to-minutes (s)
16639 "Convert a string H:MM to a number of minutes.
16640 If the string is just a number, interpret it as minutes.
16641 In fact, the first hh:mm or number in the string will be taken,
16642 there can be extra stuff in the string.
16643 If no number is found, the return value is 0."
16644 (cond
16645 ((integerp s) s)
16646 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16647 (+ (* (string-to-number (match-string 1 s)) 60)
16648 (string-to-number (match-string 2 s))))
16649 ((string-match "\\([0-9]+\\)" s)
16650 (string-to-number (match-string 1 s)))
16651 (t 0)))
16653 (defcustom org-effort-durations
16654 `(("h" . 60)
16655 ("d" . ,(* 60 8))
16656 ("w" . ,(* 60 8 5))
16657 ("m" . ,(* 60 8 5 4))
16658 ("y" . ,(* 60 8 5 40)))
16659 "Conversion factor to minutes for an effort modifier.
16661 Each entry has the form (MODIFIER . MINUTES).
16663 In an effort string, a number followed by MODIFIER is multiplied
16664 by the specified number of MINUTES to obtain an effort in
16665 minutes.
16667 For example, if the value of this variable is ((\"hours\" . 60)), then an
16668 effort string \"2hours\" is equivalent to 120 minutes."
16669 :group 'org-agenda
16670 :version "24.1"
16671 :type '(alist :key-type (string :tag "Modifier")
16672 :value-type (number :tag "Minutes")))
16674 (defun org-duration-string-to-minutes (s &optional output-to-string)
16675 "Convert a duration string S to minutes.
16677 A bare number is interpreted as minutes, modifiers can be set by
16678 customizing `org-effort-durations' (which see).
16680 Entries containing a colon are interpreted as H:MM by
16681 `org-hh:mm-string-to-minutes'."
16682 (let ((result 0)
16683 (re (concat "\\([0-9.]+\\) *\\("
16684 (regexp-opt (mapcar 'car org-effort-durations))
16685 "\\)")))
16686 (while (string-match re s)
16687 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16688 (string-to-number (match-string 1 s))))
16689 (setq s (replace-match "" nil t s)))
16690 (setq result (floor result))
16691 (incf result (org-hh:mm-string-to-minutes s))
16692 (if output-to-string (number-to-string result) result)))
16694 ;;;; Files
16696 (defun org-save-all-org-buffers ()
16697 "Save all Org-mode buffers without user confirmation."
16698 (interactive)
16699 (message "Saving all Org-mode buffers...")
16700 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16701 (when (featurep 'org-id) (org-id-locations-save))
16702 (message "Saving all Org-mode buffers... done"))
16704 (defun org-revert-all-org-buffers ()
16705 "Revert all Org-mode buffers.
16706 Prompt for confirmation when there are unsaved changes.
16707 Be sure you know what you are doing before letting this function
16708 overwrite your changes.
16710 This function is useful in a setup where one tracks org files
16711 with a version control system, to revert on one machine after pulling
16712 changes from another. I believe the procedure must be like this:
16714 1. M-x org-save-all-org-buffers
16715 2. Pull changes from the other machine, resolve conflicts
16716 3. M-x org-revert-all-org-buffers"
16717 (interactive)
16718 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16719 (error "Abort"))
16720 (save-excursion
16721 (save-window-excursion
16722 (mapc
16723 (lambda (b)
16724 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16725 (with-current-buffer b buffer-file-name))
16726 (org-pop-to-buffer-same-window b)
16727 (revert-buffer t 'no-confirm)))
16728 (buffer-list))
16729 (when (and (featurep 'org-id) org-id-track-globally)
16730 (org-id-locations-load)))))
16732 ;;;; Agenda files
16734 ;;;###autoload
16735 (defun org-switchb (&optional arg)
16736 "Switch between Org buffers.
16737 With one prefix argument, restrict available buffers to files.
16738 With two prefix arguments, restrict available buffers to agenda files.
16740 Defaults to `iswitchb' for buffer name completion.
16741 Set `org-completion-use-ido' to make it use ido instead."
16742 (interactive "P")
16743 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16744 ((equal arg '(16)) (org-buffer-list 'agenda))
16745 (t (org-buffer-list))))
16746 (org-completion-use-iswitchb org-completion-use-iswitchb)
16747 (org-completion-use-ido org-completion-use-ido))
16748 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16749 (setq org-completion-use-iswitchb t))
16750 (org-pop-to-buffer-same-window
16751 (org-icompleting-read "Org buffer: "
16752 (mapcar 'list (mapcar 'buffer-name blist))
16753 nil t))))
16755 ;;; Define some older names previously used for this functionality
16756 ;;;###autoload
16757 (defalias 'org-ido-switchb 'org-switchb)
16758 ;;;###autoload
16759 (defalias 'org-iswitchb 'org-switchb)
16761 (defun org-buffer-list (&optional predicate exclude-tmp)
16762 "Return a list of Org buffers.
16763 PREDICATE can be `export', `files' or `agenda'.
16765 export restrict the list to Export buffers.
16766 files restrict the list to buffers visiting Org files.
16767 agenda restrict the list to buffers visiting agenda files.
16769 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16770 (let* ((bfn nil)
16771 (agenda-files (and (eq predicate 'agenda)
16772 (mapcar 'file-truename (org-agenda-files t))))
16773 (filter
16774 (cond
16775 ((eq predicate 'files)
16776 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16777 ((eq predicate 'export)
16778 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16779 ((eq predicate 'agenda)
16780 (lambda (b)
16781 (with-current-buffer b
16782 (and (derived-mode-p 'org-mode)
16783 (setq bfn (buffer-file-name b))
16784 (member (file-truename bfn) agenda-files)))))
16785 (t (lambda (b) (with-current-buffer b
16786 (or (derived-mode-p 'org-mode)
16787 (string-match "\*Org .*Export"
16788 (buffer-name b)))))))))
16789 (delq nil
16790 (mapcar
16791 (lambda(b)
16792 (if (and (funcall filter b)
16793 (or (not exclude-tmp)
16794 (not (string-match "tmp" (buffer-name b)))))
16796 nil))
16797 (buffer-list)))))
16799 (defun org-agenda-files (&optional unrestricted archives)
16800 "Get the list of agenda files.
16801 Optional UNRESTRICTED means return the full list even if a restriction
16802 is currently in place.
16803 When ARCHIVES is t, include all archive files that are really being
16804 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16805 `org-agenda-archives-mode' is t."
16806 (let ((files
16807 (cond
16808 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16809 ((stringp org-agenda-files) (org-read-agenda-file-list))
16810 ((listp org-agenda-files) org-agenda-files)
16811 (t (error "Invalid value of `org-agenda-files'")))))
16812 (setq files (apply 'append
16813 (mapcar (lambda (f)
16814 (if (file-directory-p f)
16815 (directory-files
16816 f t org-agenda-file-regexp)
16817 (list f)))
16818 files)))
16819 (when org-agenda-skip-unavailable-files
16820 (setq files (delq nil
16821 (mapcar (function
16822 (lambda (file)
16823 (and (file-readable-p file) file)))
16824 files))))
16825 (when (or (eq archives t)
16826 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16827 (setq files (org-add-archive-files files)))
16828 files))
16830 (defun org-agenda-file-p (&optional file)
16831 "Return non-nil, if FILE is an agenda file.
16832 If FILE is omitted, use the file associated with the current
16833 buffer."
16834 (member (or file (buffer-file-name))
16835 (org-agenda-files t)))
16837 (defun org-edit-agenda-file-list ()
16838 "Edit the list of agenda files.
16839 Depending on setup, this either uses customize to edit the variable
16840 `org-agenda-files', or it visits the file that is holding the list. In the
16841 latter case, the buffer is set up in a way that saving it automatically kills
16842 the buffer and restores the previous window configuration."
16843 (interactive)
16844 (if (stringp org-agenda-files)
16845 (let ((cw (current-window-configuration)))
16846 (find-file org-agenda-files)
16847 (org-set-local 'org-window-configuration cw)
16848 (org-add-hook 'after-save-hook
16849 (lambda ()
16850 (set-window-configuration
16851 (prog1 org-window-configuration
16852 (kill-buffer (current-buffer))))
16853 (org-install-agenda-files-menu)
16854 (message "New agenda file list installed"))
16855 nil 'local)
16856 (message "%s" (substitute-command-keys
16857 "Edit list and finish with \\[save-buffer]")))
16858 (customize-variable 'org-agenda-files)))
16860 (defun org-store-new-agenda-file-list (list)
16861 "Set new value for the agenda file list and save it correctly."
16862 (if (stringp org-agenda-files)
16863 (let ((fe (org-read-agenda-file-list t)) b u)
16864 (while (setq b (find-buffer-visiting org-agenda-files))
16865 (kill-buffer b))
16866 (with-temp-file org-agenda-files
16867 (insert
16868 (mapconcat
16869 (lambda (f) ;; Keep un-expanded entries.
16870 (if (setq u (assoc f fe))
16871 (cdr u)
16873 list "\n")
16874 "\n")))
16875 (let ((org-mode-hook nil) (org-inhibit-startup t)
16876 (org-insert-mode-line-in-empty-file nil))
16877 (setq org-agenda-files list)
16878 (customize-save-variable 'org-agenda-files org-agenda-files))))
16880 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16881 "Read the list of agenda files from a file.
16882 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16883 filenames, used by `org-store-new-agenda-file-list' to write back
16884 un-expanded file names."
16885 (when (file-directory-p org-agenda-files)
16886 (error "`org-agenda-files' cannot be a single directory"))
16887 (when (stringp org-agenda-files)
16888 (with-temp-buffer
16889 (insert-file-contents org-agenda-files)
16890 (mapcar
16891 (lambda (f)
16892 (let ((e (expand-file-name (substitute-in-file-name f)
16893 org-directory)))
16894 (if pair-with-expansion
16895 (cons e f)
16896 e)))
16897 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16899 ;;;###autoload
16900 (defun org-cycle-agenda-files ()
16901 "Cycle through the files in `org-agenda-files'.
16902 If the current buffer visits an agenda file, find the next one in the list.
16903 If the current buffer does not, find the first agenda file."
16904 (interactive)
16905 (let* ((fs (org-agenda-files t))
16906 (files (append fs (list (car fs))))
16907 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16908 file)
16909 (unless files (error "No agenda files"))
16910 (catch 'exit
16911 (while (setq file (pop files))
16912 (if (equal (file-truename file) tcf)
16913 (when (car files)
16914 (find-file (car files))
16915 (throw 'exit t))))
16916 (find-file (car fs)))
16917 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16919 (defun org-agenda-file-to-front (&optional to-end)
16920 "Move/add the current file to the top of the agenda file list.
16921 If the file is not present in the list, it is added to the front. If it is
16922 present, it is moved there. With optional argument TO-END, add/move to the
16923 end of the list."
16924 (interactive "P")
16925 (let ((org-agenda-skip-unavailable-files nil)
16926 (file-alist (mapcar (lambda (x)
16927 (cons (file-truename x) x))
16928 (org-agenda-files t)))
16929 (ctf (file-truename buffer-file-name))
16930 x had)
16931 (setq x (assoc ctf file-alist) had x)
16933 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16934 (if to-end
16935 (setq file-alist (append (delq x file-alist) (list x)))
16936 (setq file-alist (cons x (delq x file-alist))))
16937 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16938 (org-install-agenda-files-menu)
16939 (message "File %s to %s of agenda file list"
16940 (if had "moved" "added") (if to-end "end" "front"))))
16942 (defun org-remove-file (&optional file)
16943 "Remove current file from the list of files in variable `org-agenda-files'.
16944 These are the files which are being checked for agenda entries.
16945 Optional argument FILE means use this file instead of the current."
16946 (interactive)
16947 (let* ((org-agenda-skip-unavailable-files nil)
16948 (file (or file buffer-file-name))
16949 (true-file (file-truename file))
16950 (afile (abbreviate-file-name file))
16951 (files (delq nil (mapcar
16952 (lambda (x)
16953 (if (equal true-file
16954 (file-truename x))
16955 nil x))
16956 (org-agenda-files t)))))
16957 (if (not (= (length files) (length (org-agenda-files t))))
16958 (progn
16959 (org-store-new-agenda-file-list files)
16960 (org-install-agenda-files-menu)
16961 (message "Removed file: %s" afile))
16962 (message "File was not in list: %s (not removed)" afile))))
16964 (defun org-file-menu-entry (file)
16965 (vector file (list 'find-file file) t))
16967 (defun org-check-agenda-file (file)
16968 "Make sure FILE exists. If not, ask user what to do."
16969 (when (not (file-exists-p file))
16970 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16971 (abbreviate-file-name file))
16972 (let ((r (downcase (read-char-exclusive))))
16973 (cond
16974 ((equal r ?r)
16975 (org-remove-file file)
16976 (throw 'nextfile t))
16977 (t (error "Abort"))))))
16979 (defun org-get-agenda-file-buffer (file)
16980 "Get a buffer visiting FILE. If the buffer needs to be created, add
16981 it to the list of buffers which might be released later."
16982 (let ((buf (org-find-base-buffer-visiting file)))
16983 (if buf
16984 buf ; just return it
16985 ;; Make a new buffer and remember it
16986 (setq buf (find-file-noselect file))
16987 (if buf (push buf org-agenda-new-buffers))
16988 buf)))
16990 (defun org-release-buffers (blist)
16991 "Release all buffers in list, asking the user for confirmation when needed.
16992 When a buffer is unmodified, it is just killed. When modified, it is saved
16993 \(if the user agrees) and then killed."
16994 (let (buf file)
16995 (while (setq buf (pop blist))
16996 (setq file (buffer-file-name buf))
16997 (when (and (buffer-modified-p buf)
16998 file
16999 (y-or-n-p (format "Save file %s? " file)))
17000 (with-current-buffer buf (save-buffer)))
17001 (kill-buffer buf))))
17003 (defun org-prepare-agenda-buffers (files)
17004 "Create buffers for all agenda files, protect archived trees and comments."
17005 (interactive)
17006 (let ((pa '(:org-archived t))
17007 (pc '(:org-comment t))
17008 (pall '(:org-archived t :org-comment t))
17009 (inhibit-read-only t)
17010 (rea (concat ":" org-archive-tag ":"))
17011 bmp file re)
17012 (save-excursion
17013 (save-restriction
17014 (while (setq file (pop files))
17015 (catch 'nextfile
17016 (if (bufferp file)
17017 (set-buffer file)
17018 (org-check-agenda-file file)
17019 (set-buffer (org-get-agenda-file-buffer file)))
17020 (widen)
17021 (setq bmp (buffer-modified-p))
17022 (org-refresh-category-properties)
17023 (setq org-todo-keywords-for-agenda
17024 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17025 (setq org-done-keywords-for-agenda
17026 (append org-done-keywords-for-agenda org-done-keywords))
17027 (setq org-todo-keyword-alist-for-agenda
17028 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17029 (setq org-drawers-for-agenda
17030 (append org-drawers-for-agenda org-drawers))
17031 (setq org-tag-alist-for-agenda
17032 (append org-tag-alist-for-agenda org-tag-alist))
17034 (save-excursion
17035 (remove-text-properties (point-min) (point-max) pall)
17036 (when org-agenda-skip-archived-trees
17037 (goto-char (point-min))
17038 (while (re-search-forward rea nil t)
17039 (if (org-at-heading-p t)
17040 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17041 (goto-char (point-min))
17042 (setq re (format org-heading-keyword-regexp-format
17043 org-comment-string))
17044 (while (re-search-forward re nil t)
17045 (add-text-properties
17046 (match-beginning 0) (org-end-of-subtree t) pc)))
17047 (set-buffer-modified-p bmp)))))
17048 (setq org-todo-keywords-for-agenda
17049 (org-uniquify org-todo-keywords-for-agenda))
17050 (setq org-todo-keyword-alist-for-agenda
17051 (org-uniquify org-todo-keyword-alist-for-agenda)
17052 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17054 ;;;; Embedded LaTeX
17056 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17057 "Keymap for the minor `org-cdlatex-mode'.")
17059 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17060 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17061 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17062 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17063 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17065 (defvar org-cdlatex-texmathp-advice-is-done nil
17066 "Flag remembering if we have applied the advice to texmathp already.")
17068 (define-minor-mode org-cdlatex-mode
17069 "Toggle the minor `org-cdlatex-mode'.
17070 This mode supports entering LaTeX environment and math in LaTeX fragments
17071 in Org-mode.
17072 \\{org-cdlatex-mode-map}"
17073 nil " OCDL" nil
17074 (when org-cdlatex-mode
17075 (require 'cdlatex)
17076 (run-hooks 'cdlatex-mode-hook)
17077 (cdlatex-compute-tables))
17078 (unless org-cdlatex-texmathp-advice-is-done
17079 (setq org-cdlatex-texmathp-advice-is-done t)
17080 (defadvice texmathp (around org-math-always-on activate)
17081 "Always return t in org-mode buffers.
17082 This is because we want to insert math symbols without dollars even outside
17083 the LaTeX math segments. If Orgmode thinks that point is actually inside
17084 an embedded LaTeX fragment, let texmathp do its job.
17085 \\[org-cdlatex-mode-map]"
17086 (interactive)
17087 (let (p)
17088 (cond
17089 ((not (derived-mode-p 'org-mode)) ad-do-it)
17090 ((eq this-command 'cdlatex-math-symbol)
17091 (setq ad-return-value t
17092 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17094 (let ((p (org-inside-LaTeX-fragment-p)))
17095 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17096 (setq ad-return-value t
17097 texmathp-why '("Org-mode embedded math" . 0))
17098 (if p ad-do-it)))))))))
17100 (defun turn-on-org-cdlatex ()
17101 "Unconditionally turn on `org-cdlatex-mode'."
17102 (org-cdlatex-mode 1))
17104 (defun org-inside-LaTeX-fragment-p ()
17105 "Test if point is inside a LaTeX fragment.
17106 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17107 sequence appearing also before point.
17108 Even though the matchers for math are configurable, this function assumes
17109 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17110 delimiters are skipped when they have been removed by customization.
17111 The return value is nil, or a cons cell with the delimiter and the
17112 position of this delimiter.
17114 This function does a reasonably good job, but can locally be fooled by
17115 for example currency specifications. For example it will assume being in
17116 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17117 fragments that are properly closed, but during editing, we have to live
17118 with the uncertainty caused by missing closing delimiters. This function
17119 looks only before point, not after."
17120 (catch 'exit
17121 (let ((pos (point))
17122 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17123 (lim (progn
17124 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17125 (point)))
17126 dd-on str (start 0) m re)
17127 (goto-char pos)
17128 (when dodollar
17129 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17130 re (nth 1 (assoc "$" org-latex-regexps)))
17131 (while (string-match re str start)
17132 (cond
17133 ((= (match-end 0) (length str))
17134 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17135 ((= (match-end 0) (- (length str) 5))
17136 (throw 'exit nil))
17137 (t (setq start (match-end 0))))))
17138 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17139 (goto-char pos)
17140 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17141 (and (match-beginning 2) (throw 'exit nil))
17142 ;; count $$
17143 (while (re-search-backward "\\$\\$" lim t)
17144 (setq dd-on (not dd-on)))
17145 (goto-char pos)
17146 (if dd-on (cons "$$" m))))))
17148 (defun org-inside-latex-macro-p ()
17149 "Is point inside a LaTeX macro or its arguments?"
17150 (save-match-data
17151 (org-in-regexp
17152 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17154 (defun org-try-cdlatex-tab ()
17155 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17156 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17157 - inside a LaTeX fragment, or
17158 - after the first word in a line, where an abbreviation expansion could
17159 insert a LaTeX environment."
17160 (when org-cdlatex-mode
17161 (cond
17162 ;; Before any word on the line: No expansion possible.
17163 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17164 ;; Just after first word on the line: Expand it. Make sure it
17165 ;; cannot happen on headlines, though.
17166 ((save-excursion
17167 (skip-chars-backward "a-zA-Z0-9*")
17168 (skip-chars-backward " \t")
17169 (and (bolp) (not (org-at-heading-p))))
17170 (cdlatex-tab) t)
17171 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17173 (defun org-cdlatex-underscore-caret (&optional arg)
17174 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17175 Revert to the normal definition outside of these fragments."
17176 (interactive "P")
17177 (if (org-inside-LaTeX-fragment-p)
17178 (call-interactively 'cdlatex-sub-superscript)
17179 (let (org-cdlatex-mode)
17180 (call-interactively (key-binding (vector last-input-event))))))
17182 (defun org-cdlatex-math-modify (&optional arg)
17183 "Execute `cdlatex-math-modify' in LaTeX fragments.
17184 Revert to the normal definition outside of these fragments."
17185 (interactive "P")
17186 (if (org-inside-LaTeX-fragment-p)
17187 (call-interactively 'cdlatex-math-modify)
17188 (let (org-cdlatex-mode)
17189 (call-interactively (key-binding (vector last-input-event))))))
17191 (defvar org-latex-fragment-image-overlays nil
17192 "List of overlays carrying the images of latex fragments.")
17193 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17195 (defun org-remove-latex-fragment-image-overlays ()
17196 "Remove all overlays with LaTeX fragment images in current buffer."
17197 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17198 (setq org-latex-fragment-image-overlays nil))
17200 (defun org-preview-latex-fragment (&optional subtree)
17201 "Preview the LaTeX fragment at point, or all locally or globally.
17202 If the cursor is in a LaTeX fragment, create the image and overlay
17203 it over the source code. If there is no fragment at point, display
17204 all fragments in the current text, from one headline to the next. With
17205 prefix SUBTREE, display all fragments in the current subtree. With a
17206 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17207 the cursor is before the first headline,
17208 display all fragments in the buffer.
17209 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17210 (interactive "P")
17211 (unless buffer-file-name
17212 (error "Can't preview LaTeX fragment in a non-file buffer"))
17213 (org-remove-latex-fragment-image-overlays)
17214 (save-excursion
17215 (save-restriction
17216 (let (beg end at msg)
17217 (cond
17218 ((or (equal subtree '(16))
17219 (not (save-excursion
17220 (re-search-backward org-outline-regexp-bol nil t))))
17221 (setq beg (point-min) end (point-max)
17222 msg "Creating images for buffer...%s"))
17223 ((equal subtree '(4))
17224 (org-back-to-heading)
17225 (setq beg (point) end (org-end-of-subtree t)
17226 msg "Creating images for subtree...%s"))
17228 (if (setq at (org-inside-LaTeX-fragment-p))
17229 (goto-char (max (point-min) (- (cdr at) 2)))
17230 (org-back-to-heading))
17231 (setq beg (point) end (progn (outline-next-heading) (point))
17232 msg (if at "Creating image...%s"
17233 "Creating images for entry...%s"))))
17234 (message msg "")
17235 (narrow-to-region beg end)
17236 (goto-char beg)
17237 (org-format-latex
17238 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17239 (file-name-nondirectory
17240 buffer-file-name)))
17241 default-directory 'overlays msg at 'forbuffer
17242 org-latex-create-formula-image-program)
17243 (message msg "done. Use `C-c C-c' to remove images.")))))
17245 (defvar org-latex-regexps
17246 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17247 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17248 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17249 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17250 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17251 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17252 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17253 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17254 "Regular expressions for matching embedded LaTeX.")
17256 (defvar org-export-have-math nil) ;; dynamic scoping
17257 (defun org-format-latex (prefix &optional dir overlays msg at
17258 forbuffer processing-type)
17259 "Replace LaTeX fragments with links to an image, and produce images.
17260 Some of the options can be changed using the variable
17261 `org-format-latex-options'."
17262 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17263 (let* ((prefixnodir (file-name-nondirectory prefix))
17264 (absprefix (expand-file-name prefix dir))
17265 (todir (file-name-directory absprefix))
17266 (opt org-format-latex-options)
17267 (matchers (plist-get opt :matchers))
17268 (re-list org-latex-regexps)
17269 (org-format-latex-header-extra
17270 (plist-get (org-infile-export-plist) :latex-header-extra))
17271 (cnt 0) txt hash link beg end re e checkdir
17272 executables-checked string
17273 m n block-type block linkfile movefile ov)
17274 ;; Check the different regular expressions
17275 (while (setq e (pop re-list))
17276 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17277 block (if block-type "\n\n" ""))
17278 (when (member m matchers)
17279 (goto-char (point-min))
17280 (while (re-search-forward re nil t)
17281 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17282 (not (get-text-property (match-beginning n)
17283 'org-protected))
17284 (or (not overlays)
17285 (not (eq (get-char-property (match-beginning n)
17286 'org-overlay-type)
17287 'org-latex-overlay))))
17288 (setq org-export-have-math t)
17289 (cond
17290 ((eq processing-type 'verbatim)
17291 ;; Leave the text verbatim, just protect it
17292 (add-text-properties (match-beginning n) (match-end n)
17293 '(org-protected t)))
17294 ((eq processing-type 'mathjax)
17295 ;; Prepare for MathJax processing
17296 (setq string (match-string n))
17297 (if (member m '("$" "$1"))
17298 (save-excursion
17299 (delete-region (match-beginning n) (match-end n))
17300 (goto-char (match-beginning n))
17301 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17302 "\\)")
17303 '(org-protected t))))
17304 (add-text-properties (match-beginning n) (match-end n)
17305 '(org-protected t))))
17306 ((or (eq processing-type 'dvipng)
17307 (eq processing-type 'imagemagick))
17308 ;; Process to an image
17309 (setq txt (match-string n)
17310 beg (match-beginning n) end (match-end n)
17311 cnt (1+ cnt))
17312 (let (print-length print-level) ; make sure full list is printed
17313 (setq hash (sha1 (prin1-to-string
17314 (list org-format-latex-header
17315 org-format-latex-header-extra
17316 org-export-latex-default-packages-alist
17317 org-export-latex-packages-alist
17318 org-format-latex-options
17319 forbuffer txt)))
17320 linkfile (format "%s_%s.png" prefix hash)
17321 movefile (format "%s_%s.png" absprefix hash)))
17322 (setq link (concat block "[[file:" linkfile "]]" block))
17323 (if msg (message msg cnt))
17324 (goto-char beg)
17325 (unless checkdir ; make sure the directory exists
17326 (setq checkdir t)
17327 (or (file-directory-p todir) (make-directory todir t)))
17328 (cond
17329 ((eq processing-type 'dvipng)
17330 (unless executables-checked
17331 (org-check-external-command
17332 "latex" "needed to convert LaTeX fragments to images")
17333 (org-check-external-command
17334 "dvipng" "needed to convert LaTeX fragments to images")
17335 (setq executables-checked t))
17336 (unless (file-exists-p movefile)
17337 (org-create-formula-image-with-dvipng
17338 txt movefile opt forbuffer)))
17339 ((eq processing-type 'imagemagick)
17340 (unless executables-checked
17341 (org-check-external-command
17342 "convert" "you need to install imagemagick")
17343 (setq executables-checked t))
17344 (unless (file-exists-p movefile)
17345 (org-create-formula-image-with-imagemagick
17346 txt movefile opt forbuffer))))
17347 (if overlays
17348 (progn
17349 (mapc (lambda (o)
17350 (if (eq (overlay-get o 'org-overlay-type)
17351 'org-latex-overlay)
17352 (delete-overlay o)))
17353 (overlays-in beg end))
17354 (setq ov (make-overlay beg end))
17355 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17356 (if (featurep 'xemacs)
17357 (progn
17358 (overlay-put ov 'invisible t)
17359 (overlay-put
17360 ov 'end-glyph
17361 (make-glyph (vector 'png :file movefile))))
17362 (overlay-put
17363 ov 'display
17364 (list 'image :type 'png :file movefile :ascent 'center)))
17365 (push ov org-latex-fragment-image-overlays)
17366 (goto-char end))
17367 (delete-region beg end)
17368 (insert (org-add-props link
17369 (list 'org-latex-src
17370 (replace-regexp-in-string
17371 "\"" "" txt)
17372 'org-latex-src-embed-type
17373 (if block-type 'paragraph 'character))))))
17374 ((eq processing-type 'mathml)
17375 ;; Process to MathML
17376 (unless executables-checked
17377 (unless (save-match-data (org-format-latex-mathml-available-p))
17378 (error "LaTeX to MathML converter not configured"))
17379 (setq executables-checked t))
17380 (setq txt (match-string n)
17381 beg (match-beginning n) end (match-end n)
17382 cnt (1+ cnt))
17383 (if msg (message msg cnt))
17384 (goto-char beg)
17385 (delete-region beg end)
17386 (insert (org-format-latex-as-mathml
17387 txt block-type prefix dir)))
17389 (error "Unknown conversion type %s for latex fragments"
17390 processing-type)))))))))
17392 (defun org-create-math-formula (latex-frag &optional mathml-file)
17393 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17394 Use `org-latex-to-mathml-convert-command'. If the conversion is
17395 sucessful, return the portion between \"<math...> </math>\"
17396 elements otherwise return nil. When MATHML-FILE is specified,
17397 write the results in to that file. When invoked as an
17398 interactive command, prompt for LATEX-FRAG, with initial value
17399 set to the current active region and echo the results for user
17400 inspection."
17401 (interactive (list (let ((frag (when (region-active-p)
17402 (buffer-substring-no-properties
17403 (region-beginning) (region-end)))))
17404 (read-string "LaTeX Fragment: " frag nil frag))))
17405 (unless latex-frag (error "Invalid latex-frag"))
17406 (let* ((tmp-in-file (file-relative-name
17407 (make-temp-name (expand-file-name "ltxmathml-in"))))
17408 (ignore (write-region latex-frag nil tmp-in-file))
17409 (tmp-out-file (file-relative-name
17410 (make-temp-name (expand-file-name "ltxmathml-out"))))
17411 (cmd (format-spec
17412 org-latex-to-mathml-convert-command
17413 `((?j . ,(shell-quote-argument
17414 (expand-file-name org-latex-to-mathml-jar-file)))
17415 (?I . ,(shell-quote-argument tmp-in-file))
17416 (?o . ,(shell-quote-argument tmp-out-file)))))
17417 mathml shell-command-output)
17418 (when (org-called-interactively-p 'any)
17419 (unless (org-format-latex-mathml-available-p)
17420 (error "LaTeX to MathML converter not configured")))
17421 (message "Running %s" cmd)
17422 (setq shell-command-output (shell-command-to-string cmd))
17423 (setq mathml
17424 (when (file-readable-p tmp-out-file)
17425 (with-current-buffer (find-file-noselect tmp-out-file t)
17426 (goto-char (point-min))
17427 (when (re-search-forward
17428 (concat
17429 (regexp-quote
17430 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17431 "\\(.\\|\n\\)*"
17432 (regexp-quote "</math>")) nil t)
17433 (prog1 (match-string 0) (kill-buffer))))))
17434 (cond
17435 (mathml
17436 (setq mathml
17437 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17438 (when mathml-file
17439 (write-region mathml nil mathml-file))
17440 (when (org-called-interactively-p 'any)
17441 (message mathml)))
17442 ((message "LaTeX to MathML conversion failed")
17443 (message shell-command-output)))
17444 (delete-file tmp-in-file)
17445 (when (file-exists-p tmp-out-file)
17446 (delete-file tmp-out-file))
17447 mathml))
17449 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17450 prefix &optional dir)
17451 "Use `org-create-math-formula' but check local cache first."
17452 (let* ((absprefix (expand-file-name prefix dir))
17453 (print-length nil) (print-level nil)
17454 (formula-id (concat
17455 "formula-"
17456 (sha1
17457 (prin1-to-string
17458 (list latex-frag
17459 org-latex-to-mathml-convert-command)))))
17460 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17461 (formula-cache-dir (file-name-directory formula-cache)))
17463 (unless (file-directory-p formula-cache-dir)
17464 (make-directory formula-cache-dir t))
17466 (unless (file-exists-p formula-cache)
17467 (org-create-math-formula latex-frag formula-cache))
17469 (if (file-exists-p formula-cache)
17470 ;; Successful conversion. Return the link to MathML file.
17471 (org-add-props
17472 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17473 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17474 'org-latex-src-embed-type (if latex-frag-type
17475 'paragraph 'character)))
17476 ;; Failed conversion. Return the LaTeX fragment verbatim
17477 (add-text-properties
17478 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17479 latex-frag)))
17481 ;; This function borrows from Ganesh Swami's latex2png.el
17482 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17483 "This calls dvipng."
17484 (require 'org-latex)
17485 (let* ((tmpdir (if (featurep 'xemacs)
17486 (temp-directory)
17487 temporary-file-directory))
17488 (texfilebase (make-temp-name
17489 (expand-file-name "orgtex" tmpdir)))
17490 (texfile (concat texfilebase ".tex"))
17491 (dvifile (concat texfilebase ".dvi"))
17492 (pngfile (concat texfilebase ".png"))
17493 (fnh (if (featurep 'xemacs)
17494 (font-height (face-font 'default))
17495 (face-attribute 'default :height nil)))
17496 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17497 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17498 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17499 "Black"))
17500 (bg (or (plist-get options (if buffer :background :html-background))
17501 "Transparent")))
17502 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17503 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17504 (with-temp-file texfile
17505 (insert (org-splice-latex-header
17506 org-format-latex-header
17507 org-export-latex-default-packages-alist
17508 org-export-latex-packages-alist t
17509 org-format-latex-header-extra))
17510 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17511 (require 'org-latex)
17512 (org-export-latex-fix-inputenc))
17513 (let ((dir default-directory))
17514 (condition-case nil
17515 (progn
17516 (cd tmpdir)
17517 (call-process "latex" nil nil nil texfile))
17518 (error nil))
17519 (cd dir))
17520 (if (not (file-exists-p dvifile))
17521 (progn (message "Failed to create dvi file from %s" texfile) nil)
17522 (condition-case nil
17523 (if (featurep 'xemacs)
17524 (call-process "dvipng" nil nil nil
17525 "-fg" fg "-bg" bg
17526 "-T" "tight"
17527 "-o" pngfile
17528 dvifile)
17529 (call-process "dvipng" nil nil nil
17530 "-fg" fg "-bg" bg
17531 "-D" dpi
17532 ;;"-x" scale "-y" scale
17533 "-T" "tight"
17534 "-o" pngfile
17535 dvifile))
17536 (error nil))
17537 (if (not (file-exists-p pngfile))
17538 (if org-format-latex-signal-error
17539 (error "Failed to create png file from %s" texfile)
17540 (message "Failed to create png file from %s" texfile)
17541 nil)
17542 ;; Use the requested file name and clean up
17543 (copy-file pngfile tofile 'replace)
17544 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17545 (if (file-exists-p (concat texfilebase e))
17546 (delete-file (concat texfilebase e))))
17547 pngfile))))
17549 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17550 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17551 "This calls convert, which is included into imagemagick."
17552 (require 'org-latex)
17553 (let* ((tmpdir (if (featurep 'xemacs)
17554 (temp-directory)
17555 temporary-file-directory))
17556 (texfilebase (make-temp-name
17557 (expand-file-name "orgtex" tmpdir)))
17558 (texfile (concat texfilebase ".tex"))
17559 (pdffile (concat texfilebase ".pdf"))
17560 (pngfile (concat texfilebase ".png"))
17561 (fnh (if (featurep 'xemacs)
17562 (font-height (face-font 'default))
17563 (face-attribute 'default :height nil)))
17564 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17565 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17566 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17567 "black"))
17568 (bg (or (plist-get options (if buffer :background :html-background))
17569 "white")))
17570 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17571 (setq fg (org-latex-color-format fg)))
17572 (if (eq bg 'default) (setq bg (org-latex-color :background))
17573 (setq bg (org-latex-color-format
17574 (if (string= bg "Transparent")(setq bg "white")))))
17575 (with-temp-file texfile
17576 (insert (org-splice-latex-header
17577 org-format-latex-header
17578 org-export-latex-default-packages-alist
17579 org-export-latex-packages-alist t
17580 org-format-latex-header-extra))
17581 (insert "\n\\begin{document}\n"
17582 "\\definecolor{fg}{rgb}{" fg "}\n"
17583 "\\definecolor{bg}{rgb}{" bg "}\n"
17584 "\n\\pagecolor{bg}\n"
17585 "\n{\\color{fg}\n"
17586 string
17587 "\n}\n"
17588 "\n\\end{document}\n" )
17589 (require 'org-latex)
17590 (org-export-latex-fix-inputenc))
17591 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17592 (condition-case nil
17593 (progn
17594 (cd tmpdir)
17595 (setq cmds org-latex-to-pdf-process)
17596 (while cmds
17597 (setq latex-frags-cmds (pop cmds))
17598 (if (listp latex-frags-cmds)
17599 (setq cmds nil)
17600 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17601 (while latex-frags-cmds
17602 (setq cmd (pop latex-frags-cmds))
17603 (while (string-match "%b" cmd)
17604 (setq cmd (replace-match
17605 (save-match-data
17606 (shell-quote-argument texfile))
17607 t t cmd)))
17608 (while (string-match "%f" cmd)
17609 (setq cmd (replace-match
17610 (save-match-data
17611 (shell-quote-argument (file-name-nondirectory texfile)))
17612 t t cmd)))
17613 (while (string-match "%o" cmd)
17614 (setq cmd (replace-match
17615 (save-match-data
17616 (shell-quote-argument (file-name-directory texfile)))
17617 t t cmd)))
17618 (setq cmd (split-string cmd))
17619 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17620 (error nil))
17621 (cd dir))
17622 (if (not (file-exists-p pdffile))
17623 (progn (message "Failed to create pdf file from %s" texfile) nil)
17624 (condition-case nil
17625 (if (featurep 'xemacs)
17626 (call-process "convert" nil nil nil
17627 "-density" "96"
17628 "-trim"
17629 "-antialias"
17630 pdffile
17631 "-quality" "100"
17632 ;; "-sharpen" "0x1.0"
17633 pngfile)
17634 (call-process "convert" nil nil nil
17635 "-density" dpi
17636 "-trim"
17637 "-antialias"
17638 pdffile
17639 "-quality" "100"
17640 ; "-sharpen" "0x1.0"
17641 pngfile))
17642 (error nil))
17643 (if (not (file-exists-p pngfile))
17644 (if org-format-latex-signal-error
17645 (error "Failed to create png file from %s" texfile)
17646 (message "Failed to create png file from %s" texfile)
17647 nil)
17648 ;; Use the requested file name and clean up
17649 (copy-file pngfile tofile 'replace)
17650 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17651 (if (file-exists-p (concat texfilebase e))
17652 (delete-file (concat texfilebase e))))
17653 pngfile))))
17655 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17656 "Fill a LaTeX header template TPL.
17657 In the template, the following place holders will be recognized:
17659 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17660 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17661 [PACKAGES] \\usepackage statements for PKG
17662 [NO-PACKAGES] do not include PKG
17663 [EXTRA] the string EXTRA
17664 [NO-EXTRA] do not include EXTRA
17666 For backward compatibility, if both the positive and the negative place
17667 holder is missing, the positive one (without the \"NO-\") will be
17668 assumed to be present at the end of the template.
17669 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17670 EXTRA is a string.
17671 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17672 (let (rpl (end ""))
17673 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17674 (setq rpl (if (or (match-end 1) (not def-pkg))
17675 "" (org-latex-packages-to-string def-pkg snippets-p t))
17676 tpl (replace-match rpl t t tpl))
17677 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17679 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17680 (setq rpl (if (or (match-end 1) (not pkg))
17681 "" (org-latex-packages-to-string pkg snippets-p t))
17682 tpl (replace-match rpl t t tpl))
17683 (if pkg (setq end
17684 (concat end "\n"
17685 (org-latex-packages-to-string pkg snippets-p)))))
17687 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17688 (setq rpl (if (or (match-end 1) (not extra))
17689 "" (concat extra "\n"))
17690 tpl (replace-match rpl t t tpl))
17691 (if (and extra (string-match "\\S-" extra))
17692 (setq end (concat end "\n" extra))))
17694 (if (string-match "\\S-" end)
17695 (concat tpl "\n" end)
17696 tpl)))
17698 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17699 "Turn an alist of packages into a string with the \\usepackage macros."
17700 (setq pkg (mapconcat (lambda(p)
17701 (cond
17702 ((stringp p) p)
17703 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17704 (format "%% Package %s omitted" (cadr p)))
17705 ((equal "" (car p))
17706 (format "\\usepackage{%s}" (cadr p)))
17708 (format "\\usepackage[%s]{%s}"
17709 (car p) (cadr p)))))
17711 "\n"))
17712 (if newline (concat pkg "\n") pkg))
17714 (defun org-dvipng-color (attr)
17715 "Return a RGB color specification for dvipng."
17716 (apply 'format "rgb %s %s %s"
17717 (mapcar 'org-normalize-color
17718 (if (featurep 'xemacs)
17719 (color-rgb-components
17720 (face-property 'default
17721 (cond ((eq attr :foreground) 'foreground)
17722 ((eq attr :background) 'background))))
17723 (color-values (face-attribute 'default attr nil))))))
17725 (defun org-latex-color (attr)
17726 "Return a RGB color for the LaTeX color package."
17727 (apply 'format "%s,%s,%s"
17728 (mapcar 'org-normalize-color
17729 (if (featurep 'xemacs)
17730 (color-rgb-components
17731 (face-property 'default
17732 (cond ((eq attr :foreground) 'foreground)
17733 ((eq attr :background) 'background))))
17734 (color-values (face-attribute 'default attr nil))))))
17736 (defun org-latex-color-format (color-name)
17737 "Convert COLOR-NAME to a RGB color value."
17738 (apply 'format "%s,%s,%s"
17739 (mapcar 'org-normalize-color
17740 (color-values color-name))))
17742 (defun org-normalize-color (value)
17743 "Return string to be used as color value for an RGB component."
17744 (format "%g" (/ value 65535.0)))
17746 ;; Image display
17749 (defvar org-inline-image-overlays nil)
17750 (make-variable-buffer-local 'org-inline-image-overlays)
17752 (defun org-toggle-inline-images (&optional include-linked)
17753 "Toggle the display of inline images.
17754 INCLUDE-LINKED is passed to `org-display-inline-images'."
17755 (interactive "P")
17756 (if org-inline-image-overlays
17757 (progn
17758 (org-remove-inline-images)
17759 (message "Inline image display turned off"))
17760 (org-display-inline-images include-linked)
17761 (if org-inline-image-overlays
17762 (message "%d images displayed inline"
17763 (length org-inline-image-overlays))
17764 (message "No images to display inline"))))
17766 (defun org-redisplay-inline-images ()
17767 "Refresh the display of inline images."
17768 (interactive)
17769 (if (not org-inline-image-overlays)
17770 (org-toggle-inline-images)
17771 (org-toggle-inline-images)
17772 (org-toggle-inline-images)))
17774 (defun org-display-inline-images (&optional include-linked refresh beg end)
17775 "Display inline images.
17776 Normally only links without a description part are inlined, because this
17777 is how it will work for export. When INCLUDE-LINKED is set, also links
17778 with a description part will be inlined. This can be nice for a quick
17779 look at those images, but it does not reflect what exported files will look
17780 like.
17781 When REFRESH is set, refresh existing images between BEG and END.
17782 This will create new image displays only if necessary.
17783 BEG and END default to the buffer boundaries."
17784 (interactive "P")
17785 (unless refresh
17786 (org-remove-inline-images)
17787 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17788 (save-excursion
17789 (save-restriction
17790 (widen)
17791 (setq beg (or beg (point-min)) end (or end (point-max)))
17792 (goto-char beg)
17793 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17794 (substring (org-image-file-name-regexp) 0 -2)
17795 "\\)\\]" (if include-linked "" "\\]")))
17796 old file ov img)
17797 (while (re-search-forward re end t)
17798 (setq old (get-char-property-and-overlay (match-beginning 1)
17799 'org-image-overlay))
17800 (setq file (expand-file-name
17801 (concat (or (match-string 3) "") (match-string 4))))
17802 (when (file-exists-p file)
17803 (if (and (car-safe old) refresh)
17804 (image-refresh (overlay-get (cdr old) 'display))
17805 (setq img (save-match-data (create-image file)))
17806 (when img
17807 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17808 (overlay-put ov 'display img)
17809 (overlay-put ov 'face 'default)
17810 (overlay-put ov 'org-image-overlay t)
17811 (overlay-put ov 'modification-hooks
17812 (list 'org-display-inline-modification-hook))
17813 (push ov org-inline-image-overlays)))))))))
17815 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17816 "Remove inline-display overlay if a corresponding region is modified."
17817 (let ((inhibit-modification-hooks t))
17818 (when (and ov after)
17819 (delete ov org-inline-image-overlays)
17820 (delete-overlay ov))))
17822 (defun org-remove-inline-images ()
17823 "Remove inline display of images."
17824 (interactive)
17825 (mapc 'delete-overlay org-inline-image-overlays)
17826 (setq org-inline-image-overlays nil))
17828 ;;;; Key bindings
17830 ;; Outline functions from `outline-mode-prefix-map'
17831 ;; that can be remapped in Org:
17832 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17833 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17834 (define-key org-mode-map [remap outline-forward-same-level]
17835 'org-forward-heading-same-level)
17836 (define-key org-mode-map [remap outline-backward-same-level]
17837 'org-backward-heading-same-level)
17838 (define-key org-mode-map [remap show-branches]
17839 'org-kill-note-or-show-branches)
17840 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17841 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17842 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17844 ;; Outline functions from `outline-mode-prefix-map' that can not
17845 ;; be remapped in Org:
17847 ;; - the column "key binding" shows whether the Outline function is still
17848 ;; available in Org mode on the same key that it has been bound to in
17849 ;; Outline mode:
17850 ;; - "overridden": key used for a different functionality in Org mode
17851 ;; - else: key still bound to the same Outline function in Org mode
17853 ;; | Outline function | key binding | Org replacement |
17854 ;; |------------------------------------+-------------+-----------------------|
17855 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17856 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17857 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17858 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17859 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17860 ;; | `show-entry' | overridden | no replacement |
17861 ;; | `show-children' | `C-c C-i' | visibility cycling |
17862 ;; | `show-branches' | `C-c C-k' | still same function |
17863 ;; | `show-subtree' | overridden | visibility cycling |
17864 ;; | `show-all' | overridden | no replacement |
17865 ;; | `hide-subtree' | overridden | visibility cycling |
17866 ;; | `hide-body' | overridden | no replacement |
17867 ;; | `hide-entry' | overridden | visibility cycling |
17868 ;; | `hide-leaves' | overridden | no replacement |
17869 ;; | `hide-sublevels' | overridden | no replacement |
17870 ;; | `hide-other' | overridden | no replacement |
17872 ;; Make `C-c C-x' a prefix key
17873 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17875 ;; TAB key with modifiers
17876 (org-defkey org-mode-map "\C-i" 'org-cycle)
17877 (org-defkey org-mode-map [(tab)] 'org-cycle)
17878 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17879 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17880 ;; The following line is necessary under Suse GNU/Linux
17881 (unless (featurep 'xemacs)
17882 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17883 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17884 (define-key org-mode-map [backtab] 'org-shifttab)
17886 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17887 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17888 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17890 ;; Cursor keys with modifiers
17891 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17892 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17893 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17894 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17896 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17897 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17898 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17899 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17901 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17902 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17903 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17904 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17906 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17907 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17908 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17909 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17911 ;; Babel keys
17912 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17913 (mapc (lambda (pair)
17914 (define-key org-babel-map (car pair) (cdr pair)))
17915 org-babel-key-bindings)
17917 ;;; Extra keys for tty access.
17918 ;; We only set them when really needed because otherwise the
17919 ;; menus don't show the simple keys
17921 (when (or org-use-extra-keys
17922 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17923 (not window-system))
17924 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17925 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17926 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17927 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17928 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17929 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17930 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17931 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17932 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17933 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17934 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17935 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17936 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17937 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17938 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17939 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17940 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17941 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17942 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17943 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17944 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17945 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17946 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17947 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17948 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17949 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17950 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17951 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17953 ;; All the other keys
17955 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17956 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17957 (if (boundp 'narrow-map)
17958 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17959 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17960 (if (boundp 'narrow-map)
17961 (org-defkey narrow-map "b" 'org-narrow-to-block)
17962 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17963 (if (boundp 'narrow-map)
17964 (org-defkey narrow-map "e" 'org-narrow-to-element)
17965 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17966 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17967 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17968 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17969 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17970 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17971 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17972 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17973 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17974 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17975 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17976 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17977 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17978 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17979 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17980 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17981 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17982 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17983 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17984 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17985 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17986 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17987 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17988 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17989 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17990 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17991 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17992 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17993 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17994 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17995 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17996 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17997 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17998 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17999 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18000 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18001 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18002 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18003 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18004 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18005 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18006 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18007 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18008 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18009 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18010 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18011 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18012 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18013 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18014 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18015 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18016 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18017 (org-defkey org-mode-map "\C-c^" 'org-sort)
18018 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18019 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18020 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18021 (org-defkey org-mode-map "\C-m" 'org-return)
18022 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18023 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18024 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18025 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18026 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18027 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18028 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18029 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18030 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18031 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18032 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18033 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18034 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18035 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18036 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18037 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18038 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18039 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18040 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18041 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18042 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18043 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18044 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18046 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18047 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18048 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18049 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18051 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18052 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18053 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18054 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18055 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18056 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18057 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18058 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18059 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18060 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18061 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18062 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18063 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18064 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18065 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18066 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18067 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18068 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18069 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18070 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18071 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18072 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18074 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18075 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18076 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18077 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18078 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18080 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18082 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18084 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18085 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18087 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18090 (when (featurep 'xemacs)
18091 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18094 (defconst org-speed-commands-default
18096 ("Outline Navigation")
18097 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18098 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18099 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18100 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18101 ("u" . (org-speed-move-safe 'outline-up-heading))
18102 ("j" . org-goto)
18103 ("g" . (org-refile t))
18104 ("Outline Visibility")
18105 ("c" . org-cycle)
18106 ("C" . org-shifttab)
18107 (" " . org-display-outline-path)
18108 (":" . org-columns)
18109 ("Outline Structure Editing")
18110 ("U" . org-shiftmetaup)
18111 ("D" . org-shiftmetadown)
18112 ("r" . org-metaright)
18113 ("l" . org-metaleft)
18114 ("R" . org-shiftmetaright)
18115 ("L" . org-shiftmetaleft)
18116 ("i" . (progn (forward-char 1) (call-interactively
18117 'org-insert-heading-respect-content)))
18118 ("^" . org-sort)
18119 ("w" . org-refile)
18120 ("a" . org-archive-subtree-default-with-confirmation)
18121 ("." . org-mark-subtree)
18122 ("#" . org-toggle-comment)
18123 ("Clock Commands")
18124 ("I" . org-clock-in)
18125 ("O" . org-clock-out)
18126 ("Meta Data Editing")
18127 ("t" . org-todo)
18128 ("0" . (org-priority ?\ ))
18129 ("1" . (org-priority ?A))
18130 ("2" . (org-priority ?B))
18131 ("3" . (org-priority ?C))
18132 (";" . org-set-tags-command)
18133 ("e" . org-set-effort)
18134 ("E" . org-inc-effort)
18135 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18136 (org-entry-put (point) "APPT_WARNTIME" m)))
18137 ("Agenda Views etc")
18138 ("v" . org-agenda)
18139 ("/" . org-sparse-tree)
18140 ("Misc")
18141 ("o" . org-open-at-point)
18142 ("?" . org-speed-command-help)
18143 ("<" . (org-agenda-set-restriction-lock 'subtree))
18144 (">" . (org-agenda-remove-restriction-lock))
18146 "The default speed commands.")
18148 (defun org-print-speed-command (e)
18149 (if (> (length (car e)) 1)
18150 (progn
18151 (princ "\n")
18152 (princ (car e))
18153 (princ "\n")
18154 (princ (make-string (length (car e)) ?-))
18155 (princ "\n"))
18156 (princ (car e))
18157 (princ " ")
18158 (if (symbolp (cdr e))
18159 (princ (symbol-name (cdr e)))
18160 (prin1 (cdr e)))
18161 (princ "\n")))
18163 (defun org-speed-command-help ()
18164 "Show the available speed commands."
18165 (interactive)
18166 (if (not org-use-speed-commands)
18167 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18168 (with-output-to-temp-buffer "*Help*"
18169 (princ "User-defined Speed commands\n===========================\n")
18170 (mapc 'org-print-speed-command org-speed-commands-user)
18171 (princ "\n")
18172 (princ "Built-in Speed commands\n=======================\n")
18173 (mapc 'org-print-speed-command org-speed-commands-default))
18174 (with-current-buffer "*Help*"
18175 (setq truncate-lines t))))
18177 (defun org-speed-move-safe (cmd)
18178 "Execute CMD, but make sure that the cursor always ends up in a headline.
18179 If not, return to the original position and throw an error."
18180 (interactive)
18181 (let ((pos (point)))
18182 (call-interactively cmd)
18183 (unless (and (bolp) (org-at-heading-p))
18184 (goto-char pos)
18185 (error "Boundary reached while executing %s" cmd))))
18187 (defvar org-self-insert-command-undo-counter 0)
18189 (defvar org-table-auto-blank-field) ; defined in org-table.el
18190 (defvar org-speed-command nil)
18192 (defun org-speed-command-default-hook (keys)
18193 "Hook for activating single-letter speed commands.
18194 `org-speed-commands-default' specifies a minimal command set.
18195 Use `org-speed-commands-user' for further customization."
18196 (when (or (and (bolp) (looking-at org-outline-regexp))
18197 (and (functionp org-use-speed-commands)
18198 (funcall org-use-speed-commands)))
18199 (cdr (assoc keys (append org-speed-commands-user
18200 org-speed-commands-default)))))
18202 (defun org-babel-speed-command-hook (keys)
18203 "Hook for activating single-letter code block commands."
18204 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18205 (cdr (assoc keys org-babel-key-bindings))))
18207 (defcustom org-speed-command-hook
18208 '(org-speed-command-default-hook org-babel-speed-command-hook)
18209 "Hook for activating speed commands at strategic locations.
18210 Hook functions are called in sequence until a valid handler is
18211 found.
18213 Each hook takes a single argument, a user-pressed command key
18214 which is also a `self-insert-command' from the global map.
18216 Within the hook, examine the cursor position and the command key
18217 and return nil or a valid handler as appropriate. Handler could
18218 be one of an interactive command, a function, or a form.
18220 Set `org-use-speed-commands' to non-nil value to enable this
18221 hook. The default setting is `org-speed-command-default-hook'."
18222 :group 'org-structure
18223 :version "24.1"
18224 :type 'hook)
18226 (defun org-self-insert-command (N)
18227 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18228 If the cursor is in a table looking at whitespace, the whitespace is
18229 overwritten, and the table is not marked as requiring realignment."
18230 (interactive "p")
18231 (org-check-before-invisible-edit 'insert)
18232 (cond
18233 ((and org-use-speed-commands
18234 (setq org-speed-command
18235 (run-hook-with-args-until-success
18236 'org-speed-command-hook (this-command-keys))))
18237 (cond
18238 ((commandp org-speed-command)
18239 (setq this-command org-speed-command)
18240 (call-interactively org-speed-command))
18241 ((functionp org-speed-command)
18242 (funcall org-speed-command))
18243 ((and org-speed-command (listp org-speed-command))
18244 (eval org-speed-command))
18245 (t (let (org-use-speed-commands)
18246 (call-interactively 'org-self-insert-command)))))
18247 ((and
18248 (org-table-p)
18249 (progn
18250 ;; check if we blank the field, and if that triggers align
18251 (and (featurep 'org-table) org-table-auto-blank-field
18252 (member last-command
18253 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18254 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18255 ;; got extra space, this field does not determine column width
18256 (let (org-table-may-need-update) (org-table-blank-field))
18257 ;; no extra space, this field may determine column width
18258 (org-table-blank-field)))
18260 (eq N 1)
18261 (looking-at "[^|\n]* |"))
18262 (let (org-table-may-need-update)
18263 (goto-char (1- (match-end 0)))
18264 (backward-delete-char 1)
18265 (goto-char (match-beginning 0))
18266 (self-insert-command N)))
18268 (setq org-table-may-need-update t)
18269 (self-insert-command N)
18270 (org-fix-tags-on-the-fly)
18271 (if org-self-insert-cluster-for-undo
18272 (if (not (eq last-command 'org-self-insert-command))
18273 (setq org-self-insert-command-undo-counter 1)
18274 (if (>= org-self-insert-command-undo-counter 20)
18275 (setq org-self-insert-command-undo-counter 1)
18276 (and (> org-self-insert-command-undo-counter 0)
18277 buffer-undo-list (listp buffer-undo-list)
18278 (not (cadr buffer-undo-list)) ; remove nil entry
18279 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18280 (setq org-self-insert-command-undo-counter
18281 (1+ org-self-insert-command-undo-counter))))))))
18283 (defun org-check-before-invisible-edit (kind)
18284 "Check is editing if kind KIND would be dangerous with invisible text around.
18285 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18286 ;; First, try to get out of here as quickly as possible, to reduce overhead
18287 (if (and org-catch-invisible-edits
18288 (or (not (boundp 'visible-mode)) (not visible-mode))
18289 (or (get-char-property (point) 'invisible)
18290 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18291 ;; OK, we need to take a closer look
18292 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18293 (invisible-before-point (if (bobp) nil (get-char-property
18294 (1- (point)) 'invisible)))
18295 (border-and-ok-direction
18297 ;; Check if we are acting predictably before invisible text
18298 (and invisible-at-point (not invisible-before-point)
18299 (memq kind '(insert delete-backward)))
18300 ;; Check if we are acting predictably after invisible text
18301 ;; This works not well, and I have turned it off. It seems
18302 ;; better to always show and stop after invisible text.
18303 ;; (and (not invisible-at-point) invisible-before-point
18304 ;; (memq kind '(insert delete)))
18306 (when (or (memq invisible-at-point '(outline org-hide-block t))
18307 (memq invisible-before-point '(outline org-hide-block t)))
18308 (if (eq org-catch-invisible-edits 'error)
18309 (error "Editing in invisible areas is prohibited - make visible first"))
18310 (if (and org-custom-properties-overlays
18311 (y-or-n-p "Display invisible properties in this buffer? "))
18312 (org-toggle-custom-properties-visibility)
18313 ;; Make the area visible
18314 (save-excursion
18315 (if invisible-before-point
18316 (goto-char (previous-single-char-property-change
18317 (point) 'invisible)))
18318 (org-cycle))
18319 (cond
18320 ((eq org-catch-invisible-edits 'show)
18321 ;; That's it, we do the edit after showing
18322 (message
18323 "Unfolding invisible region around point before editing")
18324 (sit-for 1))
18325 ((and (eq org-catch-invisible-edits 'smart)
18326 border-and-ok-direction)
18327 (message "Unfolding invisible region around point before editing"))
18329 ;; Don't do the edit, make the user repeat it in full visibility
18330 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18332 (defun org-fix-tags-on-the-fly ()
18333 (when (and (equal (char-after (point-at-bol)) ?*)
18334 (org-at-heading-p))
18335 (org-align-tags-here org-tags-column)))
18337 (defun org-delete-backward-char (N)
18338 "Like `delete-backward-char', insert whitespace at field end in tables.
18339 When deleting backwards, in tables this function will insert whitespace in
18340 front of the next \"|\" separator, to keep the table aligned. The table will
18341 still be marked for re-alignment if the field did fill the entire column,
18342 because, in this case the deletion might narrow the column."
18343 (interactive "p")
18344 (org-check-before-invisible-edit 'delete-backward)
18345 (if (and (org-table-p)
18346 (eq N 1)
18347 (string-match "|" (buffer-substring (point-at-bol) (point)))
18348 (looking-at ".*?|"))
18349 (let ((pos (point))
18350 (noalign (looking-at "[^|\n\r]* |"))
18351 (c org-table-may-need-update))
18352 (backward-delete-char N)
18353 (if (not overwrite-mode)
18354 (progn
18355 (skip-chars-forward "^|")
18356 (insert " ")
18357 (goto-char (1- pos))))
18358 ;; noalign: if there were two spaces at the end, this field
18359 ;; does not determine the width of the column.
18360 (if noalign (setq org-table-may-need-update c)))
18361 (backward-delete-char N)
18362 (org-fix-tags-on-the-fly)))
18364 (defun org-delete-char (N)
18365 "Like `delete-char', but insert whitespace at field end in tables.
18366 When deleting characters, in tables this function will insert whitespace in
18367 front of the next \"|\" separator, to keep the table aligned. The table will
18368 still be marked for re-alignment if the field did fill the entire column,
18369 because, in this case the deletion might narrow the column."
18370 (interactive "p")
18371 (org-check-before-invisible-edit 'delete)
18372 (if (and (org-table-p)
18373 (not (bolp))
18374 (not (= (char-after) ?|))
18375 (eq N 1))
18376 (if (looking-at ".*?|")
18377 (let ((pos (point))
18378 (noalign (looking-at "[^|\n\r]* |"))
18379 (c org-table-may-need-update))
18380 (replace-match (concat
18381 (substring (match-string 0) 1 -1)
18382 " |"))
18383 (goto-char pos)
18384 ;; noalign: if there were two spaces at the end, this field
18385 ;; does not determine the width of the column.
18386 (if noalign (setq org-table-may-need-update c)))
18387 (delete-char N))
18388 (delete-char N)
18389 (org-fix-tags-on-the-fly)))
18391 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18392 (put 'org-self-insert-command 'delete-selection t)
18393 (put 'orgtbl-self-insert-command 'delete-selection t)
18394 (put 'org-delete-char 'delete-selection 'supersede)
18395 (put 'org-delete-backward-char 'delete-selection 'supersede)
18396 (put 'org-yank 'delete-selection 'yank)
18398 ;; Make `flyspell-mode' delay after some commands
18399 (put 'org-self-insert-command 'flyspell-delayed t)
18400 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18401 (put 'org-delete-char 'flyspell-delayed t)
18402 (put 'org-delete-backward-char 'flyspell-delayed t)
18404 ;; Make pabbrev-mode expand after org-mode commands
18405 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18406 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18408 ;; How to do this: Measure non-white length of current string
18409 ;; If equal to column width, we should realign.
18411 (defun org-remap (map &rest commands)
18412 "In MAP, remap the functions given in COMMANDS.
18413 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18414 (let (new old)
18415 (while commands
18416 (setq old (pop commands) new (pop commands))
18417 (if (fboundp 'command-remapping)
18418 (org-defkey map (vector 'remap old) new)
18419 (substitute-key-definition old new map global-map)))))
18421 (when (eq org-enable-table-editor 'optimized)
18422 ;; If the user wants maximum table support, we need to hijack
18423 ;; some standard editing functions
18424 (org-remap org-mode-map
18425 'self-insert-command 'org-self-insert-command
18426 'delete-char 'org-delete-char
18427 'delete-backward-char 'org-delete-backward-char)
18428 (org-defkey org-mode-map "|" 'org-force-self-insert))
18430 (defvar org-ctrl-c-ctrl-c-hook nil
18431 "Hook for functions attaching themselves to `C-c C-c'.
18433 This can be used to add additional functionality to the C-c C-c
18434 key which executes context-dependent commands. This hook is run
18435 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18436 run after the last test.
18438 Each function will be called with no arguments. The function
18439 must check if the context is appropriate for it to act. If yes,
18440 it should do its thing and then return a non-nil value. If the
18441 context is wrong, just do nothing and return nil.")
18443 (defvar org-ctrl-c-ctrl-c-final-hook nil
18444 "Hook for functions attaching themselves to `C-c C-c'.
18446 This can be used to add additional functionality to the C-c C-c
18447 key which executes context-dependent commands. This hook is run
18448 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18449 before the first test.
18451 Each function will be called with no arguments. The function
18452 must check if the context is appropriate for it to act. If yes,
18453 it should do its thing and then return a non-nil value. If the
18454 context is wrong, just do nothing and return nil.")
18456 (defvar org-tab-first-hook nil
18457 "Hook for functions to attach themselves to TAB.
18458 See `org-ctrl-c-ctrl-c-hook' for more information.
18459 This hook runs as the first action when TAB is pressed, even before
18460 `org-cycle' messes around with the `outline-regexp' to cater for
18461 inline tasks and plain list item folding.
18462 If any function in this hook returns t, any other actions that
18463 would have been caused by TAB (such as table field motion or visibility
18464 cycling) will not occur.")
18466 (defvar org-tab-after-check-for-table-hook nil
18467 "Hook for functions to attach themselves to TAB.
18468 See `org-ctrl-c-ctrl-c-hook' for more information.
18469 This hook runs after it has been established that the cursor is not in a
18470 table, but before checking if the cursor is in a headline or if global cycling
18471 should be done.
18472 If any function in this hook returns t, not other actions like visibility
18473 cycling will be done.")
18475 (defvar org-tab-after-check-for-cycling-hook nil
18476 "Hook for functions to attach themselves to TAB.
18477 See `org-ctrl-c-ctrl-c-hook' for more information.
18478 This hook runs after it has been established that not table field motion and
18479 not visibility should be done because of current context. This is probably
18480 the place where a package like yasnippets can hook in.")
18482 (defvar org-tab-before-tab-emulation-hook nil
18483 "Hook for functions to attach themselves to TAB.
18484 See `org-ctrl-c-ctrl-c-hook' for more information.
18485 This hook runs after every other options for TAB have been exhausted, but
18486 before indentation and \t insertion takes place.")
18488 (defvar org-metaleft-hook nil
18489 "Hook for functions attaching themselves to `M-left'.
18490 See `org-ctrl-c-ctrl-c-hook' for more information.")
18491 (defvar org-metaright-hook nil
18492 "Hook for functions attaching themselves to `M-right'.
18493 See `org-ctrl-c-ctrl-c-hook' for more information.")
18494 (defvar org-metaup-hook nil
18495 "Hook for functions attaching themselves to `M-up'.
18496 See `org-ctrl-c-ctrl-c-hook' for more information.")
18497 (defvar org-metadown-hook nil
18498 "Hook for functions attaching themselves to `M-down'.
18499 See `org-ctrl-c-ctrl-c-hook' for more information.")
18500 (defvar org-shiftmetaleft-hook nil
18501 "Hook for functions attaching themselves to `M-S-left'.
18502 See `org-ctrl-c-ctrl-c-hook' for more information.")
18503 (defvar org-shiftmetaright-hook nil
18504 "Hook for functions attaching themselves to `M-S-right'.
18505 See `org-ctrl-c-ctrl-c-hook' for more information.")
18506 (defvar org-shiftmetaup-hook nil
18507 "Hook for functions attaching themselves to `M-S-up'.
18508 See `org-ctrl-c-ctrl-c-hook' for more information.")
18509 (defvar org-shiftmetadown-hook nil
18510 "Hook for functions attaching themselves to `M-S-down'.
18511 See `org-ctrl-c-ctrl-c-hook' for more information.")
18512 (defvar org-metareturn-hook nil
18513 "Hook for functions attaching themselves to `M-RET'.
18514 See `org-ctrl-c-ctrl-c-hook' for more information.")
18515 (defvar org-shiftup-hook nil
18516 "Hook for functions attaching themselves to `S-up'.
18517 See `org-ctrl-c-ctrl-c-hook' for more information.")
18518 (defvar org-shiftup-final-hook nil
18519 "Hook for functions attaching themselves to `S-up'.
18520 This one runs after all other options except shift-select have been excluded.
18521 See `org-ctrl-c-ctrl-c-hook' for more information.")
18522 (defvar org-shiftdown-hook nil
18523 "Hook for functions attaching themselves to `S-down'.
18524 See `org-ctrl-c-ctrl-c-hook' for more information.")
18525 (defvar org-shiftdown-final-hook nil
18526 "Hook for functions attaching themselves to `S-down'.
18527 This one runs after all other options except shift-select have been excluded.
18528 See `org-ctrl-c-ctrl-c-hook' for more information.")
18529 (defvar org-shiftleft-hook nil
18530 "Hook for functions attaching themselves to `S-left'.
18531 See `org-ctrl-c-ctrl-c-hook' for more information.")
18532 (defvar org-shiftleft-final-hook nil
18533 "Hook for functions attaching themselves to `S-left'.
18534 This one runs after all other options except shift-select have been excluded.
18535 See `org-ctrl-c-ctrl-c-hook' for more information.")
18536 (defvar org-shiftright-hook nil
18537 "Hook for functions attaching themselves to `S-right'.
18538 See `org-ctrl-c-ctrl-c-hook' for more information.")
18539 (defvar org-shiftright-final-hook nil
18540 "Hook for functions attaching themselves to `S-right'.
18541 This one runs after all other options except shift-select have been excluded.
18542 See `org-ctrl-c-ctrl-c-hook' for more information.")
18544 (defun org-modifier-cursor-error ()
18545 "Throw an error, a modified cursor command was applied in wrong context."
18546 (error "This command is active in special context like tables, headlines or items"))
18548 (defun org-shiftselect-error ()
18549 "Throw an error because Shift-Cursor command was applied in wrong context."
18550 (if (and (boundp 'shift-select-mode) shift-select-mode)
18551 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18552 (error "This command works only in special context like headlines or timestamps")))
18554 (defun org-call-for-shift-select (cmd)
18555 (let ((this-command-keys-shift-translated t))
18556 (call-interactively cmd)))
18558 (defun org-shifttab (&optional arg)
18559 "Global visibility cycling or move to previous table field.
18560 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18561 on context.
18562 See the individual commands for more information."
18563 (interactive "P")
18564 (cond
18565 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18566 ((integerp arg)
18567 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18568 (message "Content view to level: %d" arg)
18569 (org-content (prefix-numeric-value arg2))
18570 (setq org-cycle-global-status 'overview)))
18571 (t (call-interactively 'org-global-cycle))))
18573 (defun org-shiftmetaleft ()
18574 "Promote subtree or delete table column.
18575 Calls `org-promote-subtree', `org-outdent-item-tree', or
18576 `org-table-delete-column', depending on context. See the
18577 individual commands for more information."
18578 (interactive)
18579 (cond
18580 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18581 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18582 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18583 ((if (not (org-region-active-p)) (org-at-item-p)
18584 (save-excursion (goto-char (region-beginning))
18585 (org-at-item-p)))
18586 (call-interactively 'org-outdent-item-tree))
18587 (t (org-modifier-cursor-error))))
18589 (defun org-shiftmetaright ()
18590 "Demote subtree or insert table column.
18591 Calls `org-demote-subtree', `org-indent-item-tree', or
18592 `org-table-insert-column', depending on context. See the
18593 individual commands for more information."
18594 (interactive)
18595 (cond
18596 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18597 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18598 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18599 ((if (not (org-region-active-p)) (org-at-item-p)
18600 (save-excursion (goto-char (region-beginning))
18601 (org-at-item-p)))
18602 (call-interactively 'org-indent-item-tree))
18603 (t (org-modifier-cursor-error))))
18605 (defun org-shiftmetaup (&optional arg)
18606 "Move subtree up or kill table row.
18607 Calls `org-move-subtree-up' or `org-table-kill-row' or
18608 `org-move-item-up' or `org-timestamp-up', depending on context.
18609 See the individual commands for more information."
18610 (interactive "P")
18611 (cond
18612 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18613 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18614 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18615 ((org-at-item-p) (call-interactively 'org-move-item-up))
18616 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18617 (call-interactively 'org-timestamp-up)))
18618 (t (org-modifier-cursor-error))))
18620 (defun org-shiftmetadown (&optional arg)
18621 "Move subtree down or insert table row.
18622 Calls `org-move-subtree-down' or `org-table-insert-row' or
18623 `org-move-item-down' or `org-timestamp-up', depending on context.
18624 See the individual commands for more information."
18625 (interactive "P")
18626 (cond
18627 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18628 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18629 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18630 ((org-at-item-p) (call-interactively 'org-move-item-down))
18631 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18632 (call-interactively 'org-timestamp-down)))
18633 (t (org-modifier-cursor-error))))
18635 (defsubst org-hidden-tree-error ()
18636 (error
18637 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18639 (defun org-metaleft (&optional arg)
18640 "Promote heading or move table column to left.
18641 Calls `org-do-promote' or `org-table-move-column', depending on context.
18642 With no specific context, calls the Emacs default `backward-word'.
18643 See the individual commands for more information."
18644 (interactive "P")
18645 (cond
18646 ((run-hook-with-args-until-success 'org-metaleft-hook))
18647 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18648 ((org-with-limited-levels
18649 (or (org-at-heading-p)
18650 (and (org-region-active-p)
18651 (save-excursion
18652 (goto-char (region-beginning))
18653 (org-at-heading-p)))))
18654 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18655 (call-interactively 'org-do-promote))
18656 ;; At an inline task.
18657 ((org-at-heading-p)
18658 (call-interactively 'org-inlinetask-promote))
18659 ((or (org-at-item-p)
18660 (and (org-region-active-p)
18661 (save-excursion
18662 (goto-char (region-beginning))
18663 (org-at-item-p))))
18664 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18665 (call-interactively 'org-outdent-item))
18666 (t (call-interactively 'backward-word))))
18668 (defun org-metaright (&optional arg)
18669 "Demote a subtree, a list item or move table column to right.
18670 In front of a drawer or a block keyword, indent it correctly.
18671 With no specific context, calls the Emacs default `forward-word'.
18672 See the individual commands for more information."
18673 (interactive "P")
18674 (cond
18675 ((run-hook-with-args-until-success 'org-metaright-hook))
18676 ((org-at-table-p) (call-interactively 'org-table-move-column))
18677 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18678 ((org-at-block-p) (call-interactively 'org-indent-block))
18679 ((org-with-limited-levels
18680 (or (org-at-heading-p)
18681 (and (org-region-active-p)
18682 (save-excursion
18683 (goto-char (region-beginning))
18684 (org-at-heading-p)))))
18685 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18686 (call-interactively 'org-do-demote))
18687 ;; At an inline task.
18688 ((org-at-heading-p)
18689 (call-interactively 'org-inlinetask-demote))
18690 ((or (org-at-item-p)
18691 (and (org-region-active-p)
18692 (save-excursion
18693 (goto-char (region-beginning))
18694 (org-at-item-p))))
18695 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18696 (call-interactively 'org-indent-item))
18697 (t (call-interactively 'forward-word))))
18699 (defun org-check-for-hidden (what)
18700 "Check if there are hidden headlines/items in the current visual line.
18701 WHAT can be either `headlines' or `items'. If the current line is
18702 an outline or item heading and it has a folded subtree below it,
18703 this function returns t, nil otherwise."
18704 (let ((re (cond
18705 ((eq what 'headlines) org-outline-regexp-bol)
18706 ((eq what 'items) (org-item-beginning-re))
18707 (t (error "This should not happen"))))
18708 beg end)
18709 (save-excursion
18710 (catch 'exit
18711 (unless (org-region-active-p)
18712 (setq beg (point-at-bol))
18713 (beginning-of-line 2)
18714 (while (and (not (eobp)) ;; this is like `next-line'
18715 (get-char-property (1- (point)) 'invisible))
18716 (beginning-of-line 2))
18717 (setq end (point))
18718 (goto-char beg)
18719 (goto-char (point-at-eol))
18720 (setq end (max end (point)))
18721 (while (re-search-forward re end t)
18722 (if (get-char-property (match-beginning 0) 'invisible)
18723 (throw 'exit t))))
18724 nil))))
18726 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18727 (declare-function org-element-type "org-element" (element))
18728 (declare-function org-element-contents "org-element" (element))
18729 (declare-function org-element-property "org-element" (property element))
18730 (declare-function org-element-paragraph-parser "org-element" (limit))
18731 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18732 (declare-function org-element-up "org-element" ())
18733 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18734 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18735 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18736 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18738 (defun org-metaup (&optional arg)
18739 "Move subtree up or move table row up.
18740 Calls `org-move-subtree-up' or `org-table-move-row' or
18741 `org-move-item-up', depending on context. See the individual commands
18742 for more information."
18743 (interactive "P")
18744 (cond
18745 ((run-hook-with-args-until-success 'org-metaup-hook))
18746 ((org-region-active-p)
18747 (let* ((a (min (region-beginning) (region-end)))
18748 (b (1- (max (region-beginning) (region-end))))
18749 (c (save-excursion (goto-char a)
18750 (move-beginning-of-line 0)))
18751 (d (save-excursion (goto-char a)
18752 (move-end-of-line 0) (point))))
18753 (transpose-regions a b c d)
18754 (goto-char c)))
18755 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18756 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18757 ((org-at-item-p) (call-interactively 'org-move-item-up))
18758 (t (org-drag-element-backward))))
18760 (defun org-metadown (&optional arg)
18761 "Move subtree down or move table row down.
18762 Calls `org-move-subtree-down' or `org-table-move-row' or
18763 `org-move-item-down', depending on context. See the individual
18764 commands for more information."
18765 (interactive "P")
18766 (cond
18767 ((run-hook-with-args-until-success 'org-metadown-hook))
18768 ((org-region-active-p)
18769 (let* ((a (min (region-beginning) (region-end)))
18770 (b (max (region-beginning) (region-end)))
18771 (c (save-excursion (goto-char b)
18772 (move-beginning-of-line 1)))
18773 (d (save-excursion (goto-char b)
18774 (move-end-of-line 1) (1+ (point)))))
18775 (transpose-regions a b c d)
18776 (goto-char d)))
18777 ((org-at-table-p) (call-interactively 'org-table-move-row))
18778 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18779 ((org-at-item-p) (call-interactively 'org-move-item-down))
18780 (t (org-drag-element-forward))))
18782 (defun org-shiftup (&optional arg)
18783 "Increase item in timestamp or increase priority of current headline.
18784 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18785 depending on context. See the individual commands for more information."
18786 (interactive "P")
18787 (cond
18788 ((run-hook-with-args-until-success 'org-shiftup-hook))
18789 ((and org-support-shift-select (org-region-active-p))
18790 (org-call-for-shift-select 'previous-line))
18791 ((org-at-timestamp-p t)
18792 (call-interactively (if org-edit-timestamp-down-means-later
18793 'org-timestamp-down 'org-timestamp-up)))
18794 ((and (not (eq org-support-shift-select 'always))
18795 org-enable-priority-commands
18796 (org-at-heading-p))
18797 (call-interactively 'org-priority-up))
18798 ((and (not org-support-shift-select) (org-at-item-p))
18799 (call-interactively 'org-previous-item))
18800 ((org-clocktable-try-shift 'up arg))
18801 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18802 (org-support-shift-select
18803 (org-call-for-shift-select 'previous-line))
18804 (t (org-shiftselect-error))))
18806 (defun org-shiftdown (&optional arg)
18807 "Decrease item in timestamp or decrease priority of current headline.
18808 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18809 depending on context. See the individual commands for more information."
18810 (interactive "P")
18811 (cond
18812 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18813 ((and org-support-shift-select (org-region-active-p))
18814 (org-call-for-shift-select 'next-line))
18815 ((org-at-timestamp-p t)
18816 (call-interactively (if org-edit-timestamp-down-means-later
18817 'org-timestamp-up 'org-timestamp-down)))
18818 ((and (not (eq org-support-shift-select 'always))
18819 org-enable-priority-commands
18820 (org-at-heading-p))
18821 (call-interactively 'org-priority-down))
18822 ((and (not org-support-shift-select) (org-at-item-p))
18823 (call-interactively 'org-next-item))
18824 ((org-clocktable-try-shift 'down arg))
18825 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18826 (org-support-shift-select
18827 (org-call-for-shift-select 'next-line))
18828 (t (org-shiftselect-error))))
18830 (defun org-shiftright (&optional arg)
18831 "Cycle the thing at point or in the current line, depending on context.
18832 Depending on context, this does one of the following:
18834 - switch a timestamp at point one day into the future
18835 - on a headline, switch to the next TODO keyword.
18836 - on an item, switch entire list to the next bullet type
18837 - on a property line, switch to the next allowed value
18838 - on a clocktable definition line, move time block into the future"
18839 (interactive "P")
18840 (cond
18841 ((run-hook-with-args-until-success 'org-shiftright-hook))
18842 ((and org-support-shift-select (org-region-active-p))
18843 (org-call-for-shift-select 'forward-char))
18844 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18845 ((and (not (eq org-support-shift-select 'always))
18846 (org-at-heading-p))
18847 (let ((org-inhibit-logging
18848 (not org-treat-S-cursor-todo-selection-as-state-change))
18849 (org-inhibit-blocking
18850 (not org-treat-S-cursor-todo-selection-as-state-change)))
18851 (org-call-with-arg 'org-todo 'right)))
18852 ((or (and org-support-shift-select
18853 (not (eq org-support-shift-select 'always))
18854 (org-at-item-bullet-p))
18855 (and (not org-support-shift-select) (org-at-item-p)))
18856 (org-call-with-arg 'org-cycle-list-bullet nil))
18857 ((and (not (eq org-support-shift-select 'always))
18858 (org-at-property-p))
18859 (call-interactively 'org-property-next-allowed-value))
18860 ((org-clocktable-try-shift 'right arg))
18861 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18862 (org-support-shift-select
18863 (org-call-for-shift-select 'forward-char))
18864 (t (org-shiftselect-error))))
18866 (defun org-shiftleft (&optional arg)
18867 "Cycle the thing at point or in the current line, depending on context.
18868 Depending on context, this does one of the following:
18870 - switch a timestamp at point one day into the past
18871 - on a headline, switch to the previous TODO keyword.
18872 - on an item, switch entire list to the previous bullet type
18873 - on a property line, switch to the previous allowed value
18874 - on a clocktable definition line, move time block into the past"
18875 (interactive "P")
18876 (cond
18877 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18878 ((and org-support-shift-select (org-region-active-p))
18879 (org-call-for-shift-select 'backward-char))
18880 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18881 ((and (not (eq org-support-shift-select 'always))
18882 (org-at-heading-p))
18883 (let ((org-inhibit-logging
18884 (not org-treat-S-cursor-todo-selection-as-state-change))
18885 (org-inhibit-blocking
18886 (not org-treat-S-cursor-todo-selection-as-state-change)))
18887 (org-call-with-arg 'org-todo 'left)))
18888 ((or (and org-support-shift-select
18889 (not (eq org-support-shift-select 'always))
18890 (org-at-item-bullet-p))
18891 (and (not org-support-shift-select) (org-at-item-p)))
18892 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18893 ((and (not (eq org-support-shift-select 'always))
18894 (org-at-property-p))
18895 (call-interactively 'org-property-previous-allowed-value))
18896 ((org-clocktable-try-shift 'left arg))
18897 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18898 (org-support-shift-select
18899 (org-call-for-shift-select 'backward-char))
18900 (t (org-shiftselect-error))))
18902 (defun org-shiftcontrolright ()
18903 "Switch to next TODO set."
18904 (interactive)
18905 (cond
18906 ((and org-support-shift-select (org-region-active-p))
18907 (org-call-for-shift-select 'forward-word))
18908 ((and (not (eq org-support-shift-select 'always))
18909 (org-at-heading-p))
18910 (org-call-with-arg 'org-todo 'nextset))
18911 (org-support-shift-select
18912 (org-call-for-shift-select 'forward-word))
18913 (t (org-shiftselect-error))))
18915 (defun org-shiftcontrolleft ()
18916 "Switch to previous TODO set."
18917 (interactive)
18918 (cond
18919 ((and org-support-shift-select (org-region-active-p))
18920 (org-call-for-shift-select 'backward-word))
18921 ((and (not (eq org-support-shift-select 'always))
18922 (org-at-heading-p))
18923 (org-call-with-arg 'org-todo 'previousset))
18924 (org-support-shift-select
18925 (org-call-for-shift-select 'backward-word))
18926 (t (org-shiftselect-error))))
18928 (defun org-shiftcontrolup ()
18929 "Change timestamps synchronously up in CLOCK log lines."
18930 (interactive)
18931 (cond ((and (not org-support-shift-select)
18932 (org-at-clock-log-p)
18933 (org-at-timestamp-p t))
18934 (org-clock-timestamps-up))
18935 (t (org-shiftselect-error))))
18937 (defun org-shiftcontroldown ()
18938 "Change timestamps synchronously down in CLOCK log lines."
18939 (interactive)
18940 (cond ((and (not org-support-shift-select)
18941 (org-at-clock-log-p)
18942 (org-at-timestamp-p t))
18943 (org-clock-timestamps-down))
18944 (t (org-shiftselect-error))))
18946 (defun org-ctrl-c-ret ()
18947 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18948 (interactive)
18949 (cond
18950 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18951 (t (call-interactively 'org-insert-heading))))
18953 (defun org-find-visible ()
18954 (let ((s (point)))
18955 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18956 (get-char-property s 'invisible)))
18958 (defun org-find-invisible ()
18959 (let ((s (point)))
18960 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18961 (not (get-char-property s 'invisible))))
18964 (defun org-copy-visible (beg end)
18965 "Copy the visible parts of the region."
18966 (interactive "r")
18967 (let (snippets s)
18968 (save-excursion
18969 (save-restriction
18970 (narrow-to-region beg end)
18971 (setq s (goto-char (point-min)))
18972 (while (not (= (point) (point-max)))
18973 (goto-char (org-find-invisible))
18974 (push (buffer-substring s (point)) snippets)
18975 (setq s (goto-char (org-find-visible))))))
18976 (kill-new (apply 'concat (nreverse snippets)))))
18978 (defun org-copy-special ()
18979 "Copy region in table or copy current subtree.
18980 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18981 See the individual commands for more information."
18982 (interactive)
18983 (call-interactively
18984 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18986 (defun org-cut-special ()
18987 "Cut region in table or cut current subtree.
18988 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18989 See the individual commands for more information."
18990 (interactive)
18991 (call-interactively
18992 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18994 (defun org-paste-special (arg)
18995 "Paste rectangular region into table, or past subtree relative to level.
18996 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18997 See the individual commands for more information."
18998 (interactive "P")
18999 (if (org-at-table-p)
19000 (org-table-paste-rectangle)
19001 (org-paste-subtree arg)))
19003 (defun org-edit-special (&optional arg)
19004 "Call a special editor for the stuff at point.
19005 When at a table, call the formula editor with `org-table-edit-formulas'.
19006 When at the first line of an src example, call `org-edit-src-code'.
19007 When in an #+include line, visit the include file. Otherwise call
19008 `ffap' to visit the file at point."
19009 (interactive)
19010 ;; possibly prep session before editing source
19011 (when arg
19012 (let* ((info (org-babel-get-src-block-info))
19013 (lang (nth 0 info))
19014 (params (nth 2 info))
19015 (session (cdr (assoc :session params))))
19016 (when (and info session) ;; we are in a source-code block with a session
19017 (funcall
19018 (intern (concat "org-babel-prep-session:" lang)) session params))))
19019 (cond ;; proceed with `org-edit-special'
19020 ((save-excursion
19021 (beginning-of-line 1)
19022 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19023 (find-file (org-trim (match-string 1))))
19024 ((org-edit-src-code))
19025 ((org-edit-fixed-width-region))
19026 ((org-at-table.el-p)
19027 (org-edit-src-code))
19028 ((or (org-at-table-p)
19029 (save-excursion
19030 (beginning-of-line 1)
19031 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19032 (call-interactively 'org-table-edit-formulas))
19033 (t (call-interactively 'ffap))))
19035 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19036 (defun org-ctrl-c-ctrl-c (&optional arg)
19037 "Set tags in headline, or update according to changed information at point.
19039 This command does many different things, depending on context:
19041 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19042 this is what we do.
19044 - If the cursor is on a statistics cookie, update it.
19046 - If the cursor is in a headline, prompt for tags and insert them
19047 into the current line, aligned to `org-tags-column'. When called
19048 with prefix arg, realign all tags in the current buffer.
19050 - If the cursor is in one of the special #+KEYWORD lines, this
19051 triggers scanning the buffer for these lines and updating the
19052 information.
19054 - If the cursor is inside a table, realign the table. This command
19055 works even if the automatic table editor has been turned off.
19057 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19058 the entire table.
19060 - If the cursor is at a footnote reference or definition, jump to
19061 the corresponding definition or references, respectively.
19063 - If the cursor is a the beginning of a dynamic block, update it.
19065 - If the current buffer is a capture buffer, close note and file it.
19067 - If the cursor is on a <<<target>>>, update radio targets and
19068 corresponding links in this buffer.
19070 - If the cursor is on a numbered item in a plain list, renumber the
19071 ordered list.
19073 - If the cursor is on a checkbox, toggle it.
19075 - If the cursor is on a code block, evaluate it. The variable
19076 `org-confirm-babel-evaluate' can be used to control prompting
19077 before code block evaluation, by default every code block
19078 evaluation requires confirmation. Code block evaluation can be
19079 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19080 (interactive "P")
19081 (let ((org-enable-table-editor t))
19082 (cond
19083 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19084 org-occur-highlights
19085 org-latex-fragment-image-overlays)
19086 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19087 (org-remove-occur-highlights)
19088 (org-remove-latex-fragment-image-overlays)
19089 (message "Temporary highlights/overlays removed from current buffer"))
19090 ((and (local-variable-p 'org-finish-function (current-buffer))
19091 (fboundp org-finish-function))
19092 (funcall org-finish-function))
19093 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19094 ((org-in-regexp org-ts-regexp-both)
19095 (org-timestamp-change 0 'day))
19096 ((or (looking-at org-property-start-re)
19097 (org-at-property-p))
19098 (call-interactively 'org-property-action))
19099 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19100 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19101 (or (org-at-heading-p) (org-at-item-p)))
19102 (call-interactively 'org-update-statistics-cookies))
19103 ((org-at-heading-p) (call-interactively 'org-set-tags))
19104 ((org-at-table.el-p)
19105 (message "Use C-c ' to edit table.el tables"))
19106 ((org-at-table-p)
19107 (org-table-maybe-eval-formula)
19108 (if arg
19109 (call-interactively 'org-table-recalculate)
19110 (org-table-maybe-recalculate-line))
19111 (call-interactively 'org-table-align)
19112 (orgtbl-send-table 'maybe))
19113 ((or (org-footnote-at-reference-p)
19114 (org-footnote-at-definition-p))
19115 (call-interactively 'org-footnote-action))
19116 ((org-at-item-checkbox-p)
19117 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19118 ;; list only if at top item.
19119 (let* ((cbox (match-string 1))
19120 (struct (org-list-struct))
19121 (old-struct (copy-tree struct))
19122 (parents (org-list-parents-alist struct))
19123 (orderedp (org-entry-get nil "ORDERED"))
19124 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19125 block-item)
19126 ;; Use a light version of `org-toggle-checkbox' to avoid
19127 ;; computing list structure twice.
19128 (let ((new-box (cond
19129 ((equal arg '(16)) "[-]")
19130 ((equal arg '(4)) nil)
19131 ((equal "[X]" cbox) "[ ]")
19132 (t "[X]"))))
19133 (if (and firstp arg)
19134 ;; If at first item of sub-list, remove check-box from
19135 ;; every item at the same level.
19136 (mapc
19137 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19138 (org-list-get-all-items
19139 (point-at-bol) struct (org-list-prevs-alist struct)))
19140 (org-list-set-checkbox (point-at-bol) struct new-box)))
19141 ;; Replicate `org-list-write-struct', while grabbing a return
19142 ;; value from `org-list-struct-fix-box'.
19143 (org-list-struct-fix-ind struct parents 2)
19144 (org-list-struct-fix-item-end struct)
19145 (let ((prevs (org-list-prevs-alist struct)))
19146 (org-list-struct-fix-bul struct prevs)
19147 (org-list-struct-fix-ind struct parents)
19148 (setq block-item
19149 (org-list-struct-fix-box struct parents prevs orderedp)))
19150 (org-list-struct-apply-struct struct old-struct)
19151 (org-update-checkbox-count-maybe)
19152 (when block-item
19153 (message
19154 "Checkboxes were removed due to unchecked box at line %d"
19155 (org-current-line block-item)))
19156 (when firstp (org-list-send-list 'maybe))))
19157 ((org-at-item-p)
19158 ;; Cursor at an item: repair list. Do checkbox related actions
19159 ;; only if function was called with an argument. Send list only
19160 ;; if at top item.
19161 (let* ((struct (org-list-struct))
19162 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19163 old-struct)
19164 (when arg
19165 (setq old-struct (copy-tree struct))
19166 (if firstp
19167 ;; If at first item of sub-list, add check-box to every
19168 ;; item at the same level.
19169 (mapc
19170 (lambda (pos)
19171 (unless (org-list-get-checkbox pos struct)
19172 (org-list-set-checkbox pos struct "[ ]")))
19173 (org-list-get-all-items
19174 (point-at-bol) struct (org-list-prevs-alist struct)))
19175 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19176 (org-list-write-struct
19177 struct (org-list-parents-alist struct) old-struct)
19178 (when arg (org-update-checkbox-count-maybe))
19179 (when firstp (org-list-send-list 'maybe))))
19180 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19181 ;; Dynamic block
19182 (beginning-of-line 1)
19183 (save-excursion (org-update-dblock)))
19184 ((save-excursion
19185 (let ((case-fold-search t))
19186 (beginning-of-line 1)
19187 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19188 (cond
19189 ((or (equal (match-string 1) "TBLFM")
19190 (equal (match-string 1) "tblfm"))
19191 ;; Recalculate the table before this line
19192 (save-excursion
19193 (beginning-of-line 1)
19194 (skip-chars-backward " \r\n\t")
19195 (if (org-at-table-p)
19196 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19198 (let ((org-inhibit-startup-visibility-stuff t)
19199 (org-startup-align-all-tables nil))
19200 (when (boundp 'org-table-coordinate-overlays)
19201 (mapc 'delete-overlay org-table-coordinate-overlays)
19202 (setq org-table-coordinate-overlays nil))
19203 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19204 (message "Local setup has been refreshed"))))
19205 ((org-clock-update-time-maybe))
19207 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19208 (error "C-c C-c can do nothing useful at this location"))))))
19210 (defun org-mode-restart ()
19211 "Restart Org-mode, to scan again for special lines.
19212 Also updates the keyword regular expressions."
19213 (interactive)
19214 (org-mode)
19215 (message "Org-mode restarted"))
19217 (defun org-kill-note-or-show-branches ()
19218 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19219 (interactive)
19220 (if (not org-finish-function)
19221 (progn
19222 (hide-subtree)
19223 (call-interactively 'show-branches))
19224 (let ((org-note-abort t))
19225 (funcall org-finish-function))))
19227 (defun org-return (&optional indent)
19228 "Goto next table row or insert a newline.
19229 Calls `org-table-next-row' or `newline', depending on context.
19230 See the individual commands for more information."
19231 (interactive)
19232 (let (org-ts-what)
19233 (cond
19234 ((or (bobp) (org-in-src-block-p))
19235 (if indent (newline-and-indent) (newline)))
19236 ((org-at-table-p)
19237 (org-table-justify-field-maybe)
19238 (call-interactively 'org-table-next-row))
19239 ;; when `newline-and-indent' is called within a list, make sure
19240 ;; text moved stays inside the item.
19241 ((and (org-in-item-p) indent)
19242 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19243 (progn
19244 (save-match-data (newline))
19245 (org-indent-line-to (length (match-string 0))))
19246 (let ((ind (org-get-indentation)))
19247 (newline)
19248 (if (org-looking-back org-list-end-re)
19249 (org-indent-line)
19250 (org-indent-line-to ind)))))
19251 ((and org-return-follows-link
19252 (org-at-timestamp-p t)
19253 (not (eq org-ts-what 'after)))
19254 (org-follow-timestamp-link))
19255 ((and org-return-follows-link
19256 (let ((tprop (get-text-property (point) 'face)))
19257 (or (eq tprop 'org-link)
19258 (and (listp tprop) (memq 'org-link tprop)))))
19259 (call-interactively 'org-open-at-point))
19260 ((and (org-at-heading-p)
19261 (looking-at
19262 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19263 (org-show-entry)
19264 (end-of-line 1)
19265 (newline))
19266 (t (if indent (newline-and-indent) (newline))))))
19268 (defun org-return-indent ()
19269 "Goto next table row or insert a newline and indent.
19270 Calls `org-table-next-row' or `newline-and-indent', depending on
19271 context. See the individual commands for more information."
19272 (interactive)
19273 (org-return t))
19275 (defun org-ctrl-c-star ()
19276 "Compute table, or change heading status of lines.
19277 Calls `org-table-recalculate' or `org-toggle-heading',
19278 depending on context."
19279 (interactive)
19280 (cond
19281 ((org-at-table-p)
19282 (call-interactively 'org-table-recalculate))
19284 ;; Convert all lines in region to list items
19285 (call-interactively 'org-toggle-heading))))
19287 (defun org-ctrl-c-minus ()
19288 "Insert separator line in table or modify bullet status of line.
19289 Also turns a plain line or a region of lines into list items.
19290 Calls `org-table-insert-hline', `org-toggle-item', or
19291 `org-cycle-list-bullet', depending on context."
19292 (interactive)
19293 (cond
19294 ((org-at-table-p)
19295 (call-interactively 'org-table-insert-hline))
19296 ((org-region-active-p)
19297 (call-interactively 'org-toggle-item))
19298 ((org-in-item-p)
19299 (call-interactively 'org-cycle-list-bullet))
19301 (call-interactively 'org-toggle-item))))
19303 (defun org-toggle-item (arg)
19304 "Convert headings or normal lines to items, items to normal lines.
19305 If there is no active region, only the current line is considered.
19307 If the first non blank line in the region is an headline, convert
19308 all headlines to items, shifting text accordingly.
19310 If it is an item, convert all items to normal lines.
19312 If it is normal text, change region into an item. With a prefix
19313 argument ARG, change each line in region into an item."
19314 (interactive "P")
19315 (let ((shift-text
19316 (function
19317 ;; Shift text in current section to IND, from point to END.
19318 ;; The function leaves point to END line.
19319 (lambda (ind end)
19320 (let ((min-i 1000) (end (copy-marker end)))
19321 ;; First determine the minimum indentation (MIN-I) of
19322 ;; the text.
19323 (save-excursion
19324 (catch 'exit
19325 (while (< (point) end)
19326 (let ((i (org-get-indentation)))
19327 (cond
19328 ;; Skip blank lines and inline tasks.
19329 ((looking-at "^[ \t]*$"))
19330 ((looking-at org-outline-regexp-bol))
19331 ;; We can't find less than 0 indentation.
19332 ((zerop i) (throw 'exit (setq min-i 0)))
19333 ((< i min-i) (setq min-i i))))
19334 (forward-line))))
19335 ;; Then indent each line so that a line indented to
19336 ;; MIN-I becomes indented to IND. Ignore blank lines
19337 ;; and inline tasks in the process.
19338 (let ((delta (- ind min-i)))
19339 (while (< (point) end)
19340 (unless (or (looking-at "^[ \t]*$")
19341 (looking-at org-outline-regexp-bol))
19342 (org-indent-line-to (+ (org-get-indentation) delta)))
19343 (forward-line)))))))
19344 (skip-blanks
19345 (function
19346 ;; Return beginning of first non-blank line, starting from
19347 ;; line at POS.
19348 (lambda (pos)
19349 (save-excursion
19350 (goto-char pos)
19351 (skip-chars-forward " \r\t\n")
19352 (point-at-bol)))))
19353 beg end)
19354 ;; Determine boundaries of changes.
19355 (if (org-region-active-p)
19356 (setq beg (funcall skip-blanks (region-beginning))
19357 end (copy-marker (region-end)))
19358 (setq beg (funcall skip-blanks (point-at-bol))
19359 end (copy-marker (point-at-eol))))
19360 ;; Depending on the starting line, choose an action on the text
19361 ;; between BEG and END.
19362 (org-with-limited-levels
19363 (save-excursion
19364 (goto-char beg)
19365 (cond
19366 ;; Case 1. Start at an item: de-itemize. Note that it only
19367 ;; happens when a region is active: `org-ctrl-c-minus'
19368 ;; would call `org-cycle-list-bullet' otherwise.
19369 ((org-at-item-p)
19370 (while (< (point) end)
19371 (when (org-at-item-p)
19372 (skip-chars-forward " \t")
19373 (delete-region (point) (match-end 0)))
19374 (forward-line)))
19375 ;; Case 2. Start at an heading: convert to items.
19376 ((org-at-heading-p)
19377 (let* ((bul (org-list-bullet-string "-"))
19378 (bul-len (length bul))
19379 ;; Indentation of the first heading. It should be
19380 ;; relative to the indentation of its parent, if any.
19381 (start-ind (save-excursion
19382 (cond
19383 ((not org-adapt-indentation) 0)
19384 ((not (outline-previous-heading)) 0)
19385 (t (length (match-string 0))))))
19386 ;; Level of first heading. Further headings will be
19387 ;; compared to it to determine hierarchy in the list.
19388 (ref-level (org-reduced-level (org-outline-level))))
19389 (while (< (point) end)
19390 (let* ((level (org-reduced-level (org-outline-level)))
19391 (delta (max 0 (- level ref-level))))
19392 ;; If current headline is less indented than the first
19393 ;; one, set it as reference, in order to preserve
19394 ;; subtrees.
19395 (when (< level ref-level) (setq ref-level level))
19396 (replace-match bul t t)
19397 (org-indent-line-to (+ start-ind (* delta bul-len)))
19398 ;; Ensure all text down to END (or SECTION-END) belongs
19399 ;; to the newly created item.
19400 (let ((section-end (save-excursion
19401 (or (outline-next-heading) (point)))))
19402 (forward-line)
19403 (funcall shift-text
19404 (+ start-ind (* (1+ delta) bul-len))
19405 (min end section-end)))))))
19406 ;; Case 3. Normal line with ARG: turn each non-item line into
19407 ;; an item.
19408 (arg
19409 (while (< (point) end)
19410 (unless (or (org-at-heading-p) (org-at-item-p))
19411 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19412 (replace-match
19413 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19414 (forward-line)))
19415 ;; Case 4. Normal line without ARG: make the first line of
19416 ;; region an item, and shift indentation of others
19417 ;; lines to set them as item's body.
19418 (t (let* ((bul (org-list-bullet-string "-"))
19419 (bul-len (length bul))
19420 (ref-ind (org-get-indentation)))
19421 (skip-chars-forward " \t")
19422 (insert bul)
19423 (forward-line)
19424 (while (< (point) end)
19425 ;; Ensure that lines less indented than first one
19426 ;; still get included in item body.
19427 (funcall shift-text
19428 (+ ref-ind bul-len)
19429 (min end (save-excursion (or (outline-next-heading)
19430 (point)))))
19431 (forward-line)))))))))
19433 (defun org-toggle-heading (&optional nstars)
19434 "Convert headings to normal text, or items or text to headings.
19435 If there is no active region, only the current line is considered.
19437 With a \\[universal-argument] prefix, convert the whole list at
19438 point into heading.
19440 In a region:
19442 - If the first non blank line is an headline, remove the stars
19443 from all headlines in the region.
19445 - If it is a normal line turn each and every normal line (i.e. not an
19446 heading or an item) in the region into a heading.
19448 - If it is a plain list item, turn all plain list items into headings.
19450 When converting a line into a heading, the number of stars is chosen
19451 such that the lines become children of the current entry. However,
19452 when a prefix argument is given, its value determines the number of
19453 stars to add."
19454 (interactive "P")
19455 (let ((skip-blanks
19456 (function
19457 ;; Return beginning of first non-blank line, starting from
19458 ;; line at POS.
19459 (lambda (pos)
19460 (save-excursion
19461 (goto-char pos)
19462 (while (org-at-comment-p) (forward-line))
19463 (skip-chars-forward " \r\t\n")
19464 (point-at-bol)))))
19465 beg end toggled)
19466 ;; Determine boundaries of changes. If a universal prefix has
19467 ;; been given, put the list in a region. If region ends at a bol,
19468 ;; do not consider the last line to be in the region.
19470 (when (and current-prefix-arg (org-at-item-p))
19471 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19472 (org-mark-element))
19474 (if (org-region-active-p)
19475 (setq beg (funcall skip-blanks (region-beginning))
19476 end (copy-marker (save-excursion
19477 (goto-char (region-end))
19478 (if (bolp) (point) (point-at-eol)))))
19479 (setq beg (funcall skip-blanks (point-at-bol))
19480 end (copy-marker (point-at-eol))))
19481 ;; Ensure inline tasks don't count as headings.
19482 (org-with-limited-levels
19483 (save-excursion
19484 (goto-char beg)
19485 (cond
19486 ;; Case 1. Started at an heading: de-star headings.
19487 ((org-at-heading-p)
19488 (while (< (point) end)
19489 (when (org-at-heading-p t)
19490 (looking-at org-outline-regexp) (replace-match "")
19491 (setq toggled t))
19492 (forward-line)))
19493 ;; Case 2. Started at an item: change items into headlines.
19494 ;; One star will be added by `org-list-to-subtree'.
19495 ((org-at-item-p)
19496 (let* ((stars (make-string
19497 (if nstars
19498 ;; subtract the star that will be added again by
19499 ;; `org-list-to-subtree'
19500 (1- (prefix-numeric-value current-prefix-arg))
19501 (or (org-current-level) 0))
19502 ?*))
19503 (add-stars
19504 (cond (nstars "") ; stars from prefix only
19505 ((equal stars "") "") ; before first heading
19506 (org-odd-levels-only "*") ; inside heading, odd
19507 (t "")))) ; inside heading, oddeven
19508 (while (< (point) end)
19509 (when (org-at-item-p)
19510 ;; Pay attention to cases when region ends before list.
19511 (let* ((struct (org-list-struct))
19512 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19513 (save-restriction
19514 (narrow-to-region (point) list-end)
19515 (insert
19516 (org-list-to-subtree
19517 (org-list-parse-list t)
19518 '(:istart (concat stars add-stars (funcall get-stars depth))
19519 :icount (concat stars add-stars (funcall get-stars depth)))))))
19520 (setq toggled t))
19521 (forward-line))))
19522 ;; Case 3. Started at normal text: make every line an heading,
19523 ;; skipping headlines and items.
19524 (t (let* ((stars (make-string
19525 (if nstars
19526 (prefix-numeric-value current-prefix-arg)
19527 (or (org-current-level) 0))
19528 ?*))
19529 (add-stars
19530 (cond (nstars "") ; stars from prefix only
19531 ((equal stars "") "*") ; before first heading
19532 (org-odd-levels-only "**") ; inside heading, odd
19533 (t "*"))) ; inside heading, oddeven
19534 (rpl (concat stars add-stars " ")))
19535 (while (< (point) end)
19536 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19537 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19538 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19539 (forward-line)))))))
19540 (unless toggled (message "Cannot toggle heading from here"))))
19542 (defun org-meta-return (&optional arg)
19543 "Insert a new heading or wrap a region in a table.
19544 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19545 See the individual commands for more information."
19546 (interactive "P")
19547 (cond
19548 ((run-hook-with-args-until-success 'org-metareturn-hook))
19549 ((or (org-at-drawer-p) (org-at-property-p))
19550 (newline-and-indent))
19551 ((org-at-table-p)
19552 (call-interactively 'org-table-wrap-region))
19553 (t (call-interactively 'org-insert-heading))))
19555 ;;; Menu entries
19557 ;; Define the Org-mode menus
19558 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19559 '("Tbl"
19560 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19561 ["Next Field" org-cycle (org-at-table-p)]
19562 ["Previous Field" org-shifttab (org-at-table-p)]
19563 ["Next Row" org-return (org-at-table-p)]
19564 "--"
19565 ["Blank Field" org-table-blank-field (org-at-table-p)]
19566 ["Edit Field" org-table-edit-field (org-at-table-p)]
19567 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19568 "--"
19569 ("Column"
19570 ["Move Column Left" org-metaleft (org-at-table-p)]
19571 ["Move Column Right" org-metaright (org-at-table-p)]
19572 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19573 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19574 ("Row"
19575 ["Move Row Up" org-metaup (org-at-table-p)]
19576 ["Move Row Down" org-metadown (org-at-table-p)]
19577 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19578 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19579 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19580 "--"
19581 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19582 ("Rectangle"
19583 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19584 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19585 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19586 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19587 "--"
19588 ("Calculate"
19589 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19590 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19591 ["Edit Formulas" org-edit-special (org-at-table-p)]
19592 "--"
19593 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19594 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19595 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19596 "--"
19597 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19598 "--"
19599 ["Sum Column/Rectangle" org-table-sum
19600 (or (org-at-table-p) (org-region-active-p))]
19601 ["Which Column?" org-table-current-column (org-at-table-p)])
19602 ["Debug Formulas"
19603 org-table-toggle-formula-debugger
19604 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19605 ["Show Col/Row Numbers"
19606 org-table-toggle-coordinate-overlays
19607 :style toggle
19608 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19609 "--"
19610 ["Create" org-table-create (and (not (org-at-table-p))
19611 org-enable-table-editor)]
19612 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19613 ["Import from File" org-table-import (not (org-at-table-p))]
19614 ["Export to File" org-table-export (org-at-table-p)]
19615 "--"
19616 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19618 (easy-menu-define org-org-menu org-mode-map "Org menu"
19619 '("Org"
19620 ("Show/Hide"
19621 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19622 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19623 ["Sparse Tree..." org-sparse-tree t]
19624 ["Reveal Context" org-reveal t]
19625 ["Show All" show-all t]
19626 "--"
19627 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19628 "--"
19629 ["New Heading" org-insert-heading t]
19630 ("Navigate Headings"
19631 ["Up" outline-up-heading t]
19632 ["Next" outline-next-visible-heading t]
19633 ["Previous" outline-previous-visible-heading t]
19634 ["Next Same Level" outline-forward-same-level t]
19635 ["Previous Same Level" outline-backward-same-level t]
19636 "--"
19637 ["Jump" org-goto t])
19638 ("Edit Structure"
19639 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19640 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19641 "--"
19642 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19643 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19644 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19645 "--"
19646 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19647 "--"
19648 ["Copy visible text" org-copy-visible t]
19649 "--"
19650 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19651 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19652 ["Demote Heading" org-metaright (not (org-at-table-p))]
19653 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19654 "--"
19655 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19656 "--"
19657 ["Convert to odd levels" org-convert-to-odd-levels t]
19658 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19659 ("Editing"
19660 ["Emphasis..." org-emphasize t]
19661 ["Edit Source Example" org-edit-special t]
19662 "--"
19663 ["Footnote new/jump" org-footnote-action t]
19664 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19665 ("Archive"
19666 ["Archive (default method)" org-archive-subtree-default t]
19667 "--"
19668 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19669 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19670 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19672 "--"
19673 ("Hyperlinks"
19674 ["Store Link (Global)" org-store-link t]
19675 ["Find existing link to here" org-occur-link-in-agenda-files t]
19676 ["Insert Link" org-insert-link t]
19677 ["Follow Link" org-open-at-point t]
19678 "--"
19679 ["Next link" org-next-link t]
19680 ["Previous link" org-previous-link t]
19681 "--"
19682 ["Descriptive Links"
19683 org-toggle-link-display
19684 :style radio
19685 :selected org-descriptive-links
19687 ["Literal Links"
19688 org-toggle-link-display
19689 :style radio
19690 :selected (not org-descriptive-links)])
19691 "--"
19692 ("TODO Lists"
19693 ["TODO/DONE/-" org-todo t]
19694 ("Select keyword"
19695 ["Next keyword" org-shiftright (org-at-heading-p)]
19696 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19697 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19698 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19699 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19700 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19701 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19702 "--"
19703 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19704 :selected org-enforce-todo-dependencies :style toggle :active t]
19705 "Settings for tree at point"
19706 ["Do Children sequentially" org-toggle-ordered-property :style radio
19707 :selected (org-entry-get nil "ORDERED")
19708 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19709 ["Do Children parallel" org-toggle-ordered-property :style radio
19710 :selected (not (org-entry-get nil "ORDERED"))
19711 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19712 "--"
19713 ["Set Priority" org-priority t]
19714 ["Priority Up" org-shiftup t]
19715 ["Priority Down" org-shiftdown t]
19716 "--"
19717 ["Get news from all feeds" org-feed-update-all t]
19718 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19719 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19720 ("TAGS and Properties"
19721 ["Set Tags" org-set-tags-command t]
19722 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19723 "--"
19724 ["Set property" org-set-property t]
19725 ["Column view of properties" org-columns t]
19726 ["Insert Column View DBlock" org-insert-columns-dblock t])
19727 ("Dates and Scheduling"
19728 ["Timestamp" org-time-stamp t]
19729 ["Timestamp (inactive)" org-time-stamp-inactive t]
19730 ("Change Date"
19731 ["1 Day Later" org-shiftright t]
19732 ["1 Day Earlier" org-shiftleft t]
19733 ["1 ... Later" org-shiftup t]
19734 ["1 ... Earlier" org-shiftdown t])
19735 ["Compute Time Range" org-evaluate-time-range t]
19736 ["Schedule Item" org-schedule t]
19737 ["Deadline" org-deadline t]
19738 "--"
19739 ["Custom time format" org-toggle-time-stamp-overlays
19740 :style radio :selected org-display-custom-times]
19741 "--"
19742 ["Goto Calendar" org-goto-calendar t]
19743 ["Date from Calendar" org-date-from-calendar t]
19744 "--"
19745 ["Start/Restart Timer" org-timer-start t]
19746 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19747 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19748 ["Insert Timer String" org-timer t]
19749 ["Insert Timer Item" org-timer-item t])
19750 ("Logging work"
19751 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19752 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19753 ["Clock out" org-clock-out t]
19754 ["Clock cancel" org-clock-cancel t]
19755 "--"
19756 ["Mark as default task" org-clock-mark-default-task t]
19757 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19758 ["Goto running clock" org-clock-goto t]
19759 "--"
19760 ["Display times" org-clock-display t]
19761 ["Create clock table" org-clock-report t]
19762 "--"
19763 ["Record DONE time"
19764 (progn (setq org-log-done (not org-log-done))
19765 (message "Switching to %s will %s record a timestamp"
19766 (car org-done-keywords)
19767 (if org-log-done "automatically" "not")))
19768 :style toggle :selected org-log-done])
19769 "--"
19770 ["Agenda Command..." org-agenda t]
19771 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19772 ("File List for Agenda")
19773 ("Special views current file"
19774 ["TODO Tree" org-show-todo-tree t]
19775 ["Check Deadlines" org-check-deadlines t]
19776 ["Timeline" org-timeline t]
19777 ["Tags/Property tree" org-match-sparse-tree t])
19778 "--"
19779 ["Export/Publish..." org-export t]
19780 ("LaTeX"
19781 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19782 :selected org-cdlatex-mode]
19783 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19784 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19785 ["Modify math symbol" org-cdlatex-math-modify
19786 (org-inside-LaTeX-fragment-p)]
19787 ["Insert citation" org-reftex-citation t]
19788 "--"
19789 ["Template for BEAMER" (progn (require 'org-beamer)
19790 (org-insert-beamer-options-template)) t])
19791 "--"
19792 ("MobileOrg"
19793 ["Push Files and Views" org-mobile-push t]
19794 ["Get Captured and Flagged" org-mobile-pull t]
19795 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19796 "--"
19797 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19798 "--"
19799 ("Documentation"
19800 ["Show Version" org-version t]
19801 ["Info Documentation" org-info t])
19802 ("Customize"
19803 ["Browse Org Group" org-customize t]
19804 "--"
19805 ["Expand This Menu" org-create-customize-menu
19806 (fboundp 'customize-menu-create)])
19807 ["Send bug report" org-submit-bug-report t]
19808 "--"
19809 ("Refresh/Reload"
19810 ["Refresh setup current buffer" org-mode-restart t]
19811 ["Reload Org (after update)" org-reload t]
19812 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19815 (defun org-info (&optional node)
19816 "Read documentation for Org-mode in the info system.
19817 With optional NODE, go directly to that node."
19818 (interactive)
19819 (info (format "(org)%s" (or node ""))))
19821 ;;;###autoload
19822 (defun org-submit-bug-report ()
19823 "Submit a bug report on Org-mode via mail.
19825 Don't hesitate to report any problems or inaccurate documentation.
19827 If you don't have setup sending mail from (X)Emacs, please copy the
19828 output buffer into your mail program, as it gives us important
19829 information about your Org-mode version and configuration."
19830 (interactive)
19831 (require 'reporter)
19832 (org-load-modules-maybe)
19833 (org-require-autoloaded-modules)
19834 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19835 (reporter-submit-bug-report
19836 "emacs-orgmode@gnu.org"
19837 (org-version nil 'full)
19838 (let (list)
19839 (save-window-excursion
19840 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19841 (delete-other-windows)
19842 (erase-buffer)
19843 (insert "You are about to submit a bug report to the Org-mode mailing list.
19845 We would like to add your full Org-mode and Outline configuration to the
19846 bug report. This greatly simplifies the work of the maintainer and
19847 other experts on the mailing list.
19849 HOWEVER, some variables you have customized may contain private
19850 information. The names of customers, colleagues, or friends, might
19851 appear in the form of file names, tags, todo states, or search strings.
19852 If you answer yes to the prompt, you might want to check and remove
19853 such private information before sending the email.")
19854 (add-text-properties (point-min) (point-max) '(face org-warning))
19855 (when (yes-or-no-p "Include your Org-mode configuration ")
19856 (mapatoms
19857 (lambda (v)
19858 (and (boundp v)
19859 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19860 (or (and (symbol-value v)
19861 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19862 (and
19863 (get v 'custom-type) (get v 'standard-value)
19864 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19865 (push v list)))))
19866 (kill-buffer (get-buffer "*Warn about privacy*"))
19867 list))
19868 nil nil
19869 "Remember to cover the basics, that is, what you expected to happen and
19870 what in fact did happen. You don't know how to make a good report? See
19872 http://orgmode.org/manual/Feedback.html#Feedback
19874 Your bug report will be posted to the Org-mode mailing list.
19875 ------------------------------------------------------------------------")
19876 (save-excursion
19877 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19878 (replace-match "\\1Bug: \\3 [\\2]")))))
19881 (defun org-install-agenda-files-menu ()
19882 (let ((bl (buffer-list)))
19883 (save-excursion
19884 (while bl
19885 (set-buffer (pop bl))
19886 (if (derived-mode-p 'org-mode) (setq bl nil)))
19887 (when (derived-mode-p 'org-mode)
19888 (easy-menu-change
19889 '("Org") "File List for Agenda"
19890 (append
19891 (list
19892 ["Edit File List" (org-edit-agenda-file-list) t]
19893 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19894 ["Remove Current File from List" org-remove-file t]
19895 ["Cycle through agenda files" org-cycle-agenda-files t]
19896 ["Occur in all agenda files" org-occur-in-agenda-files t]
19897 "--")
19898 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19900 ;;;; Documentation
19902 ;;;###autoload
19903 (defun org-require-autoloaded-modules ()
19904 (interactive)
19905 (mapc 'require
19906 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19907 org-docbook org-exp org-html org-icalendar
19908 org-id org-latex
19909 org-publish org-remember org-table
19910 org-timer org-xoxo)))
19912 ;;;###autoload
19913 (defun org-reload (&optional uncompiled)
19914 "Reload all org lisp files.
19915 With prefix arg UNCOMPILED, load the uncompiled versions."
19916 (interactive "P")
19917 (require 'find-func)
19918 (let* ((file-re "^org\\(-.*\\)?\\.el")
19919 (dir-org (file-name-directory (org-find-library-dir "org")))
19920 (dir-org-contrib (ignore-errors
19921 (file-name-directory
19922 (org-find-library-dir "org-contribdir"))))
19923 (babel-files
19924 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19925 (append (list nil "comint" "eval" "exp" "keys"
19926 "lob" "ref" "table" "tangle")
19927 (delq nil
19928 (mapcar
19929 (lambda (lang)
19930 (when (cdr lang) (symbol-name (car lang))))
19931 org-babel-load-languages)))))
19932 (files
19933 (append babel-files
19934 (and dir-org-contrib
19935 (directory-files dir-org-contrib t file-re))
19936 (directory-files dir-org t file-re)))
19937 (remove-re (concat (if (featurep 'xemacs)
19938 "org-colview" "org-colview-xemacs")
19939 "\\'")))
19940 (setq files (mapcar 'file-name-sans-extension files))
19941 (setq files (mapcar
19942 (lambda (x) (if (string-match remove-re x) nil x))
19943 files))
19944 (setq files (delq nil files))
19945 (mapc
19946 (lambda (f)
19947 (when (featurep (intern (file-name-nondirectory f)))
19948 (if (and (not uncompiled)
19949 (file-exists-p (concat f ".elc")))
19950 (load (concat f ".elc") nil nil 'nosuffix)
19951 (load (concat f ".el") nil nil 'nosuffix))))
19952 files)
19953 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19954 (org-version nil 'full 'message))
19956 ;;;###autoload
19957 (defun org-customize ()
19958 "Call the customize function with org as argument."
19959 (interactive)
19960 (org-load-modules-maybe)
19961 (org-require-autoloaded-modules)
19962 (customize-browse 'org))
19964 (defun org-create-customize-menu ()
19965 "Create a full customization menu for Org-mode, insert it into the menu."
19966 (interactive)
19967 (org-load-modules-maybe)
19968 (org-require-autoloaded-modules)
19969 (if (fboundp 'customize-menu-create)
19970 (progn
19971 (easy-menu-change
19972 '("Org") "Customize"
19973 `(["Browse Org group" org-customize t]
19974 "--"
19975 ,(customize-menu-create 'org)
19976 ["Set" Custom-set t]
19977 ["Save" Custom-save t]
19978 ["Reset to Current" Custom-reset-current t]
19979 ["Reset to Saved" Custom-reset-saved t]
19980 ["Reset to Standard Settings" Custom-reset-standard t]))
19981 (message "\"Org\"-menu now contains full customization menu"))
19982 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19984 ;;;; Miscellaneous stuff
19986 ;;; Generally useful functions
19988 (defun org-get-at-bol (property)
19989 "Get text property PROPERTY at beginning of line."
19990 (get-text-property (point-at-bol) property))
19992 (defun org-find-text-property-in-string (prop s)
19993 "Return the first non-nil value of property PROP in string S."
19994 (or (get-text-property 0 prop s)
19995 (get-text-property (or (next-single-property-change 0 prop s) 0)
19996 prop s)))
19998 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19999 "Display the given MESSAGE as a warning."
20000 (if (fboundp 'display-warning)
20001 (display-warning 'org message
20002 (if (featurep 'xemacs) 'warning :warning))
20003 (let ((buf (get-buffer-create "*Org warnings*")))
20004 (with-current-buffer buf
20005 (goto-char (point-max))
20006 (insert "Warning (Org): " message)
20007 (unless (bolp)
20008 (newline)))
20009 (display-buffer buf)
20010 (sit-for 0))))
20012 (defun org-eval (form)
20013 "Eval FORM and return result."
20014 (condition-case error
20015 (eval form)
20016 (error (format "%%![Error: %s]" error))))
20018 (defun org-in-clocktable-p ()
20019 "Check if the cursor is in a clocktable."
20020 (let ((pos (point)) start)
20021 (save-excursion
20022 (end-of-line 1)
20023 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20024 (setq start (match-beginning 0))
20025 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20026 (>= (match-end 0) pos)
20027 start))))
20029 (defun org-in-commented-line ()
20030 "Is point in a line starting with `#'?"
20031 (equal (char-after (point-at-bol)) ?#))
20033 (defun org-in-indented-comment-line ()
20034 "Is point in a line starting with `#' after some white space?"
20035 (save-excursion
20036 (save-match-data
20037 (goto-char (point-at-bol))
20038 (looking-at "[ \t]*#"))))
20040 (defun org-in-verbatim-emphasis ()
20041 (save-match-data
20042 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20044 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20045 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20046 (if (and marker (marker-buffer marker)
20047 (buffer-live-p (marker-buffer marker)))
20048 (progn
20049 (org-pop-to-buffer-same-window (marker-buffer marker))
20050 (if (or (> marker (point-max)) (< marker (point-min)))
20051 (widen))
20052 (goto-char marker)
20053 (org-show-context 'org-goto))
20054 (if bookmark
20055 (bookmark-jump bookmark)
20056 (error "Cannot find location"))))
20058 (defun org-quote-csv-field (s)
20059 "Quote field for inclusion in CSV material."
20060 (if (string-match "[\",]" s)
20061 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20064 (defun org-force-self-insert (N)
20065 "Needed to enforce self-insert under remapping."
20066 (interactive "p")
20067 (self-insert-command N))
20069 (defun org-string-width (s)
20070 "Compute width of string, ignoring invisible characters.
20071 This ignores character with invisibility property `org-link', and also
20072 characters with property `org-cwidth', because these will become invisible
20073 upon the next fontification round."
20074 (let (b l)
20075 (when (or (eq t buffer-invisibility-spec)
20076 (assq 'org-link buffer-invisibility-spec))
20077 (while (setq b (text-property-any 0 (length s)
20078 'invisible 'org-link s))
20079 (setq s (concat (substring s 0 b)
20080 (substring s (or (next-single-property-change
20081 b 'invisible s) (length s)))))))
20082 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20083 (setq s (concat (substring s 0 b)
20084 (substring s (or (next-single-property-change
20085 b 'org-cwidth s) (length s))))))
20086 (setq l (string-width s) b -1)
20087 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20088 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20091 (defun org-shorten-string (s maxlength)
20092 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20093 If the string is shorter or has length MAXLENGTH, just return the
20094 original string. If it is longer, the functions finds a space in the
20095 string, breaks this string off at that locations and adds three dots
20096 as ellipsis. Including the ellipsis, the string will not be longer
20097 than MAXLENGTH. If finding a good breaking point in the string does
20098 not work, the string is just chopped off in the middle of a word
20099 if necessary."
20100 (if (<= (length s) maxlength)
20102 (let* ((n (max (- maxlength 4) 1))
20103 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20104 (if (string-match re s)
20105 (concat (match-string 1 s) "...")
20106 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20108 (defun org-get-indentation (&optional line)
20109 "Get the indentation of the current line, interpreting tabs.
20110 When LINE is given, assume it represents a line and compute its indentation."
20111 (if line
20112 (if (string-match "^ *" (org-remove-tabs line))
20113 (match-end 0))
20114 (save-excursion
20115 (beginning-of-line 1)
20116 (skip-chars-forward " \t")
20117 (current-column))))
20119 (defun org-get-string-indentation (s)
20120 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20121 (let ((n -1) (i 0) (w tab-width) c)
20122 (catch 'exit
20123 (while (< (setq n (1+ n)) (length s))
20124 (setq c (aref s n))
20125 (cond ((= c ?\ ) (setq i (1+ i)))
20126 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20127 (t (throw 'exit t)))))
20130 (defun org-remove-tabs (s &optional width)
20131 "Replace tabulators in S with spaces.
20132 Assumes that s is a single line, starting in column 0."
20133 (setq width (or width tab-width))
20134 (while (string-match "\t" s)
20135 (setq s (replace-match
20136 (make-string
20137 (- (* width (/ (+ (match-beginning 0) width) width))
20138 (match-beginning 0)) ?\ )
20139 t t s)))
20142 (defun org-fix-indentation (line ind)
20143 "Fix indentation in LINE.
20144 IND is a cons cell with target and minimum indentation.
20145 If the current indentation in LINE is smaller than the minimum,
20146 leave it alone. If it is larger than ind, set it to the target."
20147 (let* ((l (org-remove-tabs line))
20148 (i (org-get-indentation l))
20149 (i1 (car ind)) (i2 (cdr ind)))
20150 (if (>= i i2) (setq l (substring line i2)))
20151 (if (> i1 0)
20152 (concat (make-string i1 ?\ ) l)
20153 l)))
20155 (defun org-remove-indentation (code &optional n)
20156 "Remove the maximum common indentation from the lines in CODE.
20157 N may optionally be the number of spaces to remove."
20158 (with-temp-buffer
20159 (insert code)
20160 (org-do-remove-indentation n)
20161 (buffer-string)))
20163 (defun org-do-remove-indentation (&optional n)
20164 "Remove the maximum common indentation from the buffer."
20165 (untabify (point-min) (point-max))
20166 (let ((min 10000) re)
20167 (if n
20168 (setq min n)
20169 (goto-char (point-min))
20170 (while (re-search-forward "^ *[^ \n]" nil t)
20171 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20172 (unless (or (= min 0) (= min 10000))
20173 (setq re (format "^ \\{%d\\}" min))
20174 (goto-char (point-min))
20175 (while (re-search-forward re nil t)
20176 (replace-match "")
20177 (end-of-line 1))
20178 min)))
20180 (defun org-fill-template (template alist)
20181 "Find each %key of ALIST in TEMPLATE and replace it."
20182 (let ((case-fold-search nil)
20183 entry key value)
20184 (setq alist (sort (copy-sequence alist)
20185 (lambda (a b) (< (length (car a)) (length (car b))))))
20186 (while (setq entry (pop alist))
20187 (setq template
20188 (replace-regexp-in-string
20189 (concat "%" (regexp-quote (car entry)))
20190 (or (cdr entry) "") template t t)))
20191 template))
20193 (defun org-base-buffer (buffer)
20194 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20195 (if (not buffer)
20196 buffer
20197 (or (buffer-base-buffer buffer)
20198 buffer)))
20200 (defun org-trim (s)
20201 "Remove whitespace at beginning and end of string."
20202 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20203 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20206 (defun org-wrap (string &optional width lines)
20207 "Wrap string to either a number of lines, or a width in characters.
20208 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20209 that costs. If there is a word longer than WIDTH, the text is actually
20210 wrapped to the length of that word.
20211 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20212 many lines, whatever width that takes.
20213 The return value is a list of lines, without newlines at the end."
20214 (let* ((words (org-split-string string "[ \t\n]+"))
20215 (maxword (apply 'max (mapcar 'org-string-width words)))
20216 w ll)
20217 (cond (width
20218 (org-do-wrap words (max maxword width)))
20219 (lines
20220 (setq w maxword)
20221 (setq ll (org-do-wrap words maxword))
20222 (if (<= (length ll) lines)
20224 (setq ll words)
20225 (while (> (length ll) lines)
20226 (setq w (1+ w))
20227 (setq ll (org-do-wrap words w)))
20228 ll))
20229 (t (error "Cannot wrap this")))))
20231 (defun org-do-wrap (words width)
20232 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20233 (let (lines line)
20234 (while words
20235 (setq line (pop words))
20236 (while (and words (< (+ (length line) (length (car words))) width))
20237 (setq line (concat line " " (pop words))))
20238 (setq lines (push line lines)))
20239 (nreverse lines)))
20241 (defun org-split-string (string &optional separators)
20242 "Splits STRING into substrings at SEPARATORS.
20243 No empty strings are returned if there are matches at the beginning
20244 and end of string."
20245 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20246 (start 0)
20247 notfirst
20248 (list nil))
20249 (while (and (string-match rexp string
20250 (if (and notfirst
20251 (= start (match-beginning 0))
20252 (< start (length string)))
20253 (1+ start) start))
20254 (< (match-beginning 0) (length string)))
20255 (setq notfirst t)
20256 (or (eq (match-beginning 0) 0)
20257 (and (eq (match-beginning 0) (match-end 0))
20258 (eq (match-beginning 0) start))
20259 (setq list
20260 (cons (substring string start (match-beginning 0))
20261 list)))
20262 (setq start (match-end 0)))
20263 (or (eq start (length string))
20264 (setq list
20265 (cons (substring string start)
20266 list)))
20267 (nreverse list)))
20269 (defun org-quote-vert (s)
20270 "Replace \"|\" with \"\\vert\"."
20271 (while (string-match "|" s)
20272 (setq s (replace-match "\\vert" t t s)))
20275 (defun org-uuidgen-p (s)
20276 "Is S an ID created by UUIDGEN?"
20277 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20279 (defun org-in-src-block-p nil
20280 "Whether point is in a code source block."
20281 (let (ov)
20282 (when (setq ov (overlays-at (point)))
20283 (memq 'org-block-background
20284 (overlay-properties
20285 (car ov))))))
20287 (defun org-context ()
20288 "Return a list of contexts of the current cursor position.
20289 If several contexts apply, all are returned.
20290 Each context entry is a list with a symbol naming the context, and
20291 two positions indicating start and end of the context. Possible
20292 contexts are:
20294 :headline anywhere in a headline
20295 :headline-stars on the leading stars in a headline
20296 :todo-keyword on a TODO keyword (including DONE) in a headline
20297 :tags on the TAGS in a headline
20298 :priority on the priority cookie in a headline
20299 :item on the first line of a plain list item
20300 :item-bullet on the bullet/number of a plain list item
20301 :checkbox on the checkbox in a plain list item
20302 :table in an org-mode table
20303 :table-special on a special filed in a table
20304 :table-table in a table.el table
20305 :clocktable in a clocktable
20306 :src-block in a source block
20307 :link on a hyperlink
20308 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20309 :target on a <<target>>
20310 :radio-target on a <<<radio-target>>>
20311 :latex-fragment on a LaTeX fragment
20312 :latex-preview on a LaTeX fragment with overlaid preview image
20314 This function expects the position to be visible because it uses font-lock
20315 faces as a help to recognize the following contexts: :table-special, :link,
20316 and :keyword."
20317 (let* ((f (get-text-property (point) 'face))
20318 (faces (if (listp f) f (list f)))
20319 (case-fold-search t)
20320 (p (point)) clist o)
20321 ;; First the large context
20322 (cond
20323 ((org-at-heading-p t)
20324 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20325 (when (progn
20326 (beginning-of-line 1)
20327 (looking-at org-todo-line-tags-regexp))
20328 (push (org-point-in-group p 1 :headline-stars) clist)
20329 (push (org-point-in-group p 2 :todo-keyword) clist)
20330 (push (org-point-in-group p 4 :tags) clist))
20331 (goto-char p)
20332 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20333 (if (looking-at "\\[#[A-Z0-9]\\]")
20334 (push (org-point-in-group p 0 :priority) clist)))
20336 ((org-at-item-p)
20337 (push (org-point-in-group p 2 :item-bullet) clist)
20338 (push (list :item (point-at-bol)
20339 (save-excursion (org-end-of-item) (point)))
20340 clist)
20341 (and (org-at-item-checkbox-p)
20342 (push (org-point-in-group p 0 :checkbox) clist)))
20344 ((org-at-table-p)
20345 (push (list :table (org-table-begin) (org-table-end)) clist)
20346 (if (memq 'org-formula faces)
20347 (push (list :table-special
20348 (previous-single-property-change p 'face)
20349 (next-single-property-change p 'face)) clist)))
20350 ((org-at-table-p 'any)
20351 (push (list :table-table) clist)))
20352 (goto-char p)
20354 ;; New the "medium" contexts: clocktables, source blocks
20355 (cond ((org-in-clocktable-p)
20356 (push (list :clocktable
20357 (and (or (looking-at "#\\+BEGIN: clocktable")
20358 (search-backward "#+BEGIN: clocktable" nil t))
20359 (match-beginning 0))
20360 (and (re-search-forward "#\\+END:?" nil t)
20361 (match-end 0))) clist))
20362 ((org-in-src-block-p)
20363 (push (list :src-block
20364 (and (or (looking-at "#\\+BEGIN_SRC")
20365 (search-backward "#+BEGIN_SRC" nil t))
20366 (match-beginning 0))
20367 (and (search-forward "#+END_SRC" nil t)
20368 (match-beginning 0))) clist)))
20369 (goto-char p)
20371 ;; Now the small context
20372 (cond
20373 ((org-at-timestamp-p)
20374 (push (org-point-in-group p 0 :timestamp) clist))
20375 ((memq 'org-link faces)
20376 (push (list :link
20377 (previous-single-property-change p 'face)
20378 (next-single-property-change p 'face)) clist))
20379 ((memq 'org-special-keyword faces)
20380 (push (list :keyword
20381 (previous-single-property-change p 'face)
20382 (next-single-property-change p 'face)) clist))
20383 ((org-at-target-p)
20384 (push (org-point-in-group p 0 :target) clist)
20385 (goto-char (1- (match-beginning 0)))
20386 (if (looking-at org-radio-target-regexp)
20387 (push (org-point-in-group p 0 :radio-target) clist))
20388 (goto-char p))
20389 ((setq o (car (delq nil
20390 (mapcar
20391 (lambda (x)
20392 (if (memq x org-latex-fragment-image-overlays) x))
20393 (overlays-at (point))))))
20394 (push (list :latex-fragment
20395 (overlay-start o) (overlay-end o)) clist)
20396 (push (list :latex-preview
20397 (overlay-start o) (overlay-end o)) clist))
20398 ((org-inside-LaTeX-fragment-p)
20399 ;; FIXME: positions wrong.
20400 (push (list :latex-fragment (point) (point)) clist)))
20402 (setq clist (nreverse (delq nil clist)))
20403 clist))
20405 ;; FIXME: Compare with at-regexp-p Do we need both?
20406 (defun org-in-regexp (re &optional nlines visually)
20407 "Check if point is inside a match of regexp.
20408 Normally only the current line is checked, but you can include NLINES extra
20409 lines both before and after point into the search.
20410 If VISUALLY is set, require that the cursor is not after the match but
20411 really on, so that the block visually is on the match."
20412 (catch 'exit
20413 (let ((pos (point))
20414 (eol (point-at-eol (+ 1 (or nlines 0))))
20415 (inc (if visually 1 0)))
20416 (save-excursion
20417 (beginning-of-line (- 1 (or nlines 0)))
20418 (while (re-search-forward re eol t)
20419 (if (and (<= (match-beginning 0) pos)
20420 (>= (+ inc (match-end 0)) pos))
20421 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20423 (defun org-at-regexp-p (regexp)
20424 "Is point inside a match of REGEXP in the current line?"
20425 (catch 'exit
20426 (save-excursion
20427 (let ((pos (point)) (end (point-at-eol)))
20428 (beginning-of-line 1)
20429 (while (re-search-forward regexp end t)
20430 (if (and (<= (match-beginning 0) pos)
20431 (>= (match-end 0) pos))
20432 (throw 'exit t)))
20433 nil))))
20435 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20436 "Non-nil when point is between matches of START-RE and END-RE.
20438 Also return a non-nil value when point is on one of the matches.
20440 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20441 buffer positions. Default values are the positions of headlines
20442 surrounding the point.
20444 The functions returns a cons cell whose car (resp. cdr) is the
20445 position before START-RE (resp. after END-RE)."
20446 (save-match-data
20447 (let ((pos (point))
20448 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20449 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20450 beg end)
20451 (save-excursion
20452 ;; Point is on a block when on START-RE or if START-RE can be
20453 ;; found before it...
20454 (and (or (org-at-regexp-p start-re)
20455 (re-search-backward start-re limit-up t))
20456 (setq beg (match-beginning 0))
20457 ;; ... and END-RE after it...
20458 (goto-char (match-end 0))
20459 (re-search-forward end-re limit-down t)
20460 (> (setq end (match-end 0)) pos)
20461 ;; ... without another START-RE in-between.
20462 (goto-char (match-beginning 0))
20463 (not (re-search-backward start-re (1+ beg) t))
20464 ;; Return value.
20465 (cons beg end))))))
20467 (defun org-in-block-p (names)
20468 "Non-nil when point belongs to a block whose name belongs to NAMES.
20470 NAMES is a list of strings containing names of blocks.
20472 Return first block name matched, or nil. Beware that in case of
20473 nested blocks, the returned name may not belong to the closest
20474 block from point."
20475 (save-match-data
20476 (catch 'exit
20477 (let ((case-fold-search t)
20478 (lim-up (save-excursion (outline-previous-heading)))
20479 (lim-down (save-excursion (outline-next-heading))))
20480 (mapc (lambda (name)
20481 (let ((n (regexp-quote name)))
20482 (when (org-between-regexps-p
20483 (concat "^[ \t]*#\\+begin_" n)
20484 (concat "^[ \t]*#\\+end_" n)
20485 lim-up lim-down)
20486 (throw 'exit n))))
20487 names))
20488 nil)))
20490 (defun org-occur-in-agenda-files (regexp &optional nlines)
20491 "Call `multi-occur' with buffers for all agenda files."
20492 (interactive "sOrg-files matching: \np")
20493 (let* ((files (org-agenda-files))
20494 (tnames (mapcar 'file-truename files))
20495 (extra org-agenda-text-search-extra-files)
20497 (when (eq (car extra) 'agenda-archives)
20498 (setq extra (cdr extra))
20499 (setq files (org-add-archive-files files)))
20500 (while (setq f (pop extra))
20501 (unless (member (file-truename f) tnames)
20502 (add-to-list 'files f 'append)
20503 (add-to-list 'tnames (file-truename f) 'append)))
20504 (multi-occur
20505 (mapcar (lambda (x)
20506 (with-current-buffer
20507 (or (get-file-buffer x) (find-file-noselect x))
20508 (widen)
20509 (current-buffer)))
20510 files)
20511 regexp)))
20513 (if (boundp 'occur-mode-find-occurrence-hook)
20514 ;; Emacs 23
20515 (add-hook 'occur-mode-find-occurrence-hook
20516 (lambda ()
20517 (when (derived-mode-p 'org-mode)
20518 (org-reveal))))
20519 ;; Emacs 22
20520 (defadvice occur-mode-goto-occurrence
20521 (after org-occur-reveal activate)
20522 (and (derived-mode-p 'org-mode) (org-reveal)))
20523 (defadvice occur-mode-goto-occurrence-other-window
20524 (after org-occur-reveal activate)
20525 (and (derived-mode-p 'org-mode) (org-reveal)))
20526 (defadvice occur-mode-display-occurrence
20527 (after org-occur-reveal activate)
20528 (when (derived-mode-p 'org-mode)
20529 (let ((pos (occur-mode-find-occurrence)))
20530 (with-current-buffer (marker-buffer pos)
20531 (save-excursion
20532 (goto-char pos)
20533 (org-reveal)))))))
20535 (defun org-occur-link-in-agenda-files ()
20536 "Create a link and search for it in the agendas.
20537 The link is not stored in `org-stored-links', it is just created
20538 for the search purpose."
20539 (interactive)
20540 (let ((link (condition-case nil
20541 (org-store-link nil)
20542 (error "Unable to create a link to here"))))
20543 (org-occur-in-agenda-files (regexp-quote link))))
20545 (defun org-uniquify (list)
20546 "Remove duplicate elements from LIST."
20547 (let (res)
20548 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20549 res))
20551 (defun org-delete-all (elts list)
20552 "Remove all elements in ELTS from LIST."
20553 (while elts
20554 (setq list (delete (pop elts) list)))
20555 list)
20557 (defun org-count (cl-item cl-seq)
20558 "Count the number of occurrences of ITEM in SEQ.
20559 Taken from `count' in cl-seq.el with all keyword arguments removed."
20560 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20561 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20562 (while (< cl-start cl-end)
20563 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20564 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20565 (setq cl-start (1+ cl-start)))
20566 cl-count))
20568 (defun org-remove-if (predicate seq)
20569 "Remove everything from SEQ that fulfills PREDICATE."
20570 (let (res e)
20571 (while seq
20572 (setq e (pop seq))
20573 (if (not (funcall predicate e)) (push e res)))
20574 (nreverse res)))
20576 (defun org-remove-if-not (predicate seq)
20577 "Remove everything from SEQ that does not fulfill PREDICATE."
20578 (let (res e)
20579 (while seq
20580 (setq e (pop seq))
20581 (if (funcall predicate e) (push e res)))
20582 (nreverse res)))
20584 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20585 "Reduce two-argument FUNCTION across SEQ.
20586 Taken from `reduce' in cl-seq.el with all keyword arguments but
20587 \":initial-value\" removed."
20588 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20589 (cadr (memq :initial-value cl-keys)))
20590 (cl-seq (pop cl-seq))
20591 (t (funcall cl-func)))))
20592 (while cl-seq
20593 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20594 cl-accum))
20596 (defun org-back-over-empty-lines ()
20597 "Move backwards over whitespace, to the beginning of the first empty line.
20598 Returns the number of empty lines passed."
20599 (let ((pos (point)))
20600 (if (cdr (assoc 'heading org-blank-before-new-entry))
20601 (skip-chars-backward " \t\n\r")
20602 (unless (eobp)
20603 (forward-line -1)))
20604 (beginning-of-line 2)
20605 (goto-char (min (point) pos))
20606 (count-lines (point) pos)))
20608 (defun org-skip-whitespace ()
20609 (skip-chars-forward " \t\n\r"))
20611 (defun org-point-in-group (point group &optional context)
20612 "Check if POINT is in match-group GROUP.
20613 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20614 match. If the match group does not exist or point is not inside it,
20615 return nil."
20616 (and (match-beginning group)
20617 (>= point (match-beginning group))
20618 (<= point (match-end group))
20619 (if context
20620 (list context (match-beginning group) (match-end group))
20621 t)))
20623 (defun org-switch-to-buffer-other-window (&rest args)
20624 "Switch to buffer in a second window on the current frame.
20625 In particular, do not allow pop-up frames.
20626 Returns the newly created buffer."
20627 (let (pop-up-frames special-display-buffer-names special-display-regexps
20628 special-display-function)
20629 (apply 'switch-to-buffer-other-window args)))
20631 (defun org-combine-plists (&rest plists)
20632 "Create a single property list from all plists in PLISTS.
20633 The process starts by copying the first list, and then setting properties
20634 from the other lists. Settings in the last list are the most significant
20635 ones and overrule settings in the other lists."
20636 (let ((rtn (copy-sequence (pop plists)))
20637 p v ls)
20638 (while plists
20639 (setq ls (pop plists))
20640 (while ls
20641 (setq p (pop ls) v (pop ls))
20642 (setq rtn (plist-put rtn p v))))
20643 rtn))
20645 (defun org-replace-escapes (string table)
20646 "Replace %-escapes in STRING with values in TABLE.
20647 TABLE is an association list with keys like \"%a\" and string values.
20648 The sequences in STRING may contain normal field width and padding information,
20649 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20650 so values can contain further %-escapes if they are define later in TABLE."
20651 (let ((tbl (copy-alist table))
20652 (case-fold-search nil)
20653 (pchg 0)
20654 e re rpl)
20655 (while (setq e (pop tbl))
20656 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20657 (when (and (cdr e) (string-match re (cdr e)))
20658 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20659 (safe "SREF"))
20660 (add-text-properties 0 3 (list 'sref sref) safe)
20661 (setcdr e (replace-match safe t t (cdr e)))))
20662 (while (string-match re string)
20663 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20664 (cdr e)))
20665 (setq string (replace-match rpl t t string))))
20666 (while (setq pchg (next-property-change pchg string))
20667 (let ((sref (get-text-property pchg 'sref string)))
20668 (when (and sref (string-match "SREF" string pchg))
20669 (setq string (replace-match sref t t string)))))
20670 string))
20672 (defun org-sublist (list start end)
20673 "Return a section of LIST, from START to END.
20674 Counting starts at 1."
20675 (let (rtn (c start))
20676 (setq list (nthcdr (1- start) list))
20677 (while (and list (<= c end))
20678 (push (pop list) rtn)
20679 (setq c (1+ c)))
20680 (nreverse rtn)))
20682 (defun org-find-base-buffer-visiting (file)
20683 "Like `find-buffer-visiting' but always return the base buffer and
20684 not an indirect buffer."
20685 (let ((buf (or (get-file-buffer file)
20686 (find-buffer-visiting file))))
20687 (if buf
20688 (or (buffer-base-buffer buf) buf)
20689 nil)))
20691 (defun org-image-file-name-regexp (&optional extensions)
20692 "Return regexp matching the file names of images.
20693 If EXTENSIONS is given, only match these."
20694 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20695 (image-file-name-regexp)
20696 (let ((image-file-name-extensions
20697 (or extensions
20698 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20699 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20700 (concat "\\."
20701 (regexp-opt (nconc (mapcar 'upcase
20702 image-file-name-extensions)
20703 image-file-name-extensions)
20705 "\\'"))))
20707 (defun org-file-image-p (file &optional extensions)
20708 "Return non-nil if FILE is an image."
20709 (save-match-data
20710 (string-match (org-image-file-name-regexp extensions) file)))
20712 (defun org-get-cursor-date ()
20713 "Return the date at cursor in as a time.
20714 This works in the calendar and in the agenda, anywhere else it just
20715 returns the current time."
20716 (let (date day defd)
20717 (cond
20718 ((eq major-mode 'calendar-mode)
20719 (setq date (calendar-cursor-to-date)
20720 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20721 ((eq major-mode 'org-agenda-mode)
20722 (setq day (get-text-property (point) 'day))
20723 (if day
20724 (setq date (calendar-gregorian-from-absolute day)
20725 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20726 (nth 2 date))))))
20727 (or defd (current-time))))
20729 (defvar org-agenda-action-marker (make-marker)
20730 "Marker pointing to the entry for the next agenda action.")
20732 (defun org-mark-entry-for-agenda-action ()
20733 "Mark the current entry as target of an agenda action.
20734 Agenda actions are actions executed from the agenda with the key `k',
20735 which make use of the date at the cursor."
20736 (interactive)
20737 (move-marker org-agenda-action-marker
20738 (save-excursion (org-back-to-heading t) (point))
20739 (current-buffer))
20740 (message
20741 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20743 (defun org-mark-subtree (&optional up)
20744 "Mark the current subtree.
20745 This puts point at the start of the current subtree, and mark at
20746 the end. If a numeric prefix UP is given, move up into the
20747 hierarchy of headlines by UP levels before marking the subtree."
20748 (interactive "P")
20749 (org-with-limited-levels
20750 (cond ((org-at-heading-p) (beginning-of-line))
20751 ((org-before-first-heading-p) (error "Not in a subtree"))
20752 (t (outline-previous-visible-heading 1))))
20753 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20754 (org-mark-element))
20756 ;;; Indentation
20758 (defun org-indent-line ()
20759 "Indent line depending on context."
20760 (interactive)
20761 (let* ((pos (point))
20762 (itemp (org-at-item-p))
20763 (case-fold-search t)
20764 (org-drawer-regexp (or org-drawer-regexp "\000"))
20765 (inline-task-p (and (featurep 'org-inlinetask)
20766 (org-inlinetask-in-task-p)))
20767 (inline-re (and inline-task-p
20768 (org-inlinetask-outline-regexp)))
20769 column)
20770 (if (and orgstruct-is-++ (eq pos (point)))
20771 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20772 (indent-according-to-mode))
20773 (beginning-of-line 1)
20774 (cond
20775 ;; Headings
20776 ((looking-at org-outline-regexp) (setq column 0))
20777 ;; Included files
20778 ((looking-at "#\\+include:") (setq column 0))
20779 ;; Footnote definition
20780 ((looking-at org-footnote-definition-re) (setq column 0))
20781 ;; Literal examples
20782 ((looking-at "[ \t]*:\\( \\|$\\)")
20783 (setq column (org-get-indentation))) ; do nothing
20784 ;; Lists
20785 ((ignore-errors (goto-char (org-in-item-p)))
20786 (setq column (if itemp
20787 (org-get-indentation)
20788 (org-list-item-body-column (point))))
20789 (goto-char pos))
20790 ;; Drawers
20791 ((and (looking-at "[ \t]*:END:")
20792 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20793 (save-excursion
20794 (goto-char (1- (match-beginning 1)))
20795 (setq column (current-column))))
20796 ;; Special blocks
20797 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20798 (save-excursion
20799 (re-search-backward
20800 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20801 (setq column (org-get-indentation (match-string 0))))
20802 ((and (not (looking-at "[ \t]*#\\+begin_"))
20803 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20804 (save-excursion
20805 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20806 (setq column
20807 (cond ((equal (downcase (match-string 1)) "src")
20808 ;; src blocks: let `org-edit-src-exit' handle them
20809 (org-get-indentation))
20810 ((equal (downcase (match-string 1)) "example")
20811 (max (org-get-indentation)
20812 (org-get-indentation (match-string 0))))
20814 (org-get-indentation (match-string 0))))))
20815 ;; This line has nothing special, look at the previous relevant
20816 ;; line to compute indentation
20818 (beginning-of-line 0)
20819 (while (and (not (bobp))
20820 (not (looking-at org-drawer-regexp))
20821 ;; When point started in an inline task, do not move
20822 ;; above task starting line.
20823 (not (and inline-task-p (looking-at inline-re)))
20824 ;; Skip drawers, blocks, empty lines, verbatim,
20825 ;; comments, tables, footnotes definitions, lists,
20826 ;; inline tasks.
20827 (or (and (looking-at "[ \t]*:END:")
20828 (re-search-backward org-drawer-regexp nil t))
20829 (and (looking-at "[ \t]*#\\+end_")
20830 (re-search-backward "[ \t]*#\\+begin_"nil t))
20831 (looking-at "[ \t]*[\n:#|]")
20832 (looking-at org-footnote-definition-re)
20833 (and (ignore-errors (goto-char (org-in-item-p)))
20834 (goto-char
20835 (org-list-get-top-point (org-list-struct))))
20836 (and (not inline-task-p)
20837 (featurep 'org-inlinetask)
20838 (org-inlinetask-in-task-p)
20839 (or (org-inlinetask-goto-beginning) t))))
20840 (beginning-of-line 0))
20841 (cond
20842 ;; There was an heading above.
20843 ((looking-at "\\*+[ \t]+")
20844 (if (not org-adapt-indentation)
20845 (setq column 0)
20846 (goto-char (match-end 0))
20847 (setq column (current-column))))
20848 ;; A drawer had started and is unfinished
20849 ((looking-at org-drawer-regexp)
20850 (goto-char (1- (match-beginning 1)))
20851 (setq column (current-column)))
20852 ;; Else, nothing noticeable found: get indentation and go on.
20853 (t (setq column (org-get-indentation))))))
20854 ;; Now apply indentation and move cursor accordingly
20855 (goto-char pos)
20856 (if (<= (current-column) (current-indentation))
20857 (org-indent-line-to column)
20858 (save-excursion (org-indent-line-to column)))
20859 ;; Special polishing for properties, see `org-property-format'
20860 (setq column (current-column))
20861 (beginning-of-line 1)
20862 (if (looking-at
20863 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20864 (replace-match (concat (match-string 1)
20865 (format org-property-format
20866 (match-string 2) (match-string 3)))
20867 t t))
20868 (org-move-to-column column))))
20870 (defun org-indent-drawer ()
20871 "Indent the drawer at point."
20872 (interactive)
20873 (let ((p (point))
20874 (e (and (save-excursion (re-search-forward ":END:" nil t))
20875 (match-end 0)))
20876 (folded
20877 (save-excursion
20878 (end-of-line)
20879 (when (overlays-at (point))
20880 (member 'invisible (overlay-properties
20881 (car (overlays-at (point)))))))))
20882 (when folded (org-cycle))
20883 (indent-for-tab-command)
20884 (while (and (move-beginning-of-line 2) (< (point) e))
20885 (indent-for-tab-command))
20886 (goto-char p)
20887 (when folded (org-cycle)))
20888 (message "Drawer at point indented"))
20890 (defun org-indent-block ()
20891 "Indent the block at point."
20892 (interactive)
20893 (let ((p (point))
20894 (case-fold-search t)
20895 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20896 (match-end 0)))
20897 (folded
20898 (save-excursion
20899 (end-of-line)
20900 (when (overlays-at (point))
20901 (member 'invisible (overlay-properties
20902 (car (overlays-at (point)))))))))
20903 (when folded (org-cycle))
20904 (indent-for-tab-command)
20905 (while (and (move-beginning-of-line 2) (< (point) e))
20906 (indent-for-tab-command))
20907 (goto-char p)
20908 (when folded (org-cycle)))
20909 (message "Block at point indented"))
20911 (defun org-indent-region (start end)
20912 "Indent region."
20913 (interactive "r")
20914 (save-excursion
20915 (let ((line-end (org-current-line end)))
20916 (goto-char start)
20917 (while (< (org-current-line) line-end)
20918 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20919 (t (call-interactively 'org-indent-line)))
20920 (move-beginning-of-line 2)))))
20923 ;;; Filling
20925 ;; We use our own fill-paragraph and auto-fill functions. These
20926 ;; functions will shadow `fill-prefix' (computed internally with
20927 ;; `org-fill-context-prefix') and pass through to
20928 ;; `fill-region-as-paragraph' and `do-auto-fill' as appropriate.
20930 (defun org-set-autofill-regexps ()
20931 (interactive)
20932 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20933 ;; Prevent auto-fill from inserting unwanted new items.
20934 (when (boundp 'fill-nobreak-predicate)
20935 (org-set-local
20936 'fill-nobreak-predicate
20937 (org-uniquify
20938 (append fill-nobreak-predicate
20939 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20940 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20941 (org-set-local 'align-mode-rules-list
20942 '((org-in-buffer-settings
20943 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20944 (modes . '(org-mode))))))
20946 (defun org-fill-item-nobreak-p ()
20947 "Non-nil when a line break at point would insert a new item."
20948 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20950 (defun org-fill-line-break-nobreak-p ()
20951 "Non-nil when a line break at point would create an Org line break."
20952 (save-excursion
20953 (skip-chars-backward "[ \t]")
20954 (skip-chars-backward "\\\\")
20955 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20957 (declare-function message-in-body-p "message" ())
20958 (defvar org-element--affiliated-re) ; From org-element.el
20959 (defun org-fill-context-prefix (p)
20960 "Compute a fill prefix for the line at point P.
20961 Return fill prefix, as a string, or nil if current line isn't
20962 meant to be filled."
20963 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20964 ;; FIXME: Prevent an error for users who forgot to make autoloads?
20965 ;; See also `org-fill-paragraph', which has the same.
20966 (require 'org-element)
20967 ;; FIXME: This is really the job of orgstruct++-mode
20968 (save-excursion
20969 (goto-char p)
20970 (beginning-of-line)
20971 (let* ((element (org-element-at-point))
20972 (type (org-element-type element))
20973 (post-affiliated
20974 (progn
20975 (goto-char (org-element-property :begin element))
20976 (while (looking-at org-element--affiliated-re) (forward-line))
20977 (point))))
20978 (unless (< p post-affiliated)
20979 (case type
20980 (comment (looking-at "[ \t]*# ?") (match-string 0))
20981 (footnote-definition "")
20982 ((item plain-list)
20983 (make-string (org-list-item-body-column
20984 (org-element-property :begin element))
20985 ? ))
20986 (paragraph
20987 ;; Fill prefix is usually the same as the current line,
20988 ;; except if the paragraph is at the beginning of an item.
20989 (let ((parent (org-element-property :parent element)))
20990 (cond ((eq (org-element-type parent) 'item)
20991 (make-string (org-list-item-body-column
20992 (org-element-property :begin parent))
20993 ? ))
20994 ((looking-at "\\s-+") (match-string 0))
20995 (t ""))))
20996 ((comment-block verse-block)
20997 ;; Only fill contents if P is within block boundaries.
20998 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20999 (forward-line)
21000 (point)))
21001 (cend (save-excursion
21002 (goto-char (org-element-property :end element))
21003 (skip-chars-backward " \r\t\n")
21004 (line-beginning-position))))
21005 (when (and (>= p cbeg) (< p cend))
21006 (if (looking-at "\\s-+") (match-string 0) ""))))))))))
21008 (defvar org-element-paragraph-separate) ; From org-element.el
21009 (defvar org-element-all-objects) ; From org-element.el
21010 (defun org-fill-paragraph (&optional justify)
21011 "Fill element at point, when applicable.
21013 This function only applies to comment blocks, comments, example
21014 blocks, paragraphs and verse blocks. Also, as a special case,
21015 re-align table when point is at one.
21017 If JUSTIFY is non-nil (interactively, with prefix argument),
21018 justify as well. If `sentence-end-double-space' is non-nil, then
21019 period followed by one space does not end a sentence, so don't
21020 break a line there. The variable `fill-column' controls the
21021 width for filling.
21023 For convenience, when point is at a plain list, an item or
21024 a footnote definition, try to fill the first paragraph within."
21025 ;; Falls back on message-fill-paragraph when necessary
21026 (interactive)
21027 (if (and (derived-mode-p 'message-mode)
21028 (or (not (message-in-body-p))
21029 (save-excursion (move-beginning-of-line 1)
21030 (looking-at "^>+ "))))
21031 (let ((fill-paragraph-function (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21032 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21033 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21034 (paragraph-separate (cadadr (assoc 'paragraph-separate org-fb-vars))))
21035 (fill-paragraph))
21036 (save-excursion
21037 ;; Move to end of line in order to get the first paragraph within
21038 ;; a plain list or a footnote definition.
21039 (end-of-line)
21040 (let ((element (org-element-at-point)))
21041 ;; First check if point is in a blank line at the beginning of the
21042 ;; buffer. In that case, ignore filling.
21043 (if (< (point) (org-element-property :begin element)) t
21044 (case (org-element-type element)
21045 ;; Align Org tables, leave table.el tables as-is.
21046 (table-row (org-table-align) t)
21047 (table
21048 (when (eq (org-element-property :type element) 'org)
21049 (org-table-align))
21051 ;; Elements that may contain `line-break' type objects.
21052 ((paragraph verse-block)
21053 (let ((beg (org-element-property :contents-begin element))
21054 (end (org-element-property :contents-end element))
21055 (type (org-element-type element)))
21056 ;; Do nothing if point is at an affiliated keyword or at
21057 ;; verse block markers.
21058 (if (or (< (point) beg)
21059 (and (eq type 'verse-block) (>= (point) end)))
21061 ;; At a verse block, first narrow to current "paragraph"
21062 ;; and set current element to that paragraph.
21063 (save-restriction
21064 (when (eq type 'verse-block)
21065 (narrow-to-region beg end)
21066 (save-excursion
21067 (let ((bol-pos (point-at-bol)))
21068 (re-search-backward
21069 org-element-paragraph-separate nil 'm)
21070 (unless (or (bobp) (= (point-at-bol) bol-pos))
21071 (forward-line))
21072 (setq element (org-element-paragraph-parser end)
21073 beg (org-element-property :contents-begin element)
21074 end (org-element-property
21075 :contents-end element)))))
21076 ;; Fill paragraph, taking line breaks into consideration.
21077 ;; For that, slice the paragraph using line breaks as
21078 ;; separators, and fill the parts in reverse order to
21079 ;; avoid messing with markers.
21080 (save-excursion
21081 (goto-char end)
21082 (mapc
21083 (lambda (pos)
21084 (let ((fill-prefix (org-fill-context-prefix pos)))
21085 (fill-region-as-paragraph pos (point) justify))
21086 (goto-char pos))
21087 ;; Find the list of ending positions for line breaks
21088 ;; in the current paragraph. Add paragraph beginning
21089 ;; to include first slice.
21090 (nreverse
21091 (cons beg
21092 (org-element-map
21093 (org-element--parse-objects
21094 beg end nil org-element-all-objects)
21095 'line-break
21096 (lambda (lb) (org-element-property :end lb))))))))
21097 t)))
21098 ;; Contents of `comment-block' type elements should be filled as
21099 ;; plain text.
21100 (comment-block
21101 (let ((fill-prefix (org-fill-context-prefix (point))))
21102 (save-excursion
21103 (fill-region-as-paragraph
21104 (progn
21105 (goto-char (org-element-property :begin element))
21106 (while (looking-at org-element--affiliated-re) (forward-line))
21107 (forward-line)
21108 (point))
21109 (progn
21110 (goto-char (org-element-property :end element))
21111 (skip-chars-backward " \r\t\n")
21112 (line-beginning-position))
21113 justify))) t)
21114 ;; Fill comments, indented or not.
21115 (comment
21116 (let ((fill-prefix (org-fill-context-prefix (point))))
21117 (save-excursion
21118 (fill-region-as-paragraph
21119 (progn
21120 (goto-char (org-element-property :begin element))
21121 (while (looking-at org-element--affiliated-re) (forward-line))
21122 (point))
21123 (progn
21124 (goto-char (org-element-property :end element))
21125 (skip-chars-backward " \r\t\n")
21126 (line-end-position))))))
21127 ;; Ignore every other element.
21128 (otherwise t)))))))
21130 (defun org-auto-fill-function ()
21131 "Auto-fill function."
21132 ;; Check if auto-filling is meaningful before computing fill prefix.
21133 (let ((fc (current-fill-column)))
21134 (when (and fc (> (current-column) fc))
21135 (let ((fill-prefix (org-fill-context-prefix (point))))
21136 (when fill-prefix (do-auto-fill))))))
21139 ;;; Comments
21141 ;; Since difference between comments and keywords is subtle, we cannot
21142 ;; trust `comment-only-p' when applying `comment-dwim'. Hence, both
21143 ;; `comment-region-function' and `uncomment-region-function' point to
21144 ;; `org-comment-or-uncomment-region', which can tell when region only
21145 ;; contains comments or not.
21147 (defun org-insert-comment ()
21148 "Insert an empty comment above current line.
21149 If the line is empty, insert comment at its beginning."
21150 (beginning-of-line)
21151 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21152 (org-indent-line)
21153 (insert "# "))
21155 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21156 "Comment or uncomment each non-blank line in the region.
21157 Uncomment each non-blank line between BEG and END if it only
21158 contains commented lines. Otherwise, comment them."
21159 (save-excursion
21160 (goto-char beg)
21161 (skip-chars-forward " \r\t\n" end)
21162 (beginning-of-line)
21163 (let ((uncommentp
21164 ;; UNCOMMENTP is non-nil when every non blank line between
21165 ;; BEG and END is a comment.
21166 (save-excursion
21167 (while (progn (and (not (eobp))
21168 (let ((element (org-element-at-point)))
21169 (and (eq (org-element-type element) 'comment)
21170 (goto-char (org-element-property
21171 :end element)))))))
21172 (>= (point) end)))
21173 ;; Remove or adding comment markers is going to change end
21174 ;; position so make it a marker.
21175 (end (copy-marker end)))
21176 (while (< (point) end)
21177 (unless (looking-at "\\s-*$")
21178 (if (not uncommentp) (progn (back-to-indentation) (insert "# "))
21179 ;; Only comments and blank lines in region: uncomment it.
21180 (looking-at "[ \t]*\\(# ?\\)")
21181 (replace-match "" nil nil nil 1)))
21182 (forward-line))
21183 (set-marker end nil))))
21186 ;;; Other stuff.
21188 (defun org-toggle-fixed-width-section (arg)
21189 "Toggle the fixed-width export.
21190 If there is no active region, the QUOTE keyword at the current headline is
21191 inserted or removed. When present, it causes the text between this headline
21192 and the next to be exported as fixed-width text, and unmodified.
21193 If there is an active region, this command adds or removes a colon as the
21194 first character of this line. If the first character of a line is a colon,
21195 this line is also exported in fixed-width font."
21196 (interactive "P")
21197 (let* ((cc 0)
21198 (regionp (org-region-active-p))
21199 (beg (if regionp (region-beginning) (point)))
21200 (end (if regionp (region-end)))
21201 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21202 (case-fold-search nil)
21203 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21204 off)
21205 (if regionp
21206 (save-excursion
21207 (goto-char beg)
21208 (setq cc (current-column))
21209 (beginning-of-line 1)
21210 (setq off (looking-at re))
21211 (while (> nlines 0)
21212 (setq nlines (1- nlines))
21213 (beginning-of-line 1)
21214 (cond
21215 (arg
21216 (org-move-to-column cc t)
21217 (insert ": \n")
21218 (forward-line -1))
21219 ((and off (looking-at re))
21220 (replace-match "" t t nil 1))
21221 ((not off) (org-move-to-column cc t) (insert ": ")))
21222 (forward-line 1)))
21223 (save-excursion
21224 (org-back-to-heading)
21225 (cond
21226 ((looking-at (format org-heading-keyword-regexp-format
21227 org-quote-string))
21228 (goto-char (match-end 1))
21229 (looking-at (concat " +" org-quote-string))
21230 (replace-match "" t t)
21231 (when (eolp) (insert " ")))
21232 ((looking-at org-outline-regexp)
21233 (goto-char (match-end 0))
21234 (insert org-quote-string " ")))))))
21236 (defun org-reftex-citation ()
21237 "Use reftex-citation to insert a citation into the buffer.
21238 This looks for a line like
21240 #+BIBLIOGRAPHY: foo plain option:-d
21242 and derives from it that foo.bib is the bibliography file relevant
21243 for this document. It then installs the necessary environment for RefTeX
21244 to work in this buffer and calls `reftex-citation' to insert a citation
21245 into the buffer.
21247 Export of such citations to both LaTeX and HTML is handled by the contributed
21248 package org-exp-bibtex by Taru Karttunen."
21249 (interactive)
21250 (let ((reftex-docstruct-symbol 'rds)
21251 (reftex-cite-format "\\cite{%l}")
21252 rds bib)
21253 (save-excursion
21254 (save-restriction
21255 (widen)
21256 (let ((case-fold-search t)
21257 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21258 (if (not (save-excursion
21259 (or (re-search-forward re nil t)
21260 (re-search-backward re nil t))))
21261 (error "No bibliography defined in file")
21262 (setq bib (concat (match-string 1) ".bib")
21263 rds (list (list 'bib bib)))))))
21264 (call-interactively 'reftex-citation)))
21266 ;;;; Functions extending outline functionality
21268 (defun org-beginning-of-line (&optional arg)
21269 "Go to the beginning of the current line. If that is invisible, continue
21270 to a visible line beginning. This makes the function of C-a more intuitive.
21271 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21272 first attempt, and only move to after the tags when the cursor is already
21273 beyond the end of the headline."
21274 (interactive "P")
21275 (let ((pos (point))
21276 (special (if (consp org-special-ctrl-a/e)
21277 (car org-special-ctrl-a/e)
21278 org-special-ctrl-a/e))
21279 refpos)
21280 (if (org-bound-and-true-p line-move-visual)
21281 (beginning-of-visual-line 1)
21282 (beginning-of-line 1))
21283 (if (and arg (fboundp 'move-beginning-of-line))
21284 (call-interactively 'move-beginning-of-line)
21285 (if (bobp)
21287 (backward-char 1)
21288 (if (org-truely-invisible-p)
21289 (while (and (not (bobp)) (org-truely-invisible-p))
21290 (backward-char 1)
21291 (beginning-of-line 1))
21292 (forward-char 1))))
21293 (when special
21294 (cond
21295 ((and (looking-at org-complex-heading-regexp)
21296 (= (char-after (match-end 1)) ?\ ))
21297 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21298 (point-at-eol)))
21299 (goto-char
21300 (if (eq special t)
21301 (cond ((> pos refpos) refpos)
21302 ((= pos (point)) refpos)
21303 (t (point)))
21304 (cond ((> pos (point)) (point))
21305 ((not (eq last-command this-command)) (point))
21306 (t refpos)))))
21307 ((org-at-item-p)
21308 ;; Being at an item and not looking at an the item means point
21309 ;; was previously moved to beginning of a visual line, which
21310 ;; doesn't contain the item. Therefore, do nothing special,
21311 ;; just stay here.
21312 (when (looking-at org-list-full-item-re)
21313 ;; Set special position at first white space character after
21314 ;; bullet, and check-box, if any.
21315 (let ((after-bullet
21316 (let ((box (match-end 3)))
21317 (if (not box) (match-end 1)
21318 (let ((after (char-after box)))
21319 (if (and after (= after ? )) (1+ box) box))))))
21320 ;; Special case: Move point to special position when
21321 ;; currently after it or at beginning of line.
21322 (if (eq special t)
21323 (when (or (> pos after-bullet) (= (point) pos))
21324 (goto-char after-bullet))
21325 ;; Reversed case: Move point to special position when
21326 ;; point was already at beginning of line and command is
21327 ;; repeated.
21328 (when (and (= (point) pos) (eq last-command this-command))
21329 (goto-char after-bullet))))))))
21330 (org-no-warnings
21331 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21333 (defun org-end-of-line (&optional arg)
21334 "Go to the end of the line.
21335 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21336 first attempt, and only move to after the tags when the cursor is already
21337 beyond the end of the headline."
21338 (interactive "P")
21339 (let ((special (if (consp org-special-ctrl-a/e)
21340 (cdr org-special-ctrl-a/e)
21341 org-special-ctrl-a/e)))
21342 (cond
21343 ((or (not special) arg
21344 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21345 (call-interactively
21346 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21347 ((fboundp 'move-end-of-line) 'move-end-of-line)
21348 (t 'end-of-line))))
21349 ((org-at-heading-p)
21350 (let ((pos (point)))
21351 (beginning-of-line 1)
21352 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21353 (if (eq special t)
21354 (if (or (< pos (match-beginning 1))
21355 (= pos (match-end 0)))
21356 (goto-char (match-beginning 1))
21357 (goto-char (match-end 0)))
21358 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21359 (goto-char (match-end 0))
21360 (goto-char (match-beginning 1))))
21361 (call-interactively (if (fboundp 'move-end-of-line)
21362 'move-end-of-line
21363 'end-of-line)))))
21364 ((org-at-drawer-p)
21365 (move-end-of-line 1)
21366 (when (overlays-at (1- (point))) (backward-char 1)))
21367 ;; At an item: Move before any hidden text.
21368 (t (call-interactively
21369 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21370 ((fboundp 'move-end-of-line) 'move-end-of-line)
21371 (t 'end-of-line)))))
21372 (org-no-warnings
21373 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21375 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21376 (define-key org-mode-map "\C-e" 'org-end-of-line)
21378 (defun org-backward-sentence (&optional arg)
21379 "Go to beginning of sentence, or beginning of table field.
21380 This will call `backward-sentence' or `org-table-beginning-of-field',
21381 depending on context."
21382 (interactive "P")
21383 (cond
21384 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21385 (t (call-interactively 'backward-sentence))))
21387 (defun org-forward-sentence (&optional arg)
21388 "Go to end of sentence, or end of table field.
21389 This will call `forward-sentence' or `org-table-end-of-field',
21390 depending on context."
21391 (interactive "P")
21392 (cond
21393 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21394 (t (call-interactively 'forward-sentence))))
21396 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21397 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21399 (defun org-kill-line (&optional arg)
21400 "Kill line, to tags or end of line."
21401 (interactive "P")
21402 (cond
21403 ((or (not org-special-ctrl-k)
21404 (bolp)
21405 (not (org-at-heading-p)))
21406 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21407 org-ctrl-k-protect-subtree)
21408 (if (or (eq org-ctrl-k-protect-subtree 'error)
21409 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21410 (error "C-k aborted - would kill hidden subtree")))
21411 (call-interactively
21412 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21413 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21414 (kill-region (point) (match-beginning 1))
21415 (org-set-tags nil t))
21416 (t (kill-region (point) (point-at-eol)))))
21418 (define-key org-mode-map "\C-k" 'org-kill-line)
21420 (defun org-yank (&optional arg)
21421 "Yank. If the kill is a subtree, treat it specially.
21422 This command will look at the current kill and check if is a single
21423 subtree, or a series of subtrees[1]. If it passes the test, and if the
21424 cursor is at the beginning of a line or after the stars of a currently
21425 empty headline, then the yank is handled specially. How exactly depends
21426 on the value of the following variables, both set by default.
21428 org-yank-folded-subtrees
21429 When set, the subtree(s) will be folded after insertion, but only
21430 if doing so would now swallow text after the yanked text.
21432 org-yank-adjusted-subtrees
21433 When set, the subtree will be promoted or demoted in order to
21434 fit into the local outline tree structure, which means that the level
21435 will be adjusted so that it becomes the smaller one of the two
21436 *visible* surrounding headings.
21438 Any prefix to this command will cause `yank' to be called directly with
21439 no special treatment. In particular, a simple \\[universal-argument] prefix \
21440 will just
21441 plainly yank the text as it is.
21443 \[1] The test checks if the first non-white line is a heading
21444 and if there are no other headings with fewer stars."
21445 (interactive "P")
21446 (org-yank-generic 'yank arg))
21448 (defun org-yank-generic (command arg)
21449 "Perform some yank-like command.
21451 This function implements the behavior described in the `org-yank'
21452 documentation. However, it has been generalized to work for any
21453 interactive command with similar behavior."
21455 ;; pretend to be command COMMAND
21456 (setq this-command command)
21458 (if arg
21459 (call-interactively command)
21461 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21462 (and (org-kill-is-subtree-p)
21463 (or (bolp)
21464 (and (looking-at "[ \t]*$")
21465 (string-match
21466 "\\`\\*+\\'"
21467 (buffer-substring (point-at-bol) (point)))))))
21468 swallowp)
21469 (cond
21470 ((and subtreep org-yank-folded-subtrees)
21471 (let ((beg (point))
21472 end)
21473 (if (and subtreep org-yank-adjusted-subtrees)
21474 (org-paste-subtree nil nil 'for-yank)
21475 (call-interactively command))
21477 (setq end (point))
21478 (goto-char beg)
21479 (when (and (bolp) subtreep
21480 (not (setq swallowp
21481 (org-yank-folding-would-swallow-text beg end))))
21482 (org-with-limited-levels
21483 (or (looking-at org-outline-regexp)
21484 (re-search-forward org-outline-regexp-bol end t))
21485 (while (and (< (point) end) (looking-at org-outline-regexp))
21486 (hide-subtree)
21487 (org-cycle-show-empty-lines 'folded)
21488 (condition-case nil
21489 (outline-forward-same-level 1)
21490 (error (goto-char end))))))
21491 (when swallowp
21492 (message
21493 "Inserted text not folded because that would swallow text"))
21495 (goto-char end)
21496 (skip-chars-forward " \t\n\r")
21497 (beginning-of-line 1)
21498 (push-mark beg 'nomsg)))
21499 ((and subtreep org-yank-adjusted-subtrees)
21500 (let ((beg (point-at-bol)))
21501 (org-paste-subtree nil nil 'for-yank)
21502 (push-mark beg 'nomsg)))
21504 (call-interactively command))))))
21506 (defun org-yank-folding-would-swallow-text (beg end)
21507 "Would hide-subtree at BEG swallow any text after END?"
21508 (let (level)
21509 (org-with-limited-levels
21510 (save-excursion
21511 (goto-char beg)
21512 (when (or (looking-at org-outline-regexp)
21513 (re-search-forward org-outline-regexp-bol end t))
21514 (setq level (org-outline-level)))
21515 (goto-char end)
21516 (skip-chars-forward " \t\r\n\v\f")
21517 (if (or (eobp)
21518 (and (bolp) (looking-at org-outline-regexp)
21519 (<= (org-outline-level) level)))
21520 nil ; Nothing would be swallowed
21521 t))))) ; something would swallow
21523 (define-key org-mode-map "\C-y" 'org-yank)
21525 (defun org-truely-invisible-p ()
21526 "Check if point is at a character currently not visible.
21527 This version does not only check the character property, but also
21528 `visible-mode'."
21529 ;; Early versions of noutline don't have `outline-invisible-p'.
21530 (if (org-bound-and-true-p visible-mode)
21532 (outline-invisible-p)))
21534 (defun org-invisible-p2 ()
21535 "Check if point is at a character currently not visible."
21536 (save-excursion
21537 (if (and (eolp) (not (bobp))) (backward-char 1))
21538 ;; Early versions of noutline don't have `outline-invisible-p'.
21539 (outline-invisible-p)))
21541 (defun org-back-to-heading (&optional invisible-ok)
21542 "Call `outline-back-to-heading', but provide a better error message."
21543 (condition-case nil
21544 (outline-back-to-heading invisible-ok)
21545 (error (error "Before first headline at position %d in buffer %s"
21546 (point) (current-buffer)))))
21548 (defun org-beginning-of-defun ()
21549 "Go to the beginning of the subtree, i.e. back to the heading."
21550 (org-back-to-heading))
21551 (defun org-end-of-defun ()
21552 "Go to the end of the subtree."
21553 (org-end-of-subtree nil t))
21555 (defun org-before-first-heading-p ()
21556 "Before first heading?"
21557 (save-excursion
21558 (end-of-line)
21559 (null (re-search-backward org-outline-regexp-bol nil t))))
21561 (defun org-at-heading-p (&optional ignored)
21562 (outline-on-heading-p t))
21563 ;; Compatibility alias with Org versions < 7.8.03
21564 (defalias 'org-on-heading-p 'org-at-heading-p)
21566 (defun org-at-comment-p nil
21567 "Is cursor in a line starting with a # character?"
21568 (save-excursion
21569 (beginning-of-line)
21570 (looking-at "^#")))
21572 (defun org-at-drawer-p nil
21573 "Is cursor at a drawer keyword?"
21574 (save-excursion
21575 (move-beginning-of-line 1)
21576 (looking-at org-drawer-regexp)))
21578 (defun org-at-block-p nil
21579 "Is cursor at a block keyword?"
21580 (save-excursion
21581 (move-beginning-of-line 1)
21582 (looking-at org-block-regexp)))
21584 (defun org-point-at-end-of-empty-headline ()
21585 "If point is at the end of an empty headline, return t, else nil.
21586 If the heading only contains a TODO keyword, it is still still considered
21587 empty."
21588 (and (looking-at "[ \t]*$")
21589 (when org-todo-line-regexp
21590 (save-excursion
21591 (beginning-of-line 1)
21592 (let ((case-fold-search nil))
21593 (looking-at org-todo-line-regexp)
21594 (string= (match-string 3) ""))))))
21596 (defun org-at-heading-or-item-p ()
21597 (or (org-at-heading-p) (org-at-item-p)))
21599 (defun org-at-target-p ()
21600 (or (org-in-regexp org-radio-target-regexp)
21601 (org-in-regexp org-target-regexp)))
21602 ;; Compatibility alias with Org versions < 7.8.03
21603 (defalias 'org-on-target-p 'org-at-target-p)
21605 (defun org-up-heading-all (arg)
21606 "Move to the heading line of which the present line is a subheading.
21607 This function considers both visible and invisible heading lines.
21608 With argument, move up ARG levels."
21609 (if (fboundp 'outline-up-heading-all)
21610 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21611 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21613 (defun org-up-heading-safe ()
21614 "Move to the heading line of which the present line is a subheading.
21615 This version will not throw an error. It will return the level of the
21616 headline found, or nil if no higher level is found.
21618 Also, this function will be a lot faster than `outline-up-heading',
21619 because it relies on stars being the outline starters. This can really
21620 make a significant difference in outlines with very many siblings."
21621 (let (start-level re)
21622 (org-back-to-heading t)
21623 (setq start-level (funcall outline-level))
21624 (if (equal start-level 1)
21626 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21627 (if (re-search-backward re nil t)
21628 (funcall outline-level)))))
21630 (defun org-first-sibling-p ()
21631 "Is this heading the first child of its parents?"
21632 (interactive)
21633 (let ((re org-outline-regexp-bol)
21634 level l)
21635 (unless (org-at-heading-p t)
21636 (error "Not at a heading"))
21637 (setq level (funcall outline-level))
21638 (save-excursion
21639 (if (not (re-search-backward re nil t))
21641 (setq l (funcall outline-level))
21642 (< l level)))))
21644 (defun org-goto-sibling (&optional previous)
21645 "Goto the next sibling, even if it is invisible.
21646 When PREVIOUS is set, go to the previous sibling instead. Returns t
21647 when a sibling was found. When none is found, return nil and don't
21648 move point."
21649 (let ((fun (if previous 're-search-backward 're-search-forward))
21650 (pos (point))
21651 (re org-outline-regexp-bol)
21652 level l)
21653 (when (condition-case nil (org-back-to-heading t) (error nil))
21654 (setq level (funcall outline-level))
21655 (catch 'exit
21656 (or previous (forward-char 1))
21657 (while (funcall fun re nil t)
21658 (setq l (funcall outline-level))
21659 (when (< l level) (goto-char pos) (throw 'exit nil))
21660 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21661 (goto-char pos)
21662 nil))))
21664 (defun org-show-siblings ()
21665 "Show all siblings of the current headline."
21666 (save-excursion
21667 (while (org-goto-sibling) (org-flag-heading nil)))
21668 (save-excursion
21669 (while (org-goto-sibling 'previous)
21670 (org-flag-heading nil))))
21672 (defun org-goto-first-child ()
21673 "Goto the first child, even if it is invisible.
21674 Return t when a child was found. Otherwise don't move point and
21675 return nil."
21676 (let (level (pos (point)) (re org-outline-regexp-bol))
21677 (when (condition-case nil (org-back-to-heading t) (error nil))
21678 (setq level (outline-level))
21679 (forward-char 1)
21680 (if (and (re-search-forward re nil t) (> (outline-level) level))
21681 (progn (goto-char (match-beginning 0)) t)
21682 (goto-char pos) nil))))
21684 (defun org-show-hidden-entry ()
21685 "Show an entry where even the heading is hidden."
21686 (save-excursion
21687 (org-show-entry)))
21689 (defun org-flag-heading (flag &optional entry)
21690 "Flag the current heading. FLAG non-nil means make invisible.
21691 When ENTRY is non-nil, show the entire entry."
21692 (save-excursion
21693 (org-back-to-heading t)
21694 ;; Check if we should show the entire entry
21695 (if entry
21696 (progn
21697 (org-show-entry)
21698 (save-excursion
21699 (and (outline-next-heading)
21700 (org-flag-heading nil))))
21701 (outline-flag-region (max (point-min) (1- (point)))
21702 (save-excursion (outline-end-of-heading) (point))
21703 flag))))
21705 (defun org-get-next-sibling ()
21706 "Move to next heading of the same level, and return point.
21707 If there is no such heading, return nil.
21708 This is like outline-next-sibling, but invisible headings are ok."
21709 (let ((level (funcall outline-level)))
21710 (outline-next-heading)
21711 (while (and (not (eobp)) (> (funcall outline-level) level))
21712 (outline-next-heading))
21713 (if (or (eobp) (< (funcall outline-level) level))
21715 (point))))
21717 (defun org-get-last-sibling ()
21718 "Move to previous heading of the same level, and return point.
21719 If there is no such heading, return nil."
21720 (let ((opoint (point))
21721 (level (funcall outline-level)))
21722 (outline-previous-heading)
21723 (when (and (/= (point) opoint) (outline-on-heading-p t))
21724 (while (and (> (funcall outline-level) level)
21725 (not (bobp)))
21726 (outline-previous-heading))
21727 (if (< (funcall outline-level) level)
21729 (point)))))
21731 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21732 ;; This contains an exact copy of the original function, but it uses
21733 ;; `org-back-to-heading', to make it work also in invisible
21734 ;; trees. And is uses an invisible-OK argument.
21735 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21736 ;; Furthermore, when used inside Org, finding the end of a large subtree
21737 ;; with many children and grandchildren etc, this can be much faster
21738 ;; than the outline version.
21739 (org-back-to-heading invisible-OK)
21740 (let ((first t)
21741 (level (funcall outline-level)))
21742 (if (and (derived-mode-p 'org-mode) (< level 1000))
21743 ;; A true heading (not a plain list item), in Org-mode
21744 ;; This means we can easily find the end by looking
21745 ;; only for the right number of stars. Using a regexp to do
21746 ;; this is so much faster than using a Lisp loop.
21747 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21748 (forward-char 1)
21749 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21750 ;; something else, do it the slow way
21751 (while (and (not (eobp))
21752 (or first (> (funcall outline-level) level)))
21753 (setq first nil)
21754 (outline-next-heading)))
21755 (unless to-heading
21756 (if (memq (preceding-char) '(?\n ?\^M))
21757 (progn
21758 ;; Go to end of line before heading
21759 (forward-char -1)
21760 (if (memq (preceding-char) '(?\n ?\^M))
21761 ;; leave blank line before heading
21762 (forward-char -1))))))
21763 (point))
21765 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21766 "Use Org version in org-mode, for dramatic speed-up."
21767 (if (derived-mode-p 'org-mode)
21768 (progn
21769 (org-end-of-subtree nil t)
21770 (unless (eobp) (backward-char 1)))
21771 ad-do-it))
21773 (defun org-end-of-meta-data-and-drawers ()
21774 "Jump to the first text after meta data and drawers in the current entry.
21775 This will move over empty lines, lines with planning time stamps,
21776 clocking lines, and drawers."
21777 (org-back-to-heading t)
21778 (let ((end (save-excursion (outline-next-heading) (point)))
21779 (re (concat "\\(" org-drawer-regexp "\\)"
21780 "\\|" "[ \t]*" org-keyword-time-regexp)))
21781 (forward-line 1)
21782 (while (re-search-forward re end t)
21783 (if (not (match-end 1))
21784 ;; empty or planning line
21785 (forward-line 1)
21786 ;; a drawer, find the end
21787 (re-search-forward "^[ \t]*:END:" end 'move)
21788 (forward-line 1)))
21789 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21790 (point)))
21792 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21793 "Move forward to the arg'th subheading at same level as this one.
21794 Stop at the first and last subheadings of a superior heading.
21795 Normally this only looks at visible headings, but when INVISIBLE-OK is
21796 non-nil it will also look at invisible ones."
21797 (interactive "p")
21798 (org-back-to-heading invisible-ok)
21799 (org-at-heading-p)
21800 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21801 (re (format "^\\*\\{1,%d\\} " level))
21803 (forward-char 1)
21804 (while (> arg 0)
21805 (while (and (re-search-forward re nil 'move)
21806 (setq l (- (match-end 0) (match-beginning 0) 1))
21807 (= l level)
21808 (not invisible-ok)
21809 (progn (backward-char 1) (outline-invisible-p)))
21810 (if (< l level) (setq arg 1)))
21811 (setq arg (1- arg)))
21812 (beginning-of-line 1)))
21814 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21815 "Move backward to the arg'th subheading at same level as this one.
21816 Stop at the first and last subheadings of a superior heading."
21817 (interactive "p")
21818 (org-back-to-heading)
21819 (org-at-heading-p)
21820 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21821 (re (format "^\\*\\{1,%d\\} " level))
21823 (while (> arg 0)
21824 (while (and (re-search-backward re nil 'move)
21825 (setq l (- (match-end 0) (match-beginning 0) 1))
21826 (= l level)
21827 (not invisible-ok)
21828 (outline-invisible-p))
21829 (if (< l level) (setq arg 1)))
21830 (setq arg (1- arg)))))
21832 ;;;###autoload
21833 (defun org-forward-element ()
21834 "Move forward by one element.
21835 Move to the next element at the same level, when possible."
21836 (interactive)
21837 (cond ((eobp) (error "Cannot move further down"))
21838 ((org-with-limited-levels (org-at-heading-p))
21839 (let ((origin (point)))
21840 (org-forward-heading-same-level 1)
21841 (unless (org-with-limited-levels (org-at-heading-p))
21842 (goto-char origin)
21843 (error "Cannot move further down"))))
21845 (let* ((elem (org-element-at-point))
21846 (end (org-element-property :end elem))
21847 (parent (org-element-property :parent elem)))
21848 (if (and parent (= (org-element-property :contents-end parent) end))
21849 (goto-char (org-element-property :end parent))
21850 (goto-char end))))))
21852 ;;;###autoload
21853 (defun org-backward-element ()
21854 "Move backward by one element.
21855 Move to the previous element at the same level, when possible."
21856 (interactive)
21857 (if (org-with-limited-levels (org-at-heading-p))
21858 ;; At an headline, move to the previous one, if any, or stay
21859 ;; here.
21860 (let ((origin (point)))
21861 (org-backward-heading-same-level 1)
21862 (unless (org-with-limited-levels (org-at-heading-p))
21863 (goto-char origin)
21864 (error "Cannot move further up")))
21865 (let* ((trail (org-element-at-point 'keep-trail))
21866 (elem (car trail))
21867 (prev-elem (nth 1 trail))
21868 (beg (org-element-property :begin elem)))
21869 (cond
21870 ;; Move to beginning of current element if point isn't there
21871 ;; already.
21872 ((/= (point) beg) (goto-char beg))
21873 ((not prev-elem) (error "Cannot move further up"))
21874 (t (goto-char (org-element-property :begin prev-elem)))))))
21876 ;;;###autoload
21877 (defun org-up-element ()
21878 "Move to upper element."
21879 (interactive)
21880 (if (org-with-limited-levels (org-at-heading-p))
21881 (unless (org-up-heading-safe) (error "No surrounding element"))
21882 (let* ((elem (org-element-at-point))
21883 (parent (org-element-property :parent elem)))
21884 (if parent (goto-char (org-element-property :begin parent))
21885 (if (org-with-limited-levels (org-before-first-heading-p))
21886 (error "No surrounding element")
21887 (org-with-limited-levels (org-back-to-heading)))))))
21889 ;;;###autoload
21890 (defvar org-element-greater-elements)
21891 (defun org-down-element ()
21892 "Move to inner element."
21893 (interactive)
21894 (let ((element (org-element-at-point)))
21895 (cond
21896 ((memq (org-element-type element) '(plain-list table))
21897 (goto-char (org-element-property :contents-begin element))
21898 (forward-char))
21899 ((memq (org-element-type element) org-element-greater-elements)
21900 ;; If contents are hidden, first disclose them.
21901 (when (org-element-property :hiddenp element) (org-cycle))
21902 (goto-char (or (org-element-property :contents-begin element)
21903 (error "No content for this element"))))
21904 (t (error "No inner element")))))
21906 ;;;###autoload
21907 (defun org-drag-element-backward ()
21908 "Move backward element at point."
21909 (interactive)
21910 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21911 (let* ((trail (org-element-at-point 'keep-trail))
21912 (elem (car trail))
21913 (prev-elem (nth 1 trail)))
21914 ;; Error out if no previous element or previous element is
21915 ;; a parent of the current one.
21916 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21917 (error "Cannot drag element backward")
21918 (let ((pos (point)))
21919 (org-element-swap-A-B prev-elem elem)
21920 (goto-char (+ (org-element-property :begin prev-elem)
21921 (- pos (org-element-property :begin elem)))))))))
21923 ;;;###autoload
21924 (defun org-drag-element-forward ()
21925 "Move forward element at point."
21926 (interactive)
21927 (let* ((pos (point))
21928 (elem (org-element-at-point)))
21929 (when (= (point-max) (org-element-property :end elem))
21930 (error "Cannot drag element forward"))
21931 (goto-char (org-element-property :end elem))
21932 (let ((next-elem (org-element-at-point)))
21933 (when (or (org-element-nested-p elem next-elem)
21934 (and (eq (org-element-type next-elem) 'headline)
21935 (not (eq (org-element-type elem) 'headline))))
21936 (goto-char pos)
21937 (error "Cannot drag element forward"))
21938 ;; Compute new position of point: it's shifted by NEXT-ELEM
21939 ;; body's length (without final blanks) and by the length of
21940 ;; blanks between ELEM and NEXT-ELEM.
21941 (let ((size-next (- (save-excursion
21942 (goto-char (org-element-property :end next-elem))
21943 (skip-chars-backward " \r\t\n")
21944 (forward-line)
21945 ;; Small correction if buffer doesn't end
21946 ;; with a newline character.
21947 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21948 (org-element-property :begin next-elem)))
21949 (size-blank (- (org-element-property :end elem)
21950 (save-excursion
21951 (goto-char (org-element-property :end elem))
21952 (skip-chars-backward " \r\t\n")
21953 (forward-line)
21954 (point)))))
21955 (org-element-swap-A-B elem next-elem)
21956 (goto-char (+ pos size-next size-blank))))))
21958 ;;;###autoload
21959 (defun org-mark-element ()
21960 "Put point at beginning of this element, mark at end.
21962 Interactively, if this command is repeated or (in Transient Mark
21963 mode) if the mark is active, it marks the next element after the
21964 ones already marked."
21965 (interactive)
21966 (let (deactivate-mark)
21967 (if (or (and (eq last-command this-command) (mark t))
21968 (and transient-mark-mode mark-active))
21969 (set-mark
21970 (save-excursion
21971 (goto-char (mark))
21972 (goto-char (org-element-property :end (org-element-at-point)))))
21973 (let ((element (org-element-at-point)))
21974 (end-of-line)
21975 (push-mark (org-element-property :end element) t t)
21976 (goto-char (org-element-property :begin element))))))
21978 ;;;###autoload
21979 (defun org-narrow-to-element ()
21980 "Narrow buffer to current element."
21981 (interactive)
21982 (let ((elem (org-element-at-point)))
21983 (cond
21984 ((eq (car elem) 'headline)
21985 (narrow-to-region
21986 (org-element-property :begin elem)
21987 (org-element-property :end elem)))
21988 ((memq (car elem) org-element-greater-elements)
21989 (narrow-to-region
21990 (org-element-property :contents-begin elem)
21991 (org-element-property :contents-end elem)))
21993 (narrow-to-region
21994 (org-element-property :begin elem)
21995 (org-element-property :end elem))))))
21997 ;;;###autoload
21998 (defun org-transpose-element ()
21999 "Transpose current and previous elements, keeping blank lines between.
22000 Point is moved after both elements."
22001 (interactive)
22002 (org-skip-whitespace)
22003 (let ((end (org-element-property :end (org-element-at-point))))
22004 (org-drag-element-backward)
22005 (goto-char end)))
22007 ;;;###autoload
22008 (defun org-unindent-buffer ()
22009 "Un-indent the visible part of the buffer.
22010 Relative indentation (between items, inside blocks, etc.) isn't
22011 modified."
22012 (interactive)
22013 (unless (eq major-mode 'org-mode)
22014 (error "Cannot un-indent a buffer not in Org mode"))
22015 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22016 unindent-tree ; For byte-compiler.
22017 (unindent-tree
22018 (function
22019 (lambda (contents)
22020 (mapc
22021 (lambda (element)
22022 (if (memq (org-element-type element) '(headline section))
22023 (funcall unindent-tree (org-element-contents element))
22024 (save-excursion
22025 (save-restriction
22026 (narrow-to-region
22027 (org-element-property :begin element)
22028 (org-element-property :end element))
22029 (org-do-remove-indentation)))))
22030 (reverse contents))))))
22031 (funcall unindent-tree (org-element-contents parse-tree))))
22033 (defun org-show-subtree ()
22034 "Show everything after this heading at deeper levels."
22035 (interactive)
22036 (outline-flag-region
22037 (point)
22038 (save-excursion
22039 (org-end-of-subtree t t))
22040 nil))
22042 (defun org-show-entry ()
22043 "Show the body directly following this heading.
22044 Show the heading too, if it is currently invisible."
22045 (interactive)
22046 (save-excursion
22047 (condition-case nil
22048 (progn
22049 (org-back-to-heading t)
22050 (outline-flag-region
22051 (max (point-min) (1- (point)))
22052 (save-excursion
22053 (if (re-search-forward
22054 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22055 (match-beginning 1)
22056 (point-max)))
22057 nil)
22058 (org-cycle-hide-drawers 'children))
22059 (error nil))))
22061 (defun org-make-options-regexp (kwds &optional extra)
22062 "Make a regular expression for keyword lines."
22063 (concat
22065 "#?[ \t]*\\+\\("
22066 (mapconcat 'regexp-quote kwds "\\|")
22067 (if extra (concat "\\|" extra))
22068 "\\):[ \t]*"
22069 "\\(.*\\)"))
22071 ;; Make isearch reveal the necessary context
22072 (defun org-isearch-end ()
22073 "Reveal context after isearch exits."
22074 (when isearch-success ; only if search was successful
22075 (if (featurep 'xemacs)
22076 ;; Under XEmacs, the hook is run in the correct place,
22077 ;; we directly show the context.
22078 (org-show-context 'isearch)
22079 ;; In Emacs the hook runs *before* restoring the overlays.
22080 ;; So we have to use a one-time post-command-hook to do this.
22081 ;; (Emacs 22 has a special variable, see function `org-mode')
22082 (unless (and (boundp 'isearch-mode-end-hook-quit)
22083 isearch-mode-end-hook-quit)
22084 ;; Only when the isearch was not quitted.
22085 (org-add-hook 'post-command-hook 'org-isearch-post-command
22086 'append 'local)))))
22088 (defun org-isearch-post-command ()
22089 "Remove self from hook, and show context."
22090 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22091 (org-show-context 'isearch))
22094 ;;;; Integration with and fixes for other packages
22096 ;;; Imenu support
22098 (defvar org-imenu-markers nil
22099 "All markers currently used by Imenu.")
22100 (make-variable-buffer-local 'org-imenu-markers)
22102 (defun org-imenu-new-marker (&optional pos)
22103 "Return a new marker for use by Imenu, and remember the marker."
22104 (let ((m (make-marker)))
22105 (move-marker m (or pos (point)))
22106 (push m org-imenu-markers)
22109 (defun org-imenu-get-tree ()
22110 "Produce the index for Imenu."
22111 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22112 (setq org-imenu-markers nil)
22113 (let* ((n org-imenu-depth)
22114 (re (concat "^" (org-get-limited-outline-regexp)))
22115 (subs (make-vector (1+ n) nil))
22116 (last-level 0)
22117 m level head)
22118 (save-excursion
22119 (save-restriction
22120 (widen)
22121 (goto-char (point-max))
22122 (while (re-search-backward re nil t)
22123 (setq level (org-reduced-level (funcall outline-level)))
22124 (when (and (<= level n)
22125 (looking-at org-complex-heading-regexp))
22126 (setq head (org-link-display-format
22127 (org-match-string-no-properties 4))
22128 m (org-imenu-new-marker))
22129 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22130 (if (>= level last-level)
22131 (push (cons head m) (aref subs level))
22132 (push (cons head (aref subs (1+ level))) (aref subs level))
22133 (loop for i from (1+ level) to n do (aset subs i nil)))
22134 (setq last-level level)))))
22135 (aref subs 1)))
22137 (eval-after-load "imenu"
22138 '(progn
22139 (add-hook 'imenu-after-jump-hook
22140 (lambda ()
22141 (if (derived-mode-p 'org-mode)
22142 (org-show-context 'org-goto))))))
22144 (defun org-link-display-format (link)
22145 "Replace a link with either the description, or the link target
22146 if no description is present"
22147 (save-match-data
22148 (if (string-match org-bracket-link-analytic-regexp link)
22149 (replace-match (if (match-end 5)
22150 (match-string 5 link)
22151 (concat (match-string 1 link)
22152 (match-string 3 link)))
22153 nil t link)
22154 link)))
22156 (defun org-toggle-link-display ()
22157 "Toggle the literal or descriptive display of links."
22158 (interactive)
22159 (if org-descriptive-links
22160 (progn (org-remove-from-invisibility-spec '(org-link))
22161 (org-restart-font-lock)
22162 (setq org-descriptive-links nil))
22163 (progn (add-to-invisibility-spec '(org-link))
22164 (org-restart-font-lock)
22165 (setq org-descriptive-links t))))
22167 ;; Speedbar support
22169 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22170 "Overlay marking the agenda restriction line in speedbar.")
22171 (overlay-put org-speedbar-restriction-lock-overlay
22172 'face 'org-agenda-restriction-lock)
22173 (overlay-put org-speedbar-restriction-lock-overlay
22174 'help-echo "Agendas are currently limited to this item.")
22175 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22177 (defun org-speedbar-set-agenda-restriction ()
22178 "Restrict future agenda commands to the location at point in speedbar.
22179 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22180 (interactive)
22181 (require 'org-agenda)
22182 (let (p m tp np dir txt)
22183 (cond
22184 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22185 'org-imenu t))
22186 (setq m (get-text-property p 'org-imenu-marker))
22187 (with-current-buffer (marker-buffer m)
22188 (goto-char m)
22189 (org-agenda-set-restriction-lock 'subtree)))
22190 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22191 'speedbar-function 'speedbar-find-file))
22192 (setq tp (previous-single-property-change
22193 (1+ p) 'speedbar-function)
22194 np (next-single-property-change
22195 tp 'speedbar-function)
22196 dir (speedbar-line-directory)
22197 txt (buffer-substring-no-properties (or tp (point-min))
22198 (or np (point-max))))
22199 (with-current-buffer (find-file-noselect
22200 (let ((default-directory dir))
22201 (expand-file-name txt)))
22202 (unless (derived-mode-p 'org-mode)
22203 (error "Cannot restrict to non-Org-mode file"))
22204 (org-agenda-set-restriction-lock 'file)))
22205 (t (error "Don't know how to restrict Org-mode's agenda")))
22206 (move-overlay org-speedbar-restriction-lock-overlay
22207 (point-at-bol) (point-at-eol))
22208 (setq current-prefix-arg nil)
22209 (org-agenda-maybe-redo)))
22211 (eval-after-load "speedbar"
22212 '(progn
22213 (speedbar-add-supported-extension ".org")
22214 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22215 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22216 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22217 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22218 (add-hook 'speedbar-visiting-tag-hook
22219 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22221 ;;; Fixes and Hacks for problems with other packages
22223 ;; Make flyspell not check words in links, to not mess up our keymap
22224 (defun org-mode-flyspell-verify ()
22225 "Don't let flyspell put overlays at active buttons, or on
22226 {todo,all-time,additional-option-like}-keywords."
22227 (let ((pos (max (1- (point)) (point-min)))
22228 (word (thing-at-point 'word)))
22229 (and (not (get-text-property pos 'keymap))
22230 (not (get-text-property pos 'org-no-flyspell))
22231 (not (member word org-todo-keywords-1))
22232 (not (member word org-all-time-keywords))
22233 (not (member word org-options-keywords))
22234 (not (member word (mapcar 'car org-startup-options)))
22235 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22237 (defun org-remove-flyspell-overlays-in (beg end)
22238 "Remove flyspell overlays in region."
22239 (and (org-bound-and-true-p flyspell-mode)
22240 (fboundp 'flyspell-delete-region-overlays)
22241 (flyspell-delete-region-overlays beg end))
22242 (add-text-properties beg end '(org-no-flyspell t)))
22244 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22245 (eval-after-load "bookmark"
22246 '(if (boundp 'bookmark-after-jump-hook)
22247 ;; We can use the hook
22248 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22249 ;; Hook not available, use advice
22250 (defadvice bookmark-jump (after org-make-visible activate)
22251 "Make the position visible."
22252 (org-bookmark-jump-unhide))))
22254 ;; Make sure saveplace shows the location if it was hidden
22255 (eval-after-load "saveplace"
22256 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22257 "Make the position visible."
22258 (org-bookmark-jump-unhide)))
22260 ;; Make sure ecb shows the location if it was hidden
22261 (eval-after-load "ecb"
22262 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22263 "Make hierarchy visible when jumping into location from ECB tree buffer."
22264 (if (derived-mode-p 'org-mode)
22265 (org-show-context))))
22267 (defun org-bookmark-jump-unhide ()
22268 "Unhide the current position, to show the bookmark location."
22269 (and (derived-mode-p 'org-mode)
22270 (or (outline-invisible-p)
22271 (save-excursion (goto-char (max (point-min) (1- (point))))
22272 (outline-invisible-p)))
22273 (org-show-context 'bookmark-jump)))
22275 ;; Make session.el ignore our circular variable
22276 (eval-after-load "session"
22277 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22279 ;;;; Experimental code
22281 (defun org-closed-in-range ()
22282 "Sparse tree of items closed in a certain time range.
22283 Still experimental, may disappear in the future."
22284 (interactive)
22285 ;; Get the time interval from the user.
22286 (let* ((time1 (org-float-time
22287 (org-read-date nil 'to-time nil "Starting date: ")))
22288 (time2 (org-float-time
22289 (org-read-date nil 'to-time nil "End date:")))
22290 ;; callback function
22291 (callback (lambda ()
22292 (let ((time
22293 (org-float-time
22294 (apply 'encode-time
22295 (org-parse-time-string
22296 (match-string 1))))))
22297 ;; check if time in interval
22298 (and (>= time time1) (<= time time2))))))
22299 ;; make tree, check each match with the callback
22300 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22302 ;;;; Finish up
22304 (provide 'org)
22306 (run-hooks 'org-load-hook)
22308 ;;; org.el ends here