* lisp/org.el (org-open-file): Print shell command used to open file
[org-mode.git] / lisp / org.el
blob3ac562276c86aeed121bed2a5c54cec80bc9e90d
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 (or (featurep 'xemacs)
1285 (version<= emacs-version "24.1"))
1286 "Non-nil means cluster self-insert commands for undo when possible.
1287 If this is set, then, like in the Emacs command loop, 20 consecutive
1288 characters will be undone together.
1289 This is configurable, because there is some impact on typing performance."
1290 :group 'org-table
1291 :type 'boolean)
1293 (defcustom org-table-tab-recognizes-table.el t
1294 "Non-nil means TAB will automatically notice a table.el table.
1295 When it sees such a table, it moves point into it and - if necessary -
1296 calls `table-recognize-table'."
1297 :group 'org-table-editing
1298 :type 'boolean)
1300 (defgroup org-link nil
1301 "Options concerning links in Org-mode."
1302 :tag "Org Link"
1303 :group 'org)
1305 (defvar org-link-abbrev-alist-local nil
1306 "Buffer-local version of `org-link-abbrev-alist', which see.
1307 The value of this is taken from the #+LINK lines.")
1308 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1310 (defcustom org-link-abbrev-alist nil
1311 "Alist of link abbreviations.
1312 The car of each element is a string, to be replaced at the start of a link.
1313 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1314 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1316 [[linkkey:tag][description]]
1318 The 'linkkey' must be a word word, starting with a letter, followed
1319 by letters, numbers, '-' or '_'.
1321 If REPLACE is a string, the tag will simply be appended to create the link.
1322 If the string contains \"%s\", the tag will be inserted there. If the string
1323 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1324 at that point (see the function `url-hexify-string'). If the string contains
1325 the specifier \"%(my-function)\", then the custom function `my-function' will
1326 be invoked: this function takes the tag as its only argument and must return
1327 a string.
1329 REPLACE may also be a function that will be called with the tag as the
1330 only argument to create the link, which should be returned as a string.
1332 See the manual for examples."
1333 :group 'org-link
1334 :type '(repeat
1335 (cons
1336 (string :tag "Protocol")
1337 (choice
1338 (string :tag "Format")
1339 (function)))))
1341 (defcustom org-descriptive-links t
1342 "Non-nil means Org will display descriptive links.
1343 E.g. [[http://orgmode.org][Org website]] will be displayed as
1344 \"Org Website\", hiding the link itself and just displaying its
1345 description. When set to `nil', Org will display the full links
1346 literally.
1348 You can interactively set the value of this variable by calling
1349 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1350 :group 'org-link
1351 :type 'boolean)
1353 (defcustom org-link-file-path-type 'adaptive
1354 "How the path name in file links should be stored.
1355 Valid values are:
1357 relative Relative to the current directory, i.e. the directory of the file
1358 into which the link is being inserted.
1359 absolute Absolute path, if possible with ~ for home directory.
1360 noabbrev Absolute path, no abbreviation of home directory.
1361 adaptive Use relative path for files in the current directory and sub-
1362 directories of it. For other files, use an absolute path."
1363 :group 'org-link
1364 :type '(choice
1365 (const relative)
1366 (const absolute)
1367 (const noabbrev)
1368 (const adaptive)))
1370 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1371 "Types of links that should be activated in Org-mode files.
1372 This is a list of symbols, each leading to the activation of a certain link
1373 type. In principle, it does not hurt to turn on most link types - there may
1374 be a small gain when turning off unused link types. The types are:
1376 bracket The recommended [[link][description]] or [[link]] links with hiding.
1377 angle Links in angular brackets that may contain whitespace like
1378 <bbdb:Carsten Dominik>.
1379 plain Plain links in normal text, no whitespace, like http://google.com.
1380 radio Text that is matched by a radio target, see manual for details.
1381 tag Tag settings in a headline (link to tag search).
1382 date Time stamps (link to calendar).
1383 footnote Footnote labels.
1385 Changing this variable requires a restart of Emacs to become effective."
1386 :group 'org-link
1387 :type '(set :greedy t
1388 (const :tag "Double bracket links" bracket)
1389 (const :tag "Angular bracket links" angle)
1390 (const :tag "Plain text links" plain)
1391 (const :tag "Radio target matches" radio)
1392 (const :tag "Tags" tag)
1393 (const :tag "Timestamps" date)
1394 (const :tag "Footnotes" footnote)))
1396 (defcustom org-make-link-description-function nil
1397 "Function to use to generate link descriptions from links.
1398 If nil the link location will be used. This function must take
1399 two parameters; the first is the link and the second the
1400 description `org-insert-link' has generated, and should return the
1401 description to use."
1402 :group 'org-link
1403 :type 'function)
1405 (defgroup org-link-store nil
1406 "Options concerning storing links in Org-mode."
1407 :tag "Org Store Link"
1408 :group 'org-link)
1410 (defcustom org-url-hexify-p t
1411 "When non-nil, hexify URL when creating a link."
1412 :type 'boolean
1413 ;; :version "24.3"
1414 :group 'org-link-store)
1416 (defcustom org-email-link-description-format "Email %c: %.30s"
1417 "Format of the description part of a link to an email or usenet message.
1418 The following %-escapes will be replaced by corresponding information:
1420 %F full \"From\" field
1421 %f name, taken from \"From\" field, address if no name
1422 %T full \"To\" field
1423 %t first name in \"To\" field, address if no name
1424 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1425 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1426 %s subject
1427 %d date
1428 %m message-id.
1430 You may use normal field width specification between the % and the letter.
1431 This is for example useful to limit the length of the subject.
1433 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1434 :group 'org-link-store
1435 :type 'string)
1437 (defcustom org-from-is-user-regexp
1438 (let (r1 r2)
1439 (when (and user-mail-address (not (string= user-mail-address "")))
1440 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1441 (when (and user-full-name (not (string= user-full-name "")))
1442 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1443 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1444 "Regexp matched against the \"From:\" header of an email or usenet message.
1445 It should match if the message is from the user him/herself."
1446 :group 'org-link-store
1447 :type 'regexp)
1449 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1450 "Non-nil means storing a link to an Org file will use entry IDs.
1452 Note that before this variable is even considered, org-id must be loaded,
1453 so please customize `org-modules' and turn it on.
1455 The variable can have the following values:
1457 t Create an ID if needed to make a link to the current entry.
1459 create-if-interactive
1460 If `org-store-link' is called directly (interactively, as a user
1461 command), do create an ID to support the link. But when doing the
1462 job for remember, only use the ID if it already exists. The
1463 purpose of this setting is to avoid proliferation of unwanted
1464 IDs, just because you happen to be in an Org file when you
1465 call `org-capture' that automatically and preemptively creates a
1466 link. If you do want to get an ID link in a remember template to
1467 an entry not having an ID, create it first by explicitly creating
1468 a link to it, using `C-c C-l' first.
1470 create-if-interactive-and-no-custom-id
1471 Like create-if-interactive, but do not create an ID if there is
1472 a CUSTOM_ID property defined in the entry. This is the default.
1474 use-existing
1475 Use existing ID, do not create one.
1477 nil Never use an ID to make a link, instead link using a text search for
1478 the headline text."
1479 :group 'org-link-store
1480 :type '(choice
1481 (const :tag "Create ID to make link" t)
1482 (const :tag "Create if storing link interactively"
1483 create-if-interactive)
1484 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1485 create-if-interactive-and-no-custom-id)
1486 (const :tag "Only use existing" use-existing)
1487 (const :tag "Do not use ID to create link" nil)))
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 ;; :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a remember template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a remember note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :type 'directory)
1881 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1882 "Default target for storing notes.
1883 Used as a fall back file for org-remember.el and org-capture.el, for
1884 templates that do not specify a target file."
1885 :group 'org-refile
1886 :group 'org-remember
1887 :type '(choice
1888 (const :tag "Default from remember-data-file" nil)
1889 file))
1891 (defcustom org-goto-interface 'outline
1892 "The default interface to be used for `org-goto'.
1893 Allowed values are:
1894 outline The interface shows an outline of the relevant file
1895 and the correct heading is found by moving through
1896 the outline or by searching with incremental search.
1897 outline-path-completion Headlines in the current buffer are offered via
1898 completion. This is the interface also used by
1899 the refile command."
1900 :group 'org-refile
1901 :type '(choice
1902 (const :tag "Outline" outline)
1903 (const :tag "Outline-path-completion" outline-path-completion)))
1905 (defcustom org-goto-max-level 5
1906 "Maximum target level when running `org-goto' with refile interface."
1907 :group 'org-refile
1908 :type 'integer)
1910 (defcustom org-reverse-note-order nil
1911 "Non-nil means store new notes at the beginning of a file or entry.
1912 When nil, new notes will be filed to the end of a file or entry.
1913 This can also be a list with cons cells of regular expressions that
1914 are matched against file names, and values."
1915 :group 'org-remember
1916 :group 'org-refile
1917 :type '(choice
1918 (const :tag "Reverse always" t)
1919 (const :tag "Reverse never" nil)
1920 (repeat :tag "By file name regexp"
1921 (cons regexp boolean))))
1923 (defcustom org-log-refile nil
1924 "Information to record when a task is refiled.
1926 Possible values are:
1928 nil Don't add anything
1929 time Add a time stamp to the task
1930 note Prompt for a note and add it with template `org-log-note-headings'
1932 This option can also be set with on a per-file-basis with
1934 #+STARTUP: nologrefile
1935 #+STARTUP: logrefile
1936 #+STARTUP: lognoterefile
1938 You can have local logging settings for a subtree by setting the LOGGING
1939 property to one or more of these keywords.
1941 When bulk-refiling from the agenda, the value `note' is forbidden and
1942 will temporarily be changed to `time'."
1943 :group 'org-refile
1944 :group 'org-progress
1945 :version "24.1"
1946 :type '(choice
1947 (const :tag "No logging" nil)
1948 (const :tag "Record timestamp" time)
1949 (const :tag "Record timestamp with note." note)))
1951 (defcustom org-refile-targets nil
1952 "Targets for refiling entries with \\[org-refile].
1953 This is a list of cons cells. Each cell contains:
1954 - a specification of the files to be considered, either a list of files,
1955 or a symbol whose function or variable value will be used to retrieve
1956 a file name or a list of file names. If you use `org-agenda-files' for
1957 that, all agenda files will be scanned for targets. Nil means consider
1958 headings in the current buffer.
1959 - A specification of how to find candidate refile targets. This may be
1960 any of:
1961 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1962 This tag has to be present in all target headlines, inheritance will
1963 not be considered.
1964 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1965 todo keyword.
1966 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1967 headlines that are refiling targets.
1968 - a cons cell (:level . N). Any headline of level N is considered a target.
1969 Note that, when `org-odd-levels-only' is set, level corresponds to
1970 order in hierarchy, not to the number of stars.
1971 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1975 Each element of this list generates a set of possible targets.
1976 The union of these sets is presented (with completion) to
1977 the user by `org-refile'.
1979 You can set the variable `org-refile-target-verify-function' to a function
1980 to verify each headline found by the simple criteria above.
1982 When this variable is nil, all top-level headlines in the current buffer
1983 are used, equivalent to the value `((nil . (:level . 1))'."
1984 :group 'org-refile
1985 :type '(repeat
1986 (cons
1987 (choice :value org-agenda-files
1988 (const :tag "All agenda files" org-agenda-files)
1989 (const :tag "Current buffer" nil)
1990 (function) (variable) (file))
1991 (choice :tag "Identify target headline by"
1992 (cons :tag "Specific tag" (const :value :tag) (string))
1993 (cons :tag "TODO keyword" (const :value :todo) (string))
1994 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1995 (cons :tag "Level number" (const :value :level) (integer))
1996 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1998 (defcustom org-refile-target-verify-function nil
1999 "Function to verify if the headline at point should be a refile target.
2000 The function will be called without arguments, with point at the
2001 beginning of the headline. It should return t and leave point
2002 where it is if the headline is a valid target for refiling.
2004 If the target should not be selected, the function must return nil.
2005 In addition to this, it may move point to a place from where the search
2006 should be continued. For example, the function may decide that the entire
2007 subtree of the current entry should be excluded and move point to the end
2008 of the subtree."
2009 :group 'org-refile
2010 :type 'function)
2012 (defcustom org-refile-use-cache nil
2013 "Non-nil means cache refile targets to speed up the process.
2014 The cache for a particular file will be updated automatically when
2015 the buffer has been killed, or when any of the marker used for flagging
2016 refile targets no longer points at a live buffer.
2017 If you have added new entries to a buffer that might themselves be targets,
2018 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2019 find that easier, `C-u C-u C-u C-c C-w'."
2020 :group 'org-refile
2021 :version "24.1"
2022 :type 'boolean)
2024 (defcustom org-refile-use-outline-path nil
2025 "Non-nil means provide refile targets as paths.
2026 So a level 3 headline will be available as level1/level2/level3.
2028 When the value is `file', also include the file name (without directory)
2029 into the path. In this case, you can also stop the completion after
2030 the file name, to get entries inserted as top level in the file.
2032 When `full-file-path', include the full file path."
2033 :group 'org-refile
2034 :type '(choice
2035 (const :tag "Not" nil)
2036 (const :tag "Yes" t)
2037 (const :tag "Start with file name" file)
2038 (const :tag "Start with full file path" full-file-path)))
2040 (defcustom org-outline-path-complete-in-steps t
2041 "Non-nil means complete the outline path in hierarchical steps.
2042 When Org-mode uses the refile interface to select an outline path
2043 \(see variable `org-refile-use-outline-path'), the completion of
2044 the path can be done is a single go, or if can be done in steps down
2045 the headline hierarchy. Going in steps is probably the best if you
2046 do not use a special completion package like `ido' or `icicles'.
2047 However, when using these packages, going in one step can be very
2048 fast, while still showing the whole path to the entry."
2049 :group 'org-refile
2050 :type 'boolean)
2052 (defcustom org-refile-allow-creating-parent-nodes nil
2053 "Non-nil means allow to create new nodes as refile targets.
2054 New nodes are then created by adding \"/new node name\" to the completion
2055 of an existing node. When the value of this variable is `confirm',
2056 new node creation must be confirmed by the user (recommended)
2057 When nil, the completion must match an existing entry.
2059 Note that, if the new heading is not seen by the criteria
2060 listed in `org-refile-targets', multiple instances of the same
2061 heading would be created by trying again to file under the new
2062 heading."
2063 :group 'org-refile
2064 :type '(choice
2065 (const :tag "Never" nil)
2066 (const :tag "Always" t)
2067 (const :tag "Prompt for confirmation" confirm)))
2069 (defcustom org-refile-active-region-within-subtree nil
2070 "Non-nil means also refile active region within a subtree.
2072 By default `org-refile' doesn't allow refiling regions if they
2073 don't contain a set of subtrees, but it might be convenient to
2074 do so sometimes: in that case, the first line of the region is
2075 converted to a headline before refiling."
2076 :group 'org-refile
2077 :version "24.1"
2078 :type 'boolean)
2080 (defgroup org-todo nil
2081 "Options concerning TODO items in Org-mode."
2082 :tag "Org TODO"
2083 :group 'org)
2085 (defgroup org-progress nil
2086 "Options concerning Progress logging in Org-mode."
2087 :tag "Org Progress"
2088 :group 'org-time)
2090 (defvar org-todo-interpretation-widgets
2091 '((:tag "Sequence (cycling hits every state)" sequence)
2092 (:tag "Type (cycling directly to DONE)" type))
2093 "The available interpretation symbols for customizing `org-todo-keywords'.
2094 Interested libraries should add to this list.")
2096 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2097 "List of TODO entry keyword sequences and their interpretation.
2098 \\<org-mode-map>This is a list of sequences.
2100 Each sequence starts with a symbol, either `sequence' or `type',
2101 indicating if the keywords should be interpreted as a sequence of
2102 action steps, or as different types of TODO items. The first
2103 keywords are states requiring action - these states will select a headline
2104 for inclusion into the global TODO list Org-mode produces. If one of
2105 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2106 signify that no further action is necessary. If \"|\" is not found,
2107 the last keyword is treated as the only DONE state of the sequence.
2109 The command \\[org-todo] cycles an entry through these states, and one
2110 additional state where no keyword is present. For details about this
2111 cycling, see the manual.
2113 TODO keywords and interpretation can also be set on a per-file basis with
2114 the special #+SEQ_TODO and #+TYP_TODO lines.
2116 Each keyword can optionally specify a character for fast state selection
2117 \(in combination with the variable `org-use-fast-todo-selection')
2118 and specifiers for state change logging, using the same syntax that
2119 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2120 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2121 indicates to record a time stamp each time this state is selected.
2123 Each keyword may also specify if a timestamp or a note should be
2124 recorded when entering or leaving the state, by adding additional
2125 characters in the parenthesis after the keyword. This looks like this:
2126 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2127 record only the time of the state change. With X and Y being either
2128 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2129 Y when leaving the state if and only if the *target* state does not
2130 define X. You may omit any of the fast-selection key or X or /Y,
2131 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2133 For backward compatibility, this variable may also be just a list
2134 of keywords. In this case the interpretation (sequence or type) will be
2135 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2136 :group 'org-todo
2137 :group 'org-keywords
2138 :type '(choice
2139 (repeat :tag "Old syntax, just keywords"
2140 (string :tag "Keyword"))
2141 (repeat :tag "New syntax"
2142 (cons
2143 (choice
2144 :tag "Interpretation"
2145 ;;Quick and dirty way to see
2146 ;;`org-todo-interpretations'. This takes the
2147 ;;place of item arguments
2148 :convert-widget
2149 (lambda (widget)
2150 (widget-put widget
2151 :args (mapcar
2152 #'(lambda (x)
2153 (widget-convert
2154 (cons 'const x)))
2155 org-todo-interpretation-widgets))
2156 widget))
2157 (repeat
2158 (string :tag "Keyword"))))))
2160 (defvar org-todo-keywords-1 nil
2161 "All TODO and DONE keywords active in a buffer.")
2162 (make-variable-buffer-local 'org-todo-keywords-1)
2163 (defvar org-todo-keywords-for-agenda nil)
2164 (defvar org-done-keywords-for-agenda nil)
2165 (defvar org-drawers-for-agenda nil)
2166 (defvar org-todo-keyword-alist-for-agenda nil)
2167 (defvar org-tag-alist-for-agenda nil)
2168 (defvar org-agenda-contributing-files nil)
2169 (defvar org-not-done-keywords nil)
2170 (make-variable-buffer-local 'org-not-done-keywords)
2171 (defvar org-done-keywords nil)
2172 (make-variable-buffer-local 'org-done-keywords)
2173 (defvar org-todo-heads nil)
2174 (make-variable-buffer-local 'org-todo-heads)
2175 (defvar org-todo-sets nil)
2176 (make-variable-buffer-local 'org-todo-sets)
2177 (defvar org-todo-log-states nil)
2178 (make-variable-buffer-local 'org-todo-log-states)
2179 (defvar org-todo-kwd-alist nil)
2180 (make-variable-buffer-local 'org-todo-kwd-alist)
2181 (defvar org-todo-key-alist nil)
2182 (make-variable-buffer-local 'org-todo-key-alist)
2183 (defvar org-todo-key-trigger nil)
2184 (make-variable-buffer-local 'org-todo-key-trigger)
2186 (defcustom org-todo-interpretation 'sequence
2187 "Controls how TODO keywords are interpreted.
2188 This variable is in principle obsolete and is only used for
2189 backward compatibility, if the interpretation of todo keywords is
2190 not given already in `org-todo-keywords'. See that variable for
2191 more information."
2192 :group 'org-todo
2193 :group 'org-keywords
2194 :type '(choice (const sequence)
2195 (const type)))
2197 (defcustom org-use-fast-todo-selection t
2198 "Non-nil means use the fast todo selection scheme with C-c C-t.
2199 This variable describes if and under what circumstances the cycling
2200 mechanism for TODO keywords will be replaced by a single-key, direct
2201 selection scheme.
2203 When nil, fast selection is never used.
2205 When the symbol `prefix', it will be used when `org-todo' is called
2206 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2207 `C-u t' in an agenda buffer.
2209 When t, fast selection is used by default. In this case, the prefix
2210 argument forces cycling instead.
2212 In all cases, the special interface is only used if access keys have
2213 actually been assigned by the user, i.e. if keywords in the configuration
2214 are followed by a letter in parenthesis, like TODO(t)."
2215 :group 'org-todo
2216 :type '(choice
2217 (const :tag "Never" nil)
2218 (const :tag "By default" t)
2219 (const :tag "Only with C-u C-c C-t" prefix)))
2221 (defcustom org-provide-todo-statistics t
2222 "Non-nil means update todo statistics after insert and toggle.
2223 ALL-HEADLINES means update todo statistics by including headlines
2224 with no TODO keyword as well, counting them as not done.
2225 A list of TODO keywords means the same, but skip keywords that are
2226 not in this list.
2228 When this is set, todo statistics is updated in the parent of the
2229 current entry each time a todo state is changed."
2230 :group 'org-todo
2231 :type '(choice
2232 (const :tag "Yes, only for TODO entries" t)
2233 (const :tag "Yes, including all entries" 'all-headlines)
2234 (repeat :tag "Yes, for TODOs in this list"
2235 (string :tag "TODO keyword"))
2236 (other :tag "No TODO statistics" nil)))
2238 (defcustom org-hierarchical-todo-statistics t
2239 "Non-nil means TODO statistics covers just direct children.
2240 When nil, all entries in the subtree are considered.
2241 This has only an effect if `org-provide-todo-statistics' is set.
2242 To set this to nil for only a single subtree, use a COOKIE_DATA
2243 property and include the word \"recursive\" into the value."
2244 :group 'org-todo
2245 :type 'boolean)
2247 (defcustom org-after-todo-state-change-hook nil
2248 "Hook which is run after the state of a TODO item was changed.
2249 The new state (a string with a TODO keyword, or nil) is available in the
2250 Lisp variable `org-state'."
2251 :group 'org-todo
2252 :type 'hook)
2254 (defvar org-blocker-hook nil
2255 "Hook for functions that are allowed to block a state change.
2257 Each function gets as its single argument a property list, see
2258 `org-trigger-hook' for more information about this list.
2260 If any of the functions in this hook returns nil, the state change
2261 is blocked.")
2263 (defvar org-trigger-hook nil
2264 "Hook for functions that are triggered by a state change.
2266 Each function gets as its single argument a property list with at least
2267 the following elements:
2269 (:type type-of-change :position pos-at-entry-start
2270 :from old-state :to new-state)
2272 Depending on the type, more properties may be present.
2274 This mechanism is currently implemented for:
2276 TODO state changes
2277 ------------------
2278 :type todo-state-change
2279 :from previous state (keyword as a string), or nil, or a symbol
2280 'todo' or 'done', to indicate the general type of state.
2281 :to new state, like in :from")
2283 (defcustom org-enforce-todo-dependencies nil
2284 "Non-nil means undone TODO entries will block switching the parent to DONE.
2285 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2286 be blocked if any prior sibling is not yet done.
2287 Finally, if the parent is blocked because of ordered siblings of its own,
2288 the child will also be blocked."
2289 :set (lambda (var val)
2290 (set var val)
2291 (if val
2292 (add-hook 'org-blocker-hook
2293 'org-block-todo-from-children-or-siblings-or-parent)
2294 (remove-hook 'org-blocker-hook
2295 'org-block-todo-from-children-or-siblings-or-parent)))
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-enforce-todo-checkbox-dependencies nil
2300 "Non-nil means unchecked boxes will block switching the parent to DONE.
2301 When this is nil, checkboxes have no influence on switching TODO states.
2302 When non-nil, you first need to check off all check boxes before the TODO
2303 entry can be switched to DONE.
2304 This variable needs to be set before org.el is loaded, and you need to
2305 restart Emacs after a change to make the change effective. The only way
2306 to change is while Emacs is running is through the customize interface."
2307 :set (lambda (var val)
2308 (set var val)
2309 (if val
2310 (add-hook 'org-blocker-hook
2311 'org-block-todo-from-checkboxes)
2312 (remove-hook 'org-blocker-hook
2313 'org-block-todo-from-checkboxes)))
2314 :group 'org-todo
2315 :type 'boolean)
2317 (defcustom org-treat-insert-todo-heading-as-state-change nil
2318 "Non-nil means inserting a TODO heading is treated as state change.
2319 So when the command \\[org-insert-todo-heading] is used, state change
2320 logging will apply if appropriate. When nil, the new TODO item will
2321 be inserted directly, and no logging will take place."
2322 :group 'org-todo
2323 :type 'boolean)
2325 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2326 "Non-nil means switching TODO states with S-cursor counts as state change.
2327 This is the default behavior. However, setting this to nil allows a
2328 convenient way to select a TODO state and bypass any logging associated
2329 with that."
2330 :group 'org-todo
2331 :type 'boolean)
2333 (defcustom org-todo-state-tags-triggers nil
2334 "Tag changes that should be triggered by TODO state changes.
2335 This is a list. Each entry is
2337 (state-change (tag . flag) .......)
2339 State-change can be a string with a state, and empty string to indicate the
2340 state that has no TODO keyword, or it can be one of the symbols `todo'
2341 or `done', meaning any not-done or done state, respectively."
2342 :group 'org-todo
2343 :group 'org-tags
2344 :type '(repeat
2345 (cons (choice :tag "When changing to"
2346 (const :tag "Not-done state" todo)
2347 (const :tag "Done state" done)
2348 (string :tag "State"))
2349 (repeat
2350 (cons :tag "Tag action"
2351 (string :tag "Tag")
2352 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2354 (defcustom org-log-done nil
2355 "Information to record when a task moves to the DONE state.
2357 Possible values are:
2359 nil Don't add anything, just change the keyword
2360 time Add a time stamp to the task
2361 note Prompt for a note and add it with template `org-log-note-headings'
2363 This option can also be set with on a per-file-basis with
2365 #+STARTUP: nologdone
2366 #+STARTUP: logdone
2367 #+STARTUP: lognotedone
2369 You can have local logging settings for a subtree by setting the LOGGING
2370 property to one or more of these keywords."
2371 :group 'org-todo
2372 :group 'org-progress
2373 :type '(choice
2374 (const :tag "No logging" nil)
2375 (const :tag "Record CLOSED timestamp" time)
2376 (const :tag "Record CLOSED timestamp with note." note)))
2378 ;; Normalize old uses of org-log-done.
2379 (cond
2380 ((eq org-log-done t) (setq org-log-done 'time))
2381 ((and (listp org-log-done) (memq 'done org-log-done))
2382 (setq org-log-done 'note)))
2384 (defcustom org-log-reschedule nil
2385 "Information to record when the scheduling date of a tasks is modified.
2387 Possible values are:
2389 nil Don't add anything, just change the date
2390 time Add a time stamp to the task
2391 note Prompt for a note and add it with template `org-log-note-headings'
2393 This option can also be set with on a per-file-basis with
2395 #+STARTUP: nologreschedule
2396 #+STARTUP: logreschedule
2397 #+STARTUP: lognotereschedule"
2398 :group 'org-todo
2399 :group 'org-progress
2400 :type '(choice
2401 (const :tag "No logging" nil)
2402 (const :tag "Record timestamp" time)
2403 (const :tag "Record timestamp with note." note)))
2405 (defcustom org-log-redeadline nil
2406 "Information to record when the deadline date of a tasks is modified.
2408 Possible values are:
2410 nil Don't add anything, just change the date
2411 time Add a time stamp to the task
2412 note Prompt for a note and add it with template `org-log-note-headings'
2414 This option can also be set with on a per-file-basis with
2416 #+STARTUP: nologredeadline
2417 #+STARTUP: logredeadline
2418 #+STARTUP: lognoteredeadline
2420 You can have local logging settings for a subtree by setting the LOGGING
2421 property to one or more of these keywords."
2422 :group 'org-todo
2423 :group 'org-progress
2424 :type '(choice
2425 (const :tag "No logging" nil)
2426 (const :tag "Record timestamp" time)
2427 (const :tag "Record timestamp with note." note)))
2429 (defcustom org-log-note-clock-out nil
2430 "Non-nil means record a note when clocking out of an item.
2431 This can also be configured on a per-file basis by adding one of
2432 the following lines anywhere in the buffer:
2434 #+STARTUP: lognoteclock-out
2435 #+STARTUP: nolognoteclock-out"
2436 :group 'org-todo
2437 :group 'org-progress
2438 :type 'boolean)
2440 (defcustom org-log-done-with-time t
2441 "Non-nil means the CLOSED time stamp will contain date and time.
2442 When nil, only the date will be recorded."
2443 :group 'org-progress
2444 :type 'boolean)
2446 (defcustom org-log-note-headings
2447 '((done . "CLOSING NOTE %t")
2448 (state . "State %-12s from %-12S %t")
2449 (note . "Note taken on %t")
2450 (reschedule . "Rescheduled from %S on %t")
2451 (delschedule . "Not scheduled, was %S on %t")
2452 (redeadline . "New deadline from %S on %t")
2453 (deldeadline . "Removed deadline, was %S on %t")
2454 (refile . "Refiled on %t")
2455 (clock-out . ""))
2456 "Headings for notes added to entries.
2457 The value is an alist, with the car being a symbol indicating the note
2458 context, and the cdr is the heading to be used. The heading may also be the
2459 empty string.
2460 %t in the heading will be replaced by a time stamp.
2461 %T will be an active time stamp instead the default inactive one
2462 %d will be replaced by a short-format time stamp.
2463 %D will be replaced by an active short-format time stamp.
2464 %s will be replaced by the new TODO state, in double quotes.
2465 %S will be replaced by the old TODO state, in double quotes.
2466 %u will be replaced by the user name.
2467 %U will be replaced by the full user name.
2469 In fact, it is not a good idea to change the `state' entry, because
2470 agenda log mode depends on the format of these entries."
2471 :group 'org-todo
2472 :group 'org-progress
2473 :type '(list :greedy t
2474 (cons (const :tag "Heading when closing an item" done) string)
2475 (cons (const :tag
2476 "Heading when changing todo state (todo sequence only)"
2477 state) string)
2478 (cons (const :tag "Heading when just taking a note" note) string)
2479 (cons (const :tag "Heading when clocking out" clock-out) string)
2480 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2481 (cons (const :tag "Heading when rescheduling" reschedule) string)
2482 (cons (const :tag "Heading when changing deadline" redeadline) string)
2483 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2484 (cons (const :tag "Heading when refiling" refile) string)))
2486 (unless (assq 'note org-log-note-headings)
2487 (push '(note . "%t") org-log-note-headings))
2489 (defcustom org-log-into-drawer nil
2490 "Non-nil means insert state change notes and time stamps into a drawer.
2491 When nil, state changes notes will be inserted after the headline and
2492 any scheduling and clock lines, but not inside a drawer.
2494 The value of this variable should be the name of the drawer to use.
2495 LOGBOOK is proposed as the default drawer for this purpose, you can
2496 also set this to a string to define the drawer of your choice.
2498 A value of t is also allowed, representing \"LOGBOOK\".
2500 If this variable is set, `org-log-state-notes-insert-after-drawers'
2501 will be ignored.
2503 You can set the property LOG_INTO_DRAWER to overrule this setting for
2504 a subtree."
2505 :group 'org-todo
2506 :group 'org-progress
2507 :type '(choice
2508 (const :tag "Not into a drawer" nil)
2509 (const :tag "LOGBOOK" t)
2510 (string :tag "Other")))
2512 (if (fboundp 'defvaralias)
2513 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2515 (defun org-log-into-drawer ()
2516 "Return the value of `org-log-into-drawer', but let properties overrule.
2517 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2518 used instead of the default value."
2519 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2520 (cond
2521 ((or (not p) (equal p "nil")) org-log-into-drawer)
2522 ((equal p "t") "LOGBOOK")
2523 (t p))))
2525 (defcustom org-log-state-notes-insert-after-drawers nil
2526 "Non-nil means insert state change notes after any drawers in entry.
2527 Only the drawers that *immediately* follow the headline and the
2528 deadline/scheduled line are skipped.
2529 When nil, insert notes right after the heading and perhaps the line
2530 with deadline/scheduling if present.
2532 This variable will have no effect if `org-log-into-drawer' is
2533 set."
2534 :group 'org-todo
2535 :group 'org-progress
2536 :type 'boolean)
2538 (defcustom org-log-states-order-reversed t
2539 "Non-nil means the latest state note will be directly after heading.
2540 When nil, the state change notes will be ordered according to time."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type 'boolean)
2545 (defcustom org-todo-repeat-to-state nil
2546 "The TODO state to which a repeater should return the repeating task.
2547 By default this is the first task in a TODO sequence, or the previous state
2548 in a TODO_TYP set. But you can specify another task here.
2549 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2550 :group 'org-todo
2551 :version "24.1"
2552 :type '(choice (const :tag "Head of sequence" nil)
2553 (string :tag "Specific state")))
2555 (defcustom org-log-repeat 'time
2556 "Non-nil means record moving through the DONE state when triggering repeat.
2557 An auto-repeating task is immediately switched back to TODO when
2558 marked DONE. If you are not logging state changes (by adding \"@\"
2559 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2560 record a closing note, there will be no record of the task moving
2561 through DONE. This variable forces taking a note anyway.
2563 nil Don't force a record
2564 time Record a time stamp
2565 note Prompt for a note and add it with template `org-log-note-headings'
2567 This option can also be set with on a per-file-basis with
2569 #+STARTUP: nologrepeat
2570 #+STARTUP: logrepeat
2571 #+STARTUP: lognoterepeat
2573 You can have local logging settings for a subtree by setting the LOGGING
2574 property to one or more of these keywords."
2575 :group 'org-todo
2576 :group 'org-progress
2577 :type '(choice
2578 (const :tag "Don't force a record" nil)
2579 (const :tag "Force recording the DONE state" time)
2580 (const :tag "Force recording a note with the DONE state" note)))
2583 (defgroup org-priorities nil
2584 "Priorities in Org-mode."
2585 :tag "Org Priorities"
2586 :group 'org-todo)
2588 (defcustom org-enable-priority-commands t
2589 "Non-nil means priority commands are active.
2590 When nil, these commands will be disabled, so that you never accidentally
2591 set a priority."
2592 :group 'org-priorities
2593 :type 'boolean)
2595 (defcustom org-highest-priority ?A
2596 "The highest priority of TODO items. A character like ?A, ?B etc.
2597 Must have a smaller ASCII number than `org-lowest-priority'."
2598 :group 'org-priorities
2599 :type 'character)
2601 (defcustom org-lowest-priority ?C
2602 "The lowest priority of TODO items. A character like ?A, ?B etc.
2603 Must have a larger ASCII number than `org-highest-priority'."
2604 :group 'org-priorities
2605 :type 'character)
2607 (defcustom org-default-priority ?B
2608 "The default priority of TODO items.
2609 This is the priority an item gets if no explicit priority is given.
2610 When starting to cycle on an empty priority the first step in the cycle
2611 depends on `org-priority-start-cycle-with-default'. The resulting first
2612 step priority must not exceed the range from `org-highest-priority' to
2613 `org-lowest-priority' which means that `org-default-priority' has to be
2614 in this range exclusive or inclusive the range boundaries. Else the
2615 first step refuses to set the default and the second will fall back
2616 to (depending on the command used) the highest or lowest priority."
2617 :group 'org-priorities
2618 :type 'character)
2620 (defcustom org-priority-start-cycle-with-default t
2621 "Non-nil means start with default priority when starting to cycle.
2622 When this is nil, the first step in the cycle will be (depending on the
2623 command used) one higher or lower than the default priority.
2624 See also `org-default-priority'."
2625 :group 'org-priorities
2626 :type 'boolean)
2628 (defcustom org-get-priority-function nil
2629 "Function to extract the priority from a string.
2630 The string is normally the headline. If this is nil Org computes the
2631 priority from the priority cookie like [#A] in the headline. It returns
2632 an integer, increasing by 1000 for each priority level.
2633 The user can set a different function here, which should take a string
2634 as an argument and return the numeric priority."
2635 :group 'org-priorities
2636 :version "24.1"
2637 :type 'function)
2639 (defgroup org-time nil
2640 "Options concerning time stamps and deadlines in Org-mode."
2641 :tag "Org Time"
2642 :group 'org)
2644 (defcustom org-insert-labeled-timestamps-at-point nil
2645 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2646 When nil, these labeled time stamps are forces into the second line of an
2647 entry, just after the headline. When scheduling from the global TODO list,
2648 the time stamp will always be forced into the second line."
2649 :group 'org-time
2650 :type 'boolean)
2652 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2653 "Formats for `format-time-string' which are used for time stamps.
2654 It is not recommended to change this constant.")
2656 (defcustom org-time-stamp-rounding-minutes '(0 5)
2657 "Number of minutes to round time stamps to.
2658 These are two values, the first applies when first creating a time stamp.
2659 The second applies when changing it with the commands `S-up' and `S-down'.
2660 When changing the time stamp, this means that it will change in steps
2661 of N minutes, as given by the second value.
2663 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2664 numbers should be factors of 60, so for example 5, 10, 15.
2666 When this is larger than 1, you can still force an exact time stamp by using
2667 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2668 and by using a prefix arg to `S-up/down' to specify the exact number
2669 of minutes to shift."
2670 :group 'org-time
2671 :get #'(lambda (var) ; Make sure both elements are there
2672 (if (integerp (default-value var))
2673 (list (default-value var) 5)
2674 (default-value var)))
2675 :type '(list
2676 (integer :tag "when inserting times")
2677 (integer :tag "when modifying times")))
2679 ;; Normalize old customizations of this variable.
2680 (when (integerp org-time-stamp-rounding-minutes)
2681 (setq org-time-stamp-rounding-minutes
2682 (list org-time-stamp-rounding-minutes
2683 org-time-stamp-rounding-minutes)))
2685 (defcustom org-display-custom-times nil
2686 "Non-nil means overlay custom formats over all time stamps.
2687 The formats are defined through the variable `org-time-stamp-custom-formats'.
2688 To turn this on on a per-file basis, insert anywhere in the file:
2689 #+STARTUP: customtime"
2690 :group 'org-time
2691 :set 'set-default
2692 :type 'sexp)
2693 (make-variable-buffer-local 'org-display-custom-times)
2695 (defcustom org-time-stamp-custom-formats
2696 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2697 "Custom formats for time stamps. See `format-time-string' for the syntax.
2698 These are overlaid over the default ISO format if the variable
2699 `org-display-custom-times' is set. Time like %H:%M should be at the
2700 end of the second format. The custom formats are also honored by export
2701 commands, if custom time display is turned on at the time of export."
2702 :group 'org-time
2703 :type 'sexp)
2705 (defun org-time-stamp-format (&optional long inactive)
2706 "Get the right format for a time string."
2707 (let ((f (if long (cdr org-time-stamp-formats)
2708 (car org-time-stamp-formats))))
2709 (if inactive
2710 (concat "[" (substring f 1 -1) "]")
2711 f)))
2713 (defcustom org-time-clocksum-format "%d:%02d"
2714 "The format string used when creating CLOCKSUM lines.
2715 This is also used when org-mode generates a time duration."
2716 :group 'org-time
2717 :type 'string)
2719 (defcustom org-time-clocksum-use-fractional nil
2720 "If non-nil, \\[org-clock-display] uses fractional times.
2721 org-mode generates a time duration."
2722 :group 'org-time
2723 :type 'boolean)
2725 (defcustom org-time-clocksum-fractional-format "%.2f"
2726 "The format string used when creating CLOCKSUM lines, or when
2727 org-mode generates a time duration."
2728 :group 'org-time
2729 :type 'string)
2731 (defcustom org-deadline-warning-days 14
2732 "No. of days before expiration during which a deadline becomes active.
2733 This variable governs the display in sparse trees and in the agenda.
2734 When 0 or negative, it means use this number (the absolute value of it)
2735 even if a deadline has a different individual lead time specified.
2737 Custom commands can set this variable in the options section."
2738 :group 'org-time
2739 :group 'org-agenda-daily/weekly
2740 :type 'integer)
2742 (defcustom org-read-date-prefer-future t
2743 "Non-nil means assume future for incomplete date input from user.
2744 This affects the following situations:
2745 1. The user gives a month but not a year.
2746 For example, if it is April and you enter \"feb 2\", this will be read
2747 as Feb 2, *next* year. \"May 5\", however, will be this year.
2748 2. The user gives a day, but no month.
2749 For example, if today is the 15th, and you enter \"3\", Org-mode will
2750 read this as the third of *next* month. However, if you enter \"17\",
2751 it will be considered as *this* month.
2753 If you set this variable to the symbol `time', then also the following
2754 will work:
2756 3. If the user gives a time.
2757 If the time is before now, it will be interpreted as tomorrow.
2759 Currently none of this works for ISO week specifications.
2761 When this option is nil, the current day, month and year will always be
2762 used as defaults.
2764 See also `org-agenda-jump-prefer-future'."
2765 :group 'org-time
2766 :type '(choice
2767 (const :tag "Never" nil)
2768 (const :tag "Check month and day" t)
2769 (const :tag "Check month, day, and time" time)))
2771 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2772 "Should the agenda jump command prefer the future for incomplete dates?
2773 The default is to do the same as configured in `org-read-date-prefer-future'.
2774 But you can also set a deviating value here.
2775 This may t or nil, or the symbol `org-read-date-prefer-future'."
2776 :group 'org-agenda
2777 :group 'org-time
2778 :version "24.1"
2779 :type '(choice
2780 (const :tag "Use org-read-date-prefer-future"
2781 org-read-date-prefer-future)
2782 (const :tag "Never" nil)
2783 (const :tag "Always" t)))
2785 (defcustom org-read-date-force-compatible-dates t
2786 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2788 Depending on the system Emacs is running on, certain dates cannot
2789 be represented with the type used internally to represent time.
2790 Dates between 1970-1-1 and 2038-1-1 can always be represented
2791 correctly. Some systems allow for earlier dates, some for later,
2792 some for both. One way to find out it to insert any date into an
2793 Org buffer, putting the cursor on the year and hitting S-up and
2794 S-down to test the range.
2796 When this variable is set to t, the date/time prompt will not let
2797 you specify dates outside the 1970-2037 range, so it is certain that
2798 these dates will work in whatever version of Emacs you are
2799 running, and also that you can move a file from one Emacs implementation
2800 to another. WHenever Org is forcing the year for you, it will display
2801 a message and beep.
2803 When this variable is nil, Org will check if the date is
2804 representable in the specific Emacs implementation you are using.
2805 If not, it will force a year, usually the current year, and beep
2806 to remind you. Currently this setting is not recommended because
2807 the likelihood that you will open your Org files in an Emacs that
2808 has limited date range is not negligible.
2810 A workaround for this problem is to use diary sexp dates for time
2811 stamps outside of this range."
2812 :group 'org-time
2813 :version "24.1"
2814 :type 'boolean)
2816 (defcustom org-read-date-display-live t
2817 "Non-nil means display current interpretation of date prompt live.
2818 This display will be in an overlay, in the minibuffer."
2819 :group 'org-time
2820 :type 'boolean)
2822 (defcustom org-read-date-popup-calendar t
2823 "Non-nil means pop up a calendar when prompting for a date.
2824 In the calendar, the date can be selected with mouse-1. However, the
2825 minibuffer will also be active, and you can simply enter the date as well.
2826 When nil, only the minibuffer will be available."
2827 :group 'org-time
2828 :type 'boolean)
2829 (if (fboundp 'defvaralias)
2830 (defvaralias 'org-popup-calendar-for-date-prompt
2831 'org-read-date-popup-calendar))
2833 (defcustom org-read-date-minibuffer-setup-hook nil
2834 "Hook to be used to set up keys for the date/time interface.
2835 Add key definitions to `minibuffer-local-map', which will be a temporary
2836 copy."
2837 :group 'org-time
2838 :type 'hook)
2840 (defcustom org-extend-today-until 0
2841 "The hour when your day really ends. Must be an integer.
2842 This has influence for the following applications:
2843 - When switching the agenda to \"today\". It it is still earlier than
2844 the time given here, the day recognized as TODAY is actually yesterday.
2845 - When a date is read from the user and it is still before the time given
2846 here, the current date and time will be assumed to be yesterday, 23:59.
2847 Also, timestamps inserted in remember templates follow this rule.
2849 IMPORTANT: This is a feature whose implementation is and likely will
2850 remain incomplete. Really, it is only here because past midnight seems to
2851 be the favorite working time of John Wiegley :-)"
2852 :group 'org-time
2853 :type 'integer)
2855 (defcustom org-use-effective-time nil
2856 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2857 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2858 \"effective time\" of any timestamps between midnight and 8am will be
2859 23:59 of the previous day."
2860 :group 'org-time
2861 :version "24.1"
2862 :type 'boolean)
2864 (defcustom org-edit-timestamp-down-means-later nil
2865 "Non-nil means S-down will increase the time in a time stamp.
2866 When nil, S-up will increase."
2867 :group 'org-time
2868 :type 'boolean)
2870 (defcustom org-calendar-follow-timestamp-change t
2871 "Non-nil means make the calendar window follow timestamp changes.
2872 When a timestamp is modified and the calendar window is visible, it will be
2873 moved to the new date."
2874 :group 'org-time
2875 :type 'boolean)
2877 (defgroup org-tags nil
2878 "Options concerning tags in Org-mode."
2879 :tag "Org Tags"
2880 :group 'org)
2882 (defcustom org-tag-alist nil
2883 "List of tags allowed in Org-mode files.
2884 When this list is nil, Org-mode will base TAG input on what is already in the
2885 buffer.
2886 The value of this variable is an alist, the car of each entry must be a
2887 keyword as a string, the cdr may be a character that is used to select
2888 that tag through the fast-tag-selection interface.
2889 See the manual for details."
2890 :group 'org-tags
2891 :type '(repeat
2892 (choice
2893 (cons (string :tag "Tag name")
2894 (character :tag "Access char"))
2895 (list :tag "Start radio group"
2896 (const :startgroup)
2897 (option (string :tag "Group description")))
2898 (list :tag "End radio group"
2899 (const :endgroup)
2900 (option (string :tag "Group description")))
2901 (const :tag "New line" (:newline)))))
2903 (defcustom org-tag-persistent-alist nil
2904 "List of tags that will always appear in all Org-mode files.
2905 This is in addition to any in buffer settings or customizations
2906 of `org-tag-alist'.
2907 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2908 The value of this variable is an alist, the car of each entry must be a
2909 keyword as a string, the cdr may be a character that is used to select
2910 that tag through the fast-tag-selection interface.
2911 See the manual for details.
2912 To disable these tags on a per-file basis, insert anywhere in the file:
2913 #+STARTUP: noptag"
2914 :group 'org-tags
2915 :type '(repeat
2916 (choice
2917 (cons (string :tag "Tag name")
2918 (character :tag "Access char"))
2919 (const :tag "Start radio group" (:startgroup))
2920 (const :tag "End radio group" (:endgroup))
2921 (const :tag "New line" (:newline)))))
2923 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2924 "If non-nil, always offer completion for all tags of all agenda files.
2925 Instead of customizing this variable directly, you might want to
2926 set it locally for capture buffers, because there no list of
2927 tags in that file can be created dynamically (there are none).
2929 (add-hook 'org-capture-mode-hook
2930 (lambda ()
2931 (set (make-local-variable
2932 'org-complete-tags-always-offer-all-agenda-tags)
2933 t)))"
2934 :group 'org-tags
2935 :version "24.1"
2936 :type 'boolean)
2938 (defvar org-file-tags nil
2939 "List of tags that can be inherited by all entries in the file.
2940 The tags will be inherited if the variable `org-use-tag-inheritance'
2941 says they should be.
2942 This variable is populated from #+FILETAGS lines.")
2944 (defcustom org-use-fast-tag-selection 'auto
2945 "Non-nil means use fast tag selection scheme.
2946 This is a special interface to select and deselect tags with single keys.
2947 When nil, fast selection is never used.
2948 When the symbol `auto', fast selection is used if and only if selection
2949 characters for tags have been configured, either through the variable
2950 `org-tag-alist' or through a #+TAGS line in the buffer.
2951 When t, fast selection is always used and selection keys are assigned
2952 automatically if necessary."
2953 :group 'org-tags
2954 :type '(choice
2955 (const :tag "Always" t)
2956 (const :tag "Never" nil)
2957 (const :tag "When selection characters are configured" 'auto)))
2959 (defcustom org-fast-tag-selection-single-key nil
2960 "Non-nil means fast tag selection exits after first change.
2961 When nil, you have to press RET to exit it.
2962 During fast tag selection, you can toggle this flag with `C-c'.
2963 This variable can also have the value `expert'. In this case, the window
2964 displaying the tags menu is not even shown, until you press C-c again."
2965 :group 'org-tags
2966 :type '(choice
2967 (const :tag "No" nil)
2968 (const :tag "Yes" t)
2969 (const :tag "Expert" expert)))
2971 (defvar org-fast-tag-selection-include-todo nil
2972 "Non-nil means fast tags selection interface will also offer TODO states.
2973 This is an undocumented feature, you should not rely on it.")
2975 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2976 "The column to which tags should be indented in a headline.
2977 If this number is positive, it specifies the column. If it is negative,
2978 it means that the tags should be flushright to that column. For example,
2979 -80 works well for a normal 80 character screen.
2980 When 0, place tags directly after headline text, with only one space in
2981 between."
2982 :group 'org-tags
2983 :type 'integer)
2985 (defcustom org-auto-align-tags t
2986 "Non-nil keeps tags aligned when modifying headlines.
2987 Some operations (i.e. demoting) change the length of a headline and
2988 therefore shift the tags around. With this option turned on, after
2989 each such operation the tags are again aligned to `org-tags-column'."
2990 :group 'org-tags
2991 :type 'boolean)
2993 (defcustom org-use-tag-inheritance t
2994 "Non-nil means tags in levels apply also for sublevels.
2995 When nil, only the tags directly given in a specific line apply there.
2996 This may also be a list of tags that should be inherited, or a regexp that
2997 matches tags that should be inherited. Additional control is possible
2998 with the variable `org-tags-exclude-from-inheritance' which gives an
2999 explicit list of tags to be excluded from inheritance., even if the value of
3000 `org-use-tag-inheritance' would select it for inheritance.
3002 If this option is t, a match early-on in a tree can lead to a large
3003 number of matches in the subtree when constructing the agenda or creating
3004 a sparse tree. If you only want to see the first match in a tree during
3005 a search, check out the variable `org-tags-match-list-sublevels'."
3006 :group 'org-tags
3007 :type '(choice
3008 (const :tag "Not" nil)
3009 (const :tag "Always" t)
3010 (repeat :tag "Specific tags" (string :tag "Tag"))
3011 (regexp :tag "Tags matched by regexp")))
3013 (defcustom org-tags-exclude-from-inheritance nil
3014 "List of tags that should never be inherited.
3015 This is a way to exclude a few tags from inheritance. For way to do
3016 the opposite, to actively allow inheritance for selected tags,
3017 see the variable `org-use-tag-inheritance'."
3018 :group 'org-tags
3019 :type '(repeat (string :tag "Tag")))
3021 (defun org-tag-inherit-p (tag)
3022 "Check if TAG is one that should be inherited."
3023 (cond
3024 ((member tag org-tags-exclude-from-inheritance) nil)
3025 ((eq org-use-tag-inheritance t) t)
3026 ((not org-use-tag-inheritance) nil)
3027 ((stringp org-use-tag-inheritance)
3028 (string-match org-use-tag-inheritance tag))
3029 ((listp org-use-tag-inheritance)
3030 (member tag org-use-tag-inheritance))
3031 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3033 (defcustom org-tags-match-list-sublevels t
3034 "Non-nil means list also sublevels of headlines matching a search.
3035 This variable applies to tags/property searches, and also to stuck
3036 projects because this search is based on a tags match as well.
3038 When set to the symbol `indented', sublevels are indented with
3039 leading dots.
3041 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3042 the sublevels of a headline matching a tag search often also match
3043 the same search. Listing all of them can create very long lists.
3044 Setting this variable to nil causes subtrees of a match to be skipped.
3046 This variable is semi-obsolete and probably should always be true. It
3047 is better to limit inheritance to certain tags using the variables
3048 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3049 :group 'org-tags
3050 :type '(choice
3051 (const :tag "No, don't list them" nil)
3052 (const :tag "Yes, do list them" t)
3053 (const :tag "List them, indented with leading dots" indented)))
3055 (defcustom org-tags-sort-function nil
3056 "When set, tags are sorted using this function as a comparator."
3057 :group 'org-tags
3058 :type '(choice
3059 (const :tag "No sorting" nil)
3060 (const :tag "Alphabetical" string<)
3061 (const :tag "Reverse alphabetical" string>)
3062 (function :tag "Custom function" nil)))
3064 (defvar org-tags-history nil
3065 "History of minibuffer reads for tags.")
3066 (defvar org-last-tags-completion-table nil
3067 "The last used completion table for tags.")
3068 (defvar org-after-tags-change-hook nil
3069 "Hook that is run after the tags in a line have changed.")
3071 (defgroup org-properties nil
3072 "Options concerning properties in Org-mode."
3073 :tag "Org Properties"
3074 :group 'org)
3076 (defcustom org-property-format "%-10s %s"
3077 "How property key/value pairs should be formatted by `indent-line'.
3078 When `indent-line' hits a property definition, it will format the line
3079 according to this format, mainly to make sure that the values are
3080 lined-up with respect to each other."
3081 :group 'org-properties
3082 :type 'string)
3084 (defcustom org-properties-postprocess-alist nil
3085 "Alist of properties and functions to adjust inserted values.
3086 Elements of this alist must be of the form
3088 ([string] [function])
3090 where [string] must be a property name and [function] must be a
3091 lambda expression: this lambda expression must take one argument,
3092 the value to adjust, and return the new value as a string.
3094 For example, this element will allow the property \"Remaining\"
3095 to be updated wrt the relation between the \"Effort\" property
3096 and the clock summary:
3098 ((\"Remaining\" (lambda(value)
3099 (let ((clocksum (org-clock-sum-current-item))
3100 (effort (org-duration-string-to-minutes
3101 (org-entry-get (point) \"Effort\"))))
3102 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3103 :group 'org-properties
3104 :version "24.1"
3105 :type '(alist :key-type (string :tag "Property")
3106 :value-type (function :tag "Function")))
3108 (defcustom org-use-property-inheritance nil
3109 "Non-nil means properties apply also for sublevels.
3111 This setting is chiefly used during property searches. Turning it on can
3112 cause significant overhead when doing a search, which is why it is not
3113 on by default.
3115 When nil, only the properties directly given in the current entry count.
3116 When t, every property is inherited. The value may also be a list of
3117 properties that should have inheritance, or a regular expression matching
3118 properties that should be inherited.
3120 However, note that some special properties use inheritance under special
3121 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3122 and the properties ending in \"_ALL\" when they are used as descriptor
3123 for valid values of a property.
3125 Note for programmers:
3126 When querying an entry with `org-entry-get', you can control if inheritance
3127 should be used. By default, `org-entry-get' looks only at the local
3128 properties. You can request inheritance by setting the inherit argument
3129 to t (to force inheritance) or to `selective' (to respect the setting
3130 in this variable)."
3131 :group 'org-properties
3132 :type '(choice
3133 (const :tag "Not" nil)
3134 (const :tag "Always" t)
3135 (repeat :tag "Specific properties" (string :tag "Property"))
3136 (regexp :tag "Properties matched by regexp")))
3138 (defun org-property-inherit-p (property)
3139 "Check if PROPERTY is one that should be inherited."
3140 (cond
3141 ((eq org-use-property-inheritance t) t)
3142 ((not org-use-property-inheritance) nil)
3143 ((stringp org-use-property-inheritance)
3144 (string-match org-use-property-inheritance property))
3145 ((listp org-use-property-inheritance)
3146 (member property org-use-property-inheritance))
3147 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3149 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3150 "The default column format, if no other format has been defined.
3151 This variable can be set on the per-file basis by inserting a line
3153 #+COLUMNS: %25ITEM ....."
3154 :group 'org-properties
3155 :type 'string)
3157 (defcustom org-columns-ellipses ".."
3158 "The ellipses to be used when a field in column view is truncated.
3159 When this is the empty string, as many characters as possible are shown,
3160 but then there will be no visual indication that the field has been truncated.
3161 When this is a string of length N, the last N characters of a truncated
3162 field are replaced by this string. If the column is narrower than the
3163 ellipses string, only part of the ellipses string will be shown."
3164 :group 'org-properties
3165 :type 'string)
3167 (defcustom org-columns-modify-value-for-display-function nil
3168 "Function that modifies values for display in column view.
3169 For example, it can be used to cut out a certain part from a time stamp.
3170 The function must take 2 arguments:
3172 column-title The title of the column (*not* the property name)
3173 value The value that should be modified.
3175 The function should return the value that should be displayed,
3176 or nil if the normal value should be used."
3177 :group 'org-properties
3178 :type 'function)
3180 (defcustom org-effort-property "Effort"
3181 "The property that is being used to keep track of effort estimates.
3182 Effort estimates given in this property need to have the format H:MM."
3183 :group 'org-properties
3184 :group 'org-progress
3185 :type '(string :tag "Property"))
3187 (defconst org-global-properties-fixed
3188 '(("VISIBILITY_ALL" . "folded children content all")
3189 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3190 "List of property/value pairs that can be inherited by any entry.
3192 These are fixed values, for the preset properties. The user variable
3193 that can be used to add to this list is `org-global-properties'.
3195 The entries in this list are cons cells where the car is a property
3196 name and cdr is a string with the value. If the value represents
3197 multiple items like an \"_ALL\" property, separate the items by
3198 spaces.")
3200 (defcustom org-global-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3203 This list will be combined with the constant `org-global-properties-fixed'.
3205 The entries in this list are cons cells where the car is a property
3206 name and cdr is a string with the value.
3208 You can set buffer-local values for the same purpose in the variable
3209 `org-file-properties' this by adding lines like
3211 #+PROPERTY: NAME VALUE"
3212 :group 'org-properties
3213 :type '(repeat
3214 (cons (string :tag "Property")
3215 (string :tag "Value"))))
3217 (defvar org-file-properties nil
3218 "List of property/value pairs that can be inherited by any entry.
3219 Valid for the current buffer.
3220 This variable is populated from #+PROPERTY lines.")
3221 (make-variable-buffer-local 'org-file-properties)
3223 (defgroup org-agenda nil
3224 "Options concerning agenda views in Org-mode."
3225 :tag "Org Agenda"
3226 :group 'org)
3228 (defvar org-category nil
3229 "Variable used by org files to set a category for agenda display.
3230 Such files should use a file variable to set it, for example
3232 # -*- mode: org; org-category: \"ELisp\"
3234 or contain a special line
3236 #+CATEGORY: ELisp
3238 If the file does not specify a category, then file's base name
3239 is used instead.")
3240 (make-variable-buffer-local 'org-category)
3241 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3243 (defcustom org-agenda-files nil
3244 "The files to be used for agenda display.
3245 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3246 \\[org-remove-file]. You can also use customize to edit the list.
3248 If an entry is a directory, all files in that directory that are matched by
3249 `org-agenda-file-regexp' will be part of the file list.
3251 If the value of the variable is not a list but a single file name, then
3252 the list of agenda files is actually stored and maintained in that file, one
3253 agenda file per line. In this file paths can be given relative to
3254 `org-directory'. Tilde expansion and environment variable substitution
3255 are also made."
3256 :group 'org-agenda
3257 :type '(choice
3258 (repeat :tag "List of files and directories" file)
3259 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3261 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3262 "Regular expression to match files for `org-agenda-files'.
3263 If any element in the list in that variable contains a directory instead
3264 of a normal file, all files in that directory that are matched by this
3265 regular expression will be included."
3266 :group 'org-agenda
3267 :type 'regexp)
3269 (defcustom org-agenda-text-search-extra-files nil
3270 "List of extra files to be searched by text search commands.
3271 These files will be search in addition to the agenda files by the
3272 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3273 Note that these files will only be searched for text search commands,
3274 not for the other agenda views like todo lists, tag searches or the weekly
3275 agenda. This variable is intended to list notes and possibly archive files
3276 that should also be searched by these two commands.
3277 In fact, if the first element in the list is the symbol `agenda-archives',
3278 than all archive files of all agenda files will be added to the search
3279 scope."
3280 :group 'org-agenda
3281 :type '(set :greedy t
3282 (const :tag "Agenda Archives" agenda-archives)
3283 (repeat :inline t (file))))
3285 (if (fboundp 'defvaralias)
3286 (defvaralias 'org-agenda-multi-occur-extra-files
3287 'org-agenda-text-search-extra-files))
3289 (defcustom org-agenda-skip-unavailable-files nil
3290 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3291 A nil value means to remove them, after a query, from the list."
3292 :group 'org-agenda
3293 :type 'boolean)
3295 (defcustom org-calendar-to-agenda-key [?c]
3296 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3297 The command `org-calendar-goto-agenda' will be bound to this key. The
3298 default is the character `c' because then `c' can be used to switch back and
3299 forth between agenda and calendar."
3300 :group 'org-agenda
3301 :type 'sexp)
3303 (defcustom org-calendar-agenda-action-key [?k]
3304 "The key to be installed in `calendar-mode-map' for agenda-action.
3305 The command `org-agenda-action' will be bound to this key. The
3306 default is the character `k' because we use the same key in the agenda."
3307 :group 'org-agenda
3308 :type 'sexp)
3310 (defcustom org-calendar-insert-diary-entry-key [?i]
3311 "The key to be installed in `calendar-mode-map' for adding diary entries.
3312 This option is irrelevant until `org-agenda-diary-file' has been configured
3313 to point to an Org-mode file. When that is the case, the command
3314 `org-agenda-diary-entry' will be bound to the key given here, by default
3315 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3316 if you want to continue doing this, you need to change this to a different
3317 key."
3318 :group 'org-agenda
3319 :type 'sexp)
3321 (defcustom org-agenda-diary-file 'diary-file
3322 "File to which to add new entries with the `i' key in agenda and calendar.
3323 When this is the symbol `diary-file', the functionality in the Emacs
3324 calendar will be used to add entries to the `diary-file'. But when this
3325 points to a file, `org-agenda-diary-entry' will be used instead."
3326 :group 'org-agenda
3327 :type '(choice
3328 (const :tag "The standard Emacs diary file" diary-file)
3329 (file :tag "Special Org file diary entries")))
3331 (eval-after-load "calendar"
3332 '(progn
3333 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3334 'org-calendar-goto-agenda)
3335 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3336 'org-agenda-action)
3337 (add-hook 'calendar-mode-hook
3338 (lambda ()
3339 (unless (eq org-agenda-diary-file 'diary-file)
3340 (define-key calendar-mode-map
3341 org-calendar-insert-diary-entry-key
3342 'org-agenda-diary-entry))))))
3344 (defgroup org-latex nil
3345 "Options for embedding LaTeX code into Org-mode."
3346 :tag "Org LaTeX"
3347 :group 'org)
3349 (defcustom org-format-latex-options
3350 '(:foreground default :background default :scale 1.0
3351 :html-foreground "Black" :html-background "Transparent"
3352 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3353 "Options for creating images from LaTeX fragments.
3354 This is a property list with the following properties:
3355 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3356 `default' means use the foreground of the default face.
3357 :background the background color, or \"Transparent\".
3358 `default' means use the background of the default face.
3359 :scale a scaling factor for the size of the images, to get more pixels
3360 :html-foreground, :html-background, :html-scale
3361 the same numbers for HTML export.
3362 :matchers a list indicating which matchers should be used to
3363 find LaTeX fragments. Valid members of this list are:
3364 \"begin\" find environments
3365 \"$1\" find single characters surrounded by $.$
3366 \"$\" find math expressions surrounded by $...$
3367 \"$$\" find math expressions surrounded by $$....$$
3368 \"\\(\" find math expressions surrounded by \\(...\\)
3369 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3370 :group 'org-latex
3371 :type 'plist)
3373 (defcustom org-format-latex-signal-error t
3374 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3375 When nil, just push out a message."
3376 :group 'org-latex
3377 :version "24.1"
3378 :type 'boolean)
3380 (defcustom org-latex-to-mathml-jar-file nil
3381 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3382 Use this to specify additional executable file say a jar file.
3384 When using MathToWeb as the converter, specify the full-path to
3385 your mathtoweb.jar file."
3386 :group 'org-latex
3387 :version "24.1"
3388 :type '(choice
3389 (const :tag "None" nil)
3390 (file :tag "JAR file" :must-match t)))
3392 (defcustom org-latex-to-mathml-convert-command nil
3393 "Command to convert LaTeX fragments to MathML.
3394 Replace format-specifiers in the command as noted below and use
3395 `shell-command' to convert LaTeX to MathML.
3396 %j: Executable file in fully expanded form as specified by
3397 `org-latex-to-mathml-jar-file'.
3398 %I: Input LaTeX file in fully expanded form
3399 %o: Output MathML file
3400 This command is used by `org-create-math-formula'.
3402 When using MathToWeb as the converter, set this to
3403 \"java -jar %j -unicode -force -df %o %I\"."
3404 :group 'org-latex
3405 :version "24.1"
3406 :type '(choice
3407 (const :tag "None" nil)
3408 (string :tag "\nShell command")))
3410 (defcustom org-latex-create-formula-image-program 'dvipng
3411 "Program to convert LaTeX fragments with.
3413 dvipng Process the LaTeX fragments to dvi file, then convert
3414 dvi files to png files using dvipng.
3415 This will also include processing of non-math environments.
3416 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3417 to convert pdf files to png files"
3418 :group 'org-latex
3419 :version "24.1"
3420 :type '(choice
3421 (const :tag "dvipng" dvipng)
3422 (const :tag "imagemagick" imagemagick)))
3424 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3425 "Path to store latex preview images. A relative path here creates many
3426 directories relative to the processed org files paths. An absolute path
3427 puts all preview images at the same place."
3428 :group 'org-latex
3429 ;; :version "24.3"
3430 :type 'string)
3432 (defun org-format-latex-mathml-available-p ()
3433 "Return t if `org-latex-to-mathml-convert-command' is usable."
3434 (save-match-data
3435 (when (and (boundp 'org-latex-to-mathml-convert-command)
3436 org-latex-to-mathml-convert-command)
3437 (let ((executable (car (split-string
3438 org-latex-to-mathml-convert-command))))
3439 (when (executable-find executable)
3440 (if (string-match
3441 "%j" org-latex-to-mathml-convert-command)
3442 (file-readable-p org-latex-to-mathml-jar-file)
3443 t))))))
3445 (defcustom org-format-latex-header "\\documentclass{article}
3446 \\usepackage[usenames]{color}
3447 \\usepackage{amsmath}
3448 \\usepackage[mathscr]{eucal}
3449 \\pagestyle{empty} % do not remove
3450 \[PACKAGES]
3451 \[DEFAULT-PACKAGES]
3452 % The settings below are copied from fullpage.sty
3453 \\setlength{\\textwidth}{\\paperwidth}
3454 \\addtolength{\\textwidth}{-3cm}
3455 \\setlength{\\oddsidemargin}{1.5cm}
3456 \\addtolength{\\oddsidemargin}{-2.54cm}
3457 \\setlength{\\evensidemargin}{\\oddsidemargin}
3458 \\setlength{\\textheight}{\\paperheight}
3459 \\addtolength{\\textheight}{-\\headheight}
3460 \\addtolength{\\textheight}{-\\headsep}
3461 \\addtolength{\\textheight}{-\\footskip}
3462 \\addtolength{\\textheight}{-3cm}
3463 \\setlength{\\topmargin}{1.5cm}
3464 \\addtolength{\\topmargin}{-2.54cm}"
3465 "The document header used for processing LaTeX fragments.
3466 It is imperative that this header make sure that no page number
3467 appears on the page. The package defined in the variables
3468 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3469 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3470 will be appended."
3471 :group 'org-latex
3472 :type 'string)
3474 (defvar org-format-latex-header-extra nil)
3476 (defun org-set-packages-alist (var val)
3477 "Set the packages alist and make sure it has 3 elements per entry."
3478 (set var (mapcar (lambda (x)
3479 (if (and (consp x) (= (length x) 2))
3480 (list (car x) (nth 1 x) t)
3482 val)))
3484 (defun org-get-packages-alist (var)
3486 "Get the packages alist and make sure it has 3 elements per entry."
3487 (mapcar (lambda (x)
3488 (if (and (consp x) (= (length x) 2))
3489 (list (car x) (nth 1 x) t)
3491 (default-value var)))
3493 ;; The following variables are defined here because is it also used
3494 ;; when formatting latex fragments. Originally it was part of the
3495 ;; LaTeX exporter, which is why the name includes "export".
3496 (defcustom org-export-latex-default-packages-alist
3497 '(("AUTO" "inputenc" t)
3498 ("T1" "fontenc" t)
3499 ("" "fixltx2e" nil)
3500 ("" "graphicx" t)
3501 ("" "longtable" nil)
3502 ("" "float" nil)
3503 ("" "wrapfig" nil)
3504 ("" "soul" t)
3505 ("" "textcomp" t)
3506 ("" "marvosym" t)
3507 ("" "wasysym" t)
3508 ("" "latexsym" t)
3509 ("" "amssymb" t)
3510 ("" "hyperref" nil)
3511 "\\tolerance=1000"
3513 "Alist of default packages to be inserted in the header.
3514 Change this only if one of the packages here causes an incompatibility
3515 with another package you are using.
3516 The packages in this list are needed by one part or another of Org-mode
3517 to function properly.
3519 - inputenc, fontenc: for basic font and character selection
3520 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3521 for interpreting the entities in `org-entities'. You can skip some of these
3522 packages if you don't use any of the symbols in it.
3523 - graphicx: for including images
3524 - float, wrapfig: for figure placement
3525 - longtable: for long tables
3526 - hyperref: for cross references
3528 Therefore you should not modify this variable unless you know what you
3529 are doing. The one reason to change it anyway is that you might be loading
3530 some other package that conflicts with one of the default packages.
3531 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3532 If SNIPPET-FLAG is t, the package also needs to be included when
3533 compiling LaTeX snippets into images for inclusion into HTML."
3534 :group 'org-export-latex
3535 :set 'org-set-packages-alist
3536 :get 'org-get-packages-alist
3537 :version "24.1"
3538 :type '(repeat
3539 (choice
3540 (list :tag "options/package pair"
3541 (string :tag "options")
3542 (string :tag "package")
3543 (boolean :tag "Snippet"))
3544 (string :tag "A line of LaTeX"))))
3546 (defcustom org-export-latex-packages-alist nil
3547 "Alist of packages to be inserted in every LaTeX header.
3548 These will be inserted after `org-export-latex-default-packages-alist'.
3549 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3550 SNIPPET-FLAG, when t, indicates that this package is also needed when
3551 turning LaTeX snippets into images for inclusion into HTML.
3552 Make sure that you only list packages here which:
3553 - you want in every file
3554 - do not conflict with the default packages in
3555 `org-export-latex-default-packages-alist'
3556 - do not conflict with the setup in `org-format-latex-header'."
3557 :group 'org-export-latex
3558 :set 'org-set-packages-alist
3559 :get 'org-get-packages-alist
3560 :type '(repeat
3561 (choice
3562 (list :tag "options/package pair"
3563 (string :tag "options")
3564 (string :tag "package")
3565 (boolean :tag "Snippet"))
3566 (string :tag "A line of LaTeX"))))
3569 (defgroup org-appearance nil
3570 "Settings for Org-mode appearance."
3571 :tag "Org Appearance"
3572 :group 'org)
3574 (defcustom org-level-color-stars-only nil
3575 "Non-nil means fontify only the stars in each headline.
3576 When nil, the entire headline is fontified.
3577 Changing it requires restart of `font-lock-mode' to become effective
3578 also in regions already fontified."
3579 :group 'org-appearance
3580 :type 'boolean)
3582 (defcustom org-hide-leading-stars nil
3583 "Non-nil means hide the first N-1 stars in a headline.
3584 This works by using the face `org-hide' for these stars. This
3585 face is white for a light background, and black for a dark
3586 background. You may have to customize the face `org-hide' to
3587 make this work.
3588 Changing it requires restart of `font-lock-mode' to become effective
3589 also in regions already fontified.
3590 You may also set this on a per-file basis by adding one of the following
3591 lines to the buffer:
3593 #+STARTUP: hidestars
3594 #+STARTUP: showstars"
3595 :group 'org-appearance
3596 :type 'boolean)
3598 (defcustom org-hidden-keywords nil
3599 "List of symbols corresponding to keywords to be hidden the org buffer.
3600 For example, a value '(title) for this list will make the document's title
3601 appear in the buffer without the initial #+TITLE: keyword."
3602 :group 'org-appearance
3603 :version "24.1"
3604 :type '(set (const :tag "#+AUTHOR" author)
3605 (const :tag "#+DATE" date)
3606 (const :tag "#+EMAIL" email)
3607 (const :tag "#+TITLE" title)))
3609 (defcustom org-custom-properties nil
3610 "List of properties (as strings) with a special meaning.
3611 The default use of these custom properties is to let the user
3612 hide them with `org-toggle-custom-properties-visibility'."
3613 :group 'org-properties
3614 :group 'org-appearance
3615 ;; :version "24.3"
3616 :type '(repeat (string :tag "Property Name")))
3618 (defcustom org-fontify-done-headline nil
3619 "Non-nil means change the face of a headline if it is marked DONE.
3620 Normally, only the TODO/DONE keyword indicates the state of a headline.
3621 When this is non-nil, the headline after the keyword is set to the
3622 `org-headline-done' as an additional indication."
3623 :group 'org-appearance
3624 :type 'boolean)
3626 (defcustom org-fontify-emphasized-text t
3627 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3628 Changing this variable requires a restart of Emacs to take effect."
3629 :group 'org-appearance
3630 :type 'boolean)
3632 (defcustom org-fontify-whole-heading-line nil
3633 "Non-nil means fontify the whole line for headings.
3634 This is useful when setting a background color for the
3635 org-level-* faces."
3636 :group 'org-appearance
3637 :type 'boolean)
3639 (defcustom org-highlight-latex-fragments-and-specials nil
3640 "Non-nil means fontify what is treated specially by the exporters."
3641 :group 'org-appearance
3642 :type 'boolean)
3644 (defcustom org-hide-emphasis-markers nil
3645 "Non-nil mean font-lock should hide the emphasis marker characters."
3646 :group 'org-appearance
3647 :type 'boolean)
3649 (defcustom org-pretty-entities nil
3650 "Non-nil means show entities as UTF8 characters.
3651 When nil, the \\name form remains in the buffer."
3652 :group 'org-appearance
3653 :version "24.1"
3654 :type 'boolean)
3656 (defcustom org-pretty-entities-include-sub-superscripts t
3657 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3658 :group 'org-appearance
3659 :version "24.1"
3660 :type 'boolean)
3662 (defvar org-emph-re nil
3663 "Regular expression for matching emphasis.
3664 After a match, the match groups contain these elements:
3665 0 The match of the full regular expression, including the characters
3666 before and after the proper match
3667 1 The character before the proper match, or empty at beginning of line
3668 2 The proper match, including the leading and trailing markers
3669 3 The leading marker like * or /, indicating the type of highlighting
3670 4 The text between the emphasis markers, not including the markers
3671 5 The character after the match, empty at the end of a line")
3672 (defvar org-verbatim-re nil
3673 "Regular expression for matching verbatim text.")
3674 (defvar org-emphasis-regexp-components) ; defined just below
3675 (defvar org-emphasis-alist) ; defined just below
3676 (defun org-set-emph-re (var val)
3677 "Set variable and compute the emphasis regular expression."
3678 (set var val)
3679 (when (and (boundp 'org-emphasis-alist)
3680 (boundp 'org-emphasis-regexp-components)
3681 org-emphasis-alist org-emphasis-regexp-components)
3682 (let* ((e org-emphasis-regexp-components)
3683 (pre (car e))
3684 (post (nth 1 e))
3685 (border (nth 2 e))
3686 (body (nth 3 e))
3687 (nl (nth 4 e))
3688 (body1 (concat body "*?"))
3689 (markers (mapconcat 'car org-emphasis-alist ""))
3690 (vmarkers (mapconcat
3691 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3692 org-emphasis-alist "")))
3693 ;; make sure special characters appear at the right position in the class
3694 (if (string-match "\\^" markers)
3695 (setq markers (concat (replace-match "" t t markers) "^")))
3696 (if (string-match "-" markers)
3697 (setq markers (concat (replace-match "" t t markers) "-")))
3698 (if (string-match "\\^" vmarkers)
3699 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3700 (if (string-match "-" vmarkers)
3701 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3702 (if (> nl 0)
3703 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3704 (int-to-string nl) "\\}")))
3705 ;; Make the regexp
3706 (setq org-emph-re
3707 (concat "\\([" pre "]\\|^\\)"
3708 "\\("
3709 "\\([" markers "]\\)"
3710 "\\("
3711 "[^" border "]\\|"
3712 "[^" border "]"
3713 body1
3714 "[^" border "]"
3715 "\\)"
3716 "\\3\\)"
3717 "\\([" post "]\\|$\\)"))
3718 (setq org-verbatim-re
3719 (concat "\\([" pre "]\\|^\\)"
3720 "\\("
3721 "\\([" vmarkers "]\\)"
3722 "\\("
3723 "[^" border "]\\|"
3724 "[^" border "]"
3725 body1
3726 "[^" border "]"
3727 "\\)"
3728 "\\3\\)"
3729 "\\([" post "]\\|$\\)")))))
3731 (defcustom org-emphasis-regexp-components
3732 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3733 "Components used to build the regular expression for emphasis.
3734 This is a list with five entries. Terminology: In an emphasis string
3735 like \" *strong word* \", we call the initial space PREMATCH, the final
3736 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3737 and \"trong wor\" is the body. The different components in this variable
3738 specify what is allowed/forbidden in each part:
3740 pre Chars allowed as prematch. Beginning of line will be allowed too.
3741 post Chars allowed as postmatch. End of line will be allowed too.
3742 border The chars *forbidden* as border characters.
3743 body-regexp A regexp like \".\" to match a body character. Don't use
3744 non-shy groups here, and don't allow newline here.
3745 newline The maximum number of newlines allowed in an emphasis exp.
3747 Use customize to modify this, or restart Emacs after changing it."
3748 :group 'org-appearance
3749 :set 'org-set-emph-re
3750 :type '(list
3751 (sexp :tag "Allowed chars in pre ")
3752 (sexp :tag "Allowed chars in post ")
3753 (sexp :tag "Forbidden chars in border ")
3754 (sexp :tag "Regexp for body ")
3755 (integer :tag "number of newlines allowed")
3756 (option (boolean :tag "Please ignore this button"))))
3758 (defcustom org-emphasis-alist
3759 `(("*" bold "<b>" "</b>")
3760 ("/" italic "<i>" "</i>")
3761 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3762 ("=" org-code "<code>" "</code>" verbatim)
3763 ("~" org-verbatim "<code>" "</code>" verbatim)
3764 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3765 "<del>" "</del>")
3767 "Special syntax for emphasized text.
3768 Text starting and ending with a special character will be emphasized, for
3769 example *bold*, _underlined_ and /italic/. This variable sets the marker
3770 characters, the face to be used by font-lock for highlighting in Org-mode
3771 Emacs buffers, and the HTML tags to be used for this.
3772 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3773 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3774 Use customize to modify this, or restart Emacs after changing it."
3775 :group 'org-appearance
3776 :set 'org-set-emph-re
3777 :type '(repeat
3778 (list
3779 (string :tag "Marker character")
3780 (choice
3781 (face :tag "Font-lock-face")
3782 (plist :tag "Face property list"))
3783 (string :tag "HTML start tag")
3784 (string :tag "HTML end tag")
3785 (option (const verbatim)))))
3787 (defvar org-protecting-blocks
3788 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3789 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3790 This is needed for font-lock setup.")
3792 ;;; Miscellaneous options
3794 (defgroup org-completion nil
3795 "Completion in Org-mode."
3796 :tag "Org Completion"
3797 :group 'org)
3799 (defcustom org-completion-use-ido nil
3800 "Non-nil means use ido completion wherever possible.
3801 Note that `ido-mode' must be active for this variable to be relevant.
3802 If you decide to turn this variable on, you might well want to turn off
3803 `org-outline-path-complete-in-steps'.
3804 See also `org-completion-use-iswitchb'."
3805 :group 'org-completion
3806 :type 'boolean)
3808 (defcustom org-completion-use-iswitchb nil
3809 "Non-nil means use iswitchb completion wherever possible.
3810 Note that `iswitchb-mode' must be active for this variable to be relevant.
3811 If you decide to turn this variable on, you might well want to turn off
3812 `org-outline-path-complete-in-steps'.
3813 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3814 :group 'org-completion
3815 :type 'boolean)
3817 (defcustom org-completion-fallback-command 'hippie-expand
3818 "The expansion command called by \\[pcomplete] in normal context.
3819 Normal means, no org-mode-specific context."
3820 :group 'org-completion
3821 :type 'function)
3823 ;;; Functions and variables from their packages
3824 ;; Declared here to avoid compiler warnings
3826 ;; XEmacs only
3827 (defvar outline-mode-menu-heading)
3828 (defvar outline-mode-menu-show)
3829 (defvar outline-mode-menu-hide)
3830 (defvar zmacs-regions) ; XEmacs regions
3832 ;; Emacs only
3833 (defvar mark-active)
3835 ;; Various packages
3836 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3837 (declare-function calendar-forward-day "cal-move" (arg))
3838 (declare-function calendar-goto-date "cal-move" (date))
3839 (declare-function calendar-goto-today "cal-move" ())
3840 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3841 (defvar calc-embedded-close-formula)
3842 (defvar calc-embedded-open-formula)
3843 (declare-function cdlatex-tab "ext:cdlatex" ())
3844 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3845 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3846 (defvar font-lock-unfontify-region-function)
3847 (declare-function iswitchb-read-buffer "iswitchb"
3848 (prompt &optional default require-match start matches-set))
3849 (defvar iswitchb-temp-buflist)
3850 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3851 (defvar org-agenda-tags-todo-honor-ignore-options)
3852 (declare-function org-agenda-skip "org-agenda" ())
3853 (declare-function
3854 org-agenda-format-item "org-agenda"
3855 (extra txt &optional category tags dotime noprefix remove-re habitp))
3856 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3857 (declare-function org-agenda-change-all-lines "org-agenda"
3858 (newhead hdmarker &optional fixface just-this))
3859 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3860 (declare-function org-agenda-maybe-redo "org-agenda" ())
3861 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3862 (beg end))
3863 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3864 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3865 "org-agenda" (&optional end))
3866 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3867 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3868 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3869 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3870 (declare-function org-indent-mode "org-indent" (&optional arg))
3871 (declare-function parse-time-string "parse-time" (string))
3872 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3873 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3874 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3875 (defvar remember-data-file)
3876 (defvar texmathp-why)
3877 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3878 (declare-function table--at-cell-p "table" (position &optional object at-column))
3880 (defvar w3m-current-url)
3881 (defvar w3m-current-title)
3883 (defvar org-latex-regexps)
3885 ;;; Autoload and prepare some org modules
3887 ;; Some table stuff that needs to be defined here, because it is used
3888 ;; by the functions setting up org-mode or checking for table context.
3890 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3891 "Detect an org-type or table-type table.")
3892 (defconst org-table-line-regexp "^[ \t]*|"
3893 "Detect an org-type table line.")
3894 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3895 "Detect an org-type table line.")
3896 (defconst org-table-hline-regexp "^[ \t]*|-"
3897 "Detect an org-type table hline.")
3898 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3899 "Detect a table-type table hline.")
3900 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3901 "Detect the first line outside a table when searching from within it.
3902 This works for both table types.")
3904 ;; Autoload the functions in org-table.el that are needed by functions here.
3906 (eval-and-compile
3907 (org-autoload "org-table"
3908 '(org-table-align org-table-begin org-table-blank-field
3909 org-table-convert org-table-convert-region org-table-copy-down
3910 org-table-copy-region org-table-create
3911 org-table-create-or-convert-from-region
3912 org-table-create-with-table.el org-table-current-dline
3913 org-table-cut-region org-table-delete-column org-table-edit-field
3914 org-table-edit-formulas org-table-end org-table-eval-formula
3915 org-table-export org-table-field-info
3916 org-table-get-stored-formulas org-table-goto-column
3917 org-table-hline-and-move org-table-import org-table-insert-column
3918 org-table-insert-hline org-table-insert-row org-table-iterate
3919 org-table-justify-field-maybe org-table-kill-row
3920 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3921 org-table-move-column org-table-move-column-left
3922 org-table-move-column-right org-table-move-row
3923 org-table-move-row-down org-table-move-row-up
3924 org-table-next-field org-table-next-row org-table-paste-rectangle
3925 org-table-previous-field org-table-recalculate
3926 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3927 org-table-toggle-coordinate-overlays
3928 org-table-toggle-formula-debugger org-table-wrap-region
3929 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3930 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3931 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3933 (defun org-at-table-p (&optional table-type)
3934 "Return t if the cursor is inside an org-type table.
3935 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3936 (if org-enable-table-editor
3937 (save-excursion
3938 (beginning-of-line 1)
3939 (looking-at (if table-type org-table-any-line-regexp
3940 org-table-line-regexp)))
3941 nil))
3942 (defsubst org-table-p () (org-at-table-p))
3944 (defun org-at-table.el-p ()
3945 "Return t if and only if we are at a table.el table."
3946 (and (org-at-table-p 'any)
3947 (save-excursion
3948 (goto-char (org-table-begin 'any))
3949 (looking-at org-table1-hline-regexp))))
3950 (defun org-table-recognize-table.el ()
3951 "If there is a table.el table nearby, recognize it and move into it."
3952 (if org-table-tab-recognizes-table.el
3953 (if (org-at-table.el-p)
3954 (progn
3955 (beginning-of-line 1)
3956 (if (looking-at org-table-dataline-regexp)
3958 (if (looking-at org-table1-hline-regexp)
3959 (progn
3960 (beginning-of-line 2)
3961 (if (looking-at org-table-any-border-regexp)
3962 (beginning-of-line -1)))))
3963 (if (re-search-forward "|" (org-table-end t) t)
3964 (progn
3965 (require 'table)
3966 (if (table--at-cell-p (point))
3968 (message "recognizing table.el table...")
3969 (table-recognize-table)
3970 (message "recognizing table.el table...done")))
3971 (error "This should not happen"))
3973 nil)
3974 nil))
3976 (defun org-at-table-hline-p ()
3977 "Return t if the cursor is inside a hline in a table."
3978 (if org-enable-table-editor
3979 (save-excursion
3980 (beginning-of-line 1)
3981 (looking-at org-table-hline-regexp))
3982 nil))
3984 (defvar org-table-clean-did-remove-column nil)
3986 (defun org-table-map-tables (function &optional quietly)
3987 "Apply FUNCTION to the start of all tables in the buffer."
3988 (save-excursion
3989 (save-restriction
3990 (widen)
3991 (goto-char (point-min))
3992 (while (re-search-forward org-table-any-line-regexp nil t)
3993 (unless quietly
3994 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3995 (beginning-of-line 1)
3996 (when (and (looking-at org-table-line-regexp)
3997 ;; Exclude tables in src/example/verbatim/clocktable blocks
3998 (not (org-in-block-p '("src" "example"))))
3999 (save-excursion (funcall function))
4000 (or (looking-at org-table-line-regexp)
4001 (forward-char 1)))
4002 (re-search-forward org-table-any-border-regexp nil 1))))
4003 (unless quietly (message "Mapping tables: done")))
4005 ;; Declare and autoload functions from org-exp.el & Co
4007 (declare-function org-default-export-plist "org-exp")
4008 (declare-function org-infile-export-plist "org-exp")
4009 (declare-function org-get-current-options "org-exp")
4010 (eval-and-compile
4011 (org-autoload "org-exp"
4012 '(org-export org-export-visible
4013 org-insert-export-options-template
4014 org-table-clean-before-export))
4015 (org-autoload "org-ascii"
4016 '(org-export-as-ascii org-export-ascii-preprocess
4017 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4018 org-export-region-as-ascii))
4019 (org-autoload "org-latex"
4020 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4021 org-replace-region-by-latex org-export-region-as-latex
4022 org-export-as-latex org-export-as-pdf
4023 org-export-as-pdf-and-open))
4024 (org-autoload "org-html"
4025 '(org-export-as-html-and-open
4026 org-export-as-html-batch org-export-as-html-to-buffer
4027 org-replace-region-by-html org-export-region-as-html
4028 org-export-as-html))
4029 (org-autoload "org-docbook"
4030 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4031 org-replace-region-by-docbook org-export-region-as-docbook
4032 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4033 org-export-as-docbook))
4034 (org-autoload "org-icalendar"
4035 '(org-export-icalendar-this-file
4036 org-export-icalendar-all-agenda-files
4037 org-export-icalendar-combine-agenda-files))
4038 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4039 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4041 ;; Declare and autoload functions from org-agenda.el
4043 (eval-and-compile
4044 (org-autoload "org-agenda"
4045 '(org-agenda org-agenda-list org-search-view
4046 org-todo-list org-tags-view org-agenda-list-stuck-projects
4047 org-diary org-agenda-to-appt
4048 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4050 ;; Autoload org-remember
4052 (eval-and-compile
4053 (org-autoload "org-remember"
4054 '(org-remember-insinuate org-remember-annotation
4055 org-remember-apply-template org-remember org-remember-handler)))
4057 (eval-and-compile
4058 (org-autoload "org-capture"
4059 '(org-capture org-capture-insert-template-here
4060 org-capture-import-remember-templates)))
4062 ;; Autoload org-clock.el
4064 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4065 (beg end))
4066 (declare-function org-clock-update-mode-line "org-clock" ())
4067 (declare-function org-resolve-clocks "org-clock"
4068 (&optional also-non-dangling-p prompt last-valid))
4069 (defvar org-clock-start-time)
4070 (defvar org-clock-marker (make-marker)
4071 "Marker recording the last clock-in.")
4072 (defvar org-clock-hd-marker (make-marker)
4073 "Marker recording the last clock-in, but the headline position.")
4074 (defvar org-clock-heading ""
4075 "The heading of the current clock entry.")
4076 (defun org-clock-is-active ()
4077 "Return non-nil if clock is currently running.
4078 The return value is actually the clock marker."
4079 (marker-buffer org-clock-marker))
4081 (eval-and-compile
4082 (org-autoload
4083 "org-clock"
4084 '(org-clock-in org-clock-out org-clock-cancel
4085 org-clock-goto org-clock-sum org-clock-display
4086 org-clock-remove-overlays org-clock-report
4087 org-clocktable-shift org-dblock-write:clocktable
4088 org-get-clocktable org-resolve-clocks)))
4090 (defun org-clock-update-time-maybe ()
4091 "If this is a CLOCK line, update it and return t.
4092 Otherwise, return nil."
4093 (interactive)
4094 (save-excursion
4095 (beginning-of-line 1)
4096 (skip-chars-forward " \t")
4097 (when (looking-at org-clock-string)
4098 (let ((re (concat "[ \t]*" org-clock-string
4099 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4100 "\\([ \t]*=>.*\\)?\\)?"))
4101 ts te h m s neg)
4102 (cond
4103 ((not (looking-at re))
4104 nil)
4105 ((not (match-end 2))
4106 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4107 (> org-clock-marker (point))
4108 (<= org-clock-marker (point-at-eol)))
4109 ;; The clock is running here
4110 (setq org-clock-start-time
4111 (apply 'encode-time
4112 (org-parse-time-string (match-string 1))))
4113 (org-clock-update-mode-line)))
4115 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4116 (end-of-line 1)
4117 (setq ts (match-string 1)
4118 te (match-string 3))
4119 (setq s (- (org-float-time
4120 (apply 'encode-time (org-parse-time-string te)))
4121 (org-float-time
4122 (apply 'encode-time (org-parse-time-string ts))))
4123 neg (< s 0)
4124 s (abs s)
4125 h (floor (/ s 3600))
4126 s (- s (* 3600 h))
4127 m (floor (/ s 60))
4128 s (- s (* 60 s)))
4129 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4130 t))))))
4132 (defun org-check-running-clock ()
4133 "Check if the current buffer contains the running clock.
4134 If yes, offer to stop it and to save the buffer with the changes."
4135 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4136 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4137 (buffer-name))))
4138 (org-clock-out)
4139 (when (y-or-n-p "Save changed buffer?")
4140 (save-buffer))))
4142 (defun org-clocktable-try-shift (dir n)
4143 "Check if this line starts a clock table, if yes, shift the time block."
4144 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4145 (org-clocktable-shift dir n)))
4147 ;; Autoload org-timer.el
4149 (eval-and-compile
4150 (org-autoload
4151 "org-timer"
4152 '(org-timer-start org-timer org-timer-item
4153 org-timer-change-times-in-region
4154 org-timer-set-timer
4155 org-timer-reset-timers
4156 org-timer-show-remaining-time)))
4158 ;; Autoload org-feed.el
4160 (eval-and-compile
4161 (org-autoload
4162 "org-feed"
4163 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4166 ;; Autoload org-indent.el
4168 ;; Define the variable already here, to make sure we have it.
4169 (defvar org-indent-mode nil
4170 "Non-nil if Org-Indent mode is enabled.
4171 Use the command `org-indent-mode' to change this variable.")
4173 (eval-and-compile
4174 (org-autoload
4175 "org-indent"
4176 '(org-indent-mode)))
4178 ;; Autoload org-mobile.el
4180 (eval-and-compile
4181 (org-autoload
4182 "org-mobile"
4183 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4185 ;; Autoload archiving code
4186 ;; The stuff that is needed for cycling and tags has to be defined here.
4188 (defgroup org-archive nil
4189 "Options concerning archiving in Org-mode."
4190 :tag "Org Archive"
4191 :group 'org-structure)
4193 (defcustom org-archive-location "%s_archive::"
4194 "The location where subtrees should be archived.
4196 The value of this variable is a string, consisting of two parts,
4197 separated by a double-colon. The first part is a filename and
4198 the second part is a headline.
4200 When the filename is omitted, archiving happens in the same file.
4201 %s in the filename will be replaced by the current file
4202 name (without the directory part). Archiving to a different file
4203 is useful to keep archived entries from contributing to the
4204 Org-mode Agenda.
4206 The archived entries will be filed as subtrees of the specified
4207 headline. When the headline is omitted, the subtrees are simply
4208 filed away at the end of the file, as top-level entries. Also in
4209 the heading you can use %s to represent the file name, this can be
4210 useful when using the same archive for a number of different files.
4212 Here are a few examples:
4213 \"%s_archive::\"
4214 If the current file is Projects.org, archive in file
4215 Projects.org_archive, as top-level trees. This is the default.
4217 \"::* Archived Tasks\"
4218 Archive in the current file, under the top-level headline
4219 \"* Archived Tasks\".
4221 \"~/org/archive.org::\"
4222 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4224 \"~/org/archive.org::* From %s\"
4225 Archive in file ~/org/archive.org (absolute path), under headlines
4226 \"From FILENAME\" where file name is the current file name.
4228 \"~/org/datetree.org::datetree/* Finished Tasks\"
4229 The \"datetree/\" string is special, signifying to archive
4230 items to the datetree. Items are placed in either the CLOSED
4231 date of the item, or the current date if there is no CLOSED date.
4232 The heading will be a subentry to the current date. There doesn't
4233 need to be a heading, but there always needs to be a slash after
4234 datetree. For example, to store archived items directly in the
4235 datetree, use \"~/org/datetree.org::datetree/\".
4237 \"basement::** Finished Tasks\"
4238 Archive in file ./basement (relative path), as level 3 trees
4239 below the level 2 heading \"** Finished Tasks\".
4241 You may set this option on a per-file basis by adding to the buffer a
4242 line like
4244 #+ARCHIVE: basement::** Finished Tasks
4246 You may also define it locally for a subtree by setting an ARCHIVE property
4247 in the entry. If such a property is found in an entry, or anywhere up
4248 the hierarchy, it will be used."
4249 :group 'org-archive
4250 :type 'string)
4252 (defcustom org-archive-tag "ARCHIVE"
4253 "The tag that marks a subtree as archived.
4254 An archived subtree does not open during visibility cycling, and does
4255 not contribute to the agenda listings.
4256 After changing this, font-lock must be restarted in the relevant buffers to
4257 get the proper fontification."
4258 :group 'org-archive
4259 :group 'org-keywords
4260 :type 'string)
4262 (defcustom org-agenda-skip-archived-trees t
4263 "Non-nil means the agenda will skip any items located in archived trees.
4264 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4265 variable is no longer recommended, you should leave it at the value t.
4266 Instead, use the key `v' to cycle the archives-mode in the agenda."
4267 :group 'org-archive
4268 :group 'org-agenda-skip
4269 :type 'boolean)
4271 (defcustom org-columns-skip-archived-trees t
4272 "Non-nil means ignore archived trees when creating column view."
4273 :group 'org-archive
4274 :group 'org-properties
4275 :type 'boolean)
4277 (defcustom org-cycle-open-archived-trees nil
4278 "Non-nil means `org-cycle' will open archived trees.
4279 An archived tree is a tree marked with the tag ARCHIVE.
4280 When nil, archived trees will stay folded. You can still open them with
4281 normal outline commands like `show-all', but not with the cycling commands."
4282 :group 'org-archive
4283 :group 'org-cycle
4284 :type 'boolean)
4286 (defcustom org-sparse-tree-open-archived-trees nil
4287 "Non-nil means sparse tree construction shows matches in archived trees.
4288 When nil, matches in these trees are highlighted, but the trees are kept in
4289 collapsed state."
4290 :group 'org-archive
4291 :group 'org-sparse-trees
4292 :type 'boolean)
4294 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4295 "The default date type when building a sparse tree.
4296 When this is nil, a date is a scheduled or a deadline timestamp.
4297 Otherwise, these types are allowed:
4299 all: all timestamps
4300 active: only active timestamps (<...>)
4301 inactive: only inactive timestamps (<...)
4302 scheduled: only scheduled timestamps
4303 deadline: only deadline timestamps"
4304 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4305 (const :tag "All timestamps" all)
4306 (const :tag "Only active timestamps" active)
4307 (const :tag "Only inactive timestamps" inactive)
4308 (const :tag "Only scheduled timestamps" scheduled)
4309 (const :tag "Only deadline timestamps" deadline))
4310 ;; :version "24.3"
4311 :group 'org-sparse-trees)
4313 (defun org-cycle-hide-archived-subtrees (state)
4314 "Re-hide all archived subtrees after a visibility state change."
4315 (when (and (not org-cycle-open-archived-trees)
4316 (not (memq state '(overview folded))))
4317 (save-excursion
4318 (let* ((globalp (memq state '(contents all)))
4319 (beg (if globalp (point-min) (point)))
4320 (end (if globalp (point-max) (org-end-of-subtree t))))
4321 (org-hide-archived-subtrees beg end)
4322 (goto-char beg)
4323 (if (looking-at (concat ".*:" org-archive-tag ":"))
4324 (message "%s" (substitute-command-keys
4325 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4327 (defun org-force-cycle-archived ()
4328 "Cycle subtree even if it is archived."
4329 (interactive)
4330 (setq this-command 'org-cycle)
4331 (let ((org-cycle-open-archived-trees t))
4332 (call-interactively 'org-cycle)))
4334 (defun org-hide-archived-subtrees (beg end)
4335 "Re-hide all archived subtrees after a visibility state change."
4336 (save-excursion
4337 (let* ((re (concat ":" org-archive-tag ":")))
4338 (goto-char beg)
4339 (while (re-search-forward re end t)
4340 (when (org-at-heading-p)
4341 (org-flag-subtree t)
4342 (org-end-of-subtree t))))))
4344 (declare-function outline-end-of-heading "outline" ())
4345 (declare-function outline-flag-region "outline" (from to flag))
4346 (defun org-flag-subtree (flag)
4347 (save-excursion
4348 (org-back-to-heading t)
4349 (outline-end-of-heading)
4350 (outline-flag-region (point)
4351 (progn (org-end-of-subtree t) (point))
4352 flag)))
4354 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4356 (eval-and-compile
4357 (org-autoload "org-archive"
4358 '(org-add-archive-files org-archive-subtree
4359 org-archive-to-archive-sibling org-toggle-archive-tag
4360 org-archive-subtree-default
4361 org-archive-subtree-default-with-confirmation)))
4363 ;; Autoload Column View Code
4365 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4366 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4367 (declare-function org-columns-compute "org-colview" (property))
4369 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4370 '(org-columns-number-to-string org-columns-get-format-and-top-level
4371 org-columns-compute org-agenda-columns org-columns-remove-overlays
4372 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4374 ;; Autoload ID code
4376 (declare-function org-id-store-link "org-id")
4377 (declare-function org-id-locations-load "org-id")
4378 (declare-function org-id-locations-save "org-id")
4379 (defvar org-id-track-globally)
4380 (org-autoload "org-id"
4381 '(org-id-get-create org-id-new org-id-copy org-id-get
4382 org-id-get-with-outline-path-completion
4383 org-id-get-with-outline-drilling org-id-store-link
4384 org-id-goto org-id-find org-id-store-link))
4386 ;; Autoload Plotting Code
4388 (org-autoload "org-plot"
4389 '(org-plot/gnuplot))
4391 ;;; Variables for pre-computed regular expressions, all buffer local
4393 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4394 "Matches first line of a hidden block.")
4395 (make-variable-buffer-local 'org-drawer-regexp)
4396 (defvar org-todo-regexp nil
4397 "Matches any of the TODO state keywords.")
4398 (make-variable-buffer-local 'org-todo-regexp)
4399 (defvar org-not-done-regexp nil
4400 "Matches any of the TODO state keywords except the last one.")
4401 (make-variable-buffer-local 'org-not-done-regexp)
4402 (defvar org-not-done-heading-regexp nil
4403 "Matches a TODO headline that is not done.")
4404 (make-variable-buffer-local 'org-not-done-regexp)
4405 (defvar org-todo-line-regexp nil
4406 "Matches a headline and puts TODO state into group 2 if present.")
4407 (make-variable-buffer-local 'org-todo-line-regexp)
4408 (defvar org-complex-heading-regexp nil
4409 "Matches a headline and puts everything into groups:
4410 group 1: the stars
4411 group 2: The todo keyword, maybe
4412 group 3: Priority cookie
4413 group 4: True headline
4414 group 5: Tags")
4415 (make-variable-buffer-local 'org-complex-heading-regexp)
4416 (defvar org-complex-heading-regexp-format nil
4417 "Printf format to make regexp to match an exact headline.
4418 This regexp will match the headline of any node which has the
4419 exact headline text that is put into the format, but may have any
4420 TODO state, priority and tags.")
4421 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4422 (defvar org-todo-line-tags-regexp nil
4423 "Matches a headline and puts TODO state into group 2 if present.
4424 Also put tags into group 4 if tags are present.")
4425 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4426 (defvar org-ds-keyword-length 12
4427 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4428 (make-variable-buffer-local 'org-ds-keyword-length)
4429 (defvar org-deadline-regexp nil
4430 "Matches the DEADLINE keyword.")
4431 (make-variable-buffer-local 'org-deadline-regexp)
4432 (defvar org-deadline-time-regexp nil
4433 "Matches the DEADLINE keyword together with a time stamp.")
4434 (make-variable-buffer-local 'org-deadline-time-regexp)
4435 (defvar org-deadline-line-regexp nil
4436 "Matches the DEADLINE keyword and the rest of the line.")
4437 (make-variable-buffer-local 'org-deadline-line-regexp)
4438 (defvar org-scheduled-regexp nil
4439 "Matches the SCHEDULED keyword.")
4440 (make-variable-buffer-local 'org-scheduled-regexp)
4441 (defvar org-scheduled-time-regexp nil
4442 "Matches the SCHEDULED keyword together with a time stamp.")
4443 (make-variable-buffer-local 'org-scheduled-time-regexp)
4444 (defvar org-closed-time-regexp nil
4445 "Matches the CLOSED keyword together with a time stamp.")
4446 (make-variable-buffer-local 'org-closed-time-regexp)
4448 (defvar org-keyword-time-regexp nil
4449 "Matches any of the 4 keywords, together with the time stamp.")
4450 (make-variable-buffer-local 'org-keyword-time-regexp)
4451 (defvar org-keyword-time-not-clock-regexp nil
4452 "Matches any of the 3 keywords, together with the time stamp.")
4453 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4454 (defvar org-maybe-keyword-time-regexp nil
4455 "Matches a timestamp, possibly preceded by a keyword.")
4456 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4457 (defvar org-all-time-keywords nil
4458 "List of time keywords.")
4459 (make-variable-buffer-local 'org-all-time-keywords)
4461 (defconst org-plain-time-of-day-regexp
4462 (concat
4463 "\\(\\<[012]?[0-9]"
4464 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4465 "\\(--?"
4466 "\\(\\<[012]?[0-9]"
4467 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4468 "\\)?")
4469 "Regular expression to match a plain time or time range.
4470 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4471 groups carry important information:
4472 0 the full match
4473 1 the first time, range or not
4474 8 the second time, if it is a range.")
4476 (defconst org-plain-time-extension-regexp
4477 (concat
4478 "\\(\\<[012]?[0-9]"
4479 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4480 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4481 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4482 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4483 groups carry important information:
4484 0 the full match
4485 7 hours of duration
4486 9 minutes of duration")
4488 (defconst org-stamp-time-of-day-regexp
4489 (concat
4490 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4491 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4492 "\\(--?"
4493 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4494 "Regular expression to match a timestamp time or time range.
4495 After a match, the following groups carry important information:
4496 0 the full match
4497 1 date plus weekday, for back referencing to make sure both times are on the same day
4498 2 the first time, range or not
4499 4 the second time, if it is a range.")
4501 (defconst org-startup-options
4502 '(("fold" org-startup-folded t)
4503 ("overview" org-startup-folded t)
4504 ("nofold" org-startup-folded nil)
4505 ("showall" org-startup-folded nil)
4506 ("showeverything" org-startup-folded showeverything)
4507 ("content" org-startup-folded content)
4508 ("indent" org-startup-indented t)
4509 ("noindent" org-startup-indented nil)
4510 ("hidestars" org-hide-leading-stars t)
4511 ("showstars" org-hide-leading-stars nil)
4512 ("odd" org-odd-levels-only t)
4513 ("oddeven" org-odd-levels-only nil)
4514 ("align" org-startup-align-all-tables t)
4515 ("noalign" org-startup-align-all-tables nil)
4516 ("inlineimages" org-startup-with-inline-images t)
4517 ("noinlineimages" org-startup-with-inline-images nil)
4518 ("customtime" org-display-custom-times t)
4519 ("logdone" org-log-done time)
4520 ("lognotedone" org-log-done note)
4521 ("nologdone" org-log-done nil)
4522 ("lognoteclock-out" org-log-note-clock-out t)
4523 ("nolognoteclock-out" org-log-note-clock-out nil)
4524 ("logrepeat" org-log-repeat state)
4525 ("lognoterepeat" org-log-repeat note)
4526 ("nologrepeat" org-log-repeat nil)
4527 ("logreschedule" org-log-reschedule time)
4528 ("lognotereschedule" org-log-reschedule note)
4529 ("nologreschedule" org-log-reschedule nil)
4530 ("logredeadline" org-log-redeadline time)
4531 ("lognoteredeadline" org-log-redeadline note)
4532 ("nologredeadline" org-log-redeadline nil)
4533 ("logrefile" org-log-refile time)
4534 ("lognoterefile" org-log-refile note)
4535 ("nologrefile" org-log-refile nil)
4536 ("fninline" org-footnote-define-inline t)
4537 ("nofninline" org-footnote-define-inline nil)
4538 ("fnlocal" org-footnote-section nil)
4539 ("fnauto" org-footnote-auto-label t)
4540 ("fnprompt" org-footnote-auto-label nil)
4541 ("fnconfirm" org-footnote-auto-label confirm)
4542 ("fnplain" org-footnote-auto-label plain)
4543 ("fnadjust" org-footnote-auto-adjust t)
4544 ("nofnadjust" org-footnote-auto-adjust nil)
4545 ("constcgs" constants-unit-system cgs)
4546 ("constSI" constants-unit-system SI)
4547 ("noptag" org-tag-persistent-alist nil)
4548 ("hideblocks" org-hide-block-startup t)
4549 ("nohideblocks" org-hide-block-startup nil)
4550 ("beamer" org-startup-with-beamer-mode t)
4551 ("entitiespretty" org-pretty-entities t)
4552 ("entitiesplain" org-pretty-entities nil))
4553 "Variable associated with STARTUP options for org-mode.
4554 Each element is a list of three items: the startup options (as written
4555 in the #+STARTUP line), the corresponding variable, and the value to set
4556 this variable to if the option is found. An optional forth element PUSH
4557 means to push this value onto the list in the variable.")
4559 (defun org-update-property-plist (key val props)
4560 "Update PROPS with KEY and VAL."
4561 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4562 (key (if appending (substring key 0 (- (length key) 1)) key))
4563 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4564 (previous (cdr (assoc key props))))
4565 (if appending
4566 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4567 (cons (cons key val) remainder))))
4569 (defconst org-block-regexp
4570 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4571 "Regular expression for hiding blocks.")
4572 (defconst org-heading-keyword-regexp-format
4573 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4574 "Printf format for a regexp matching an headline with some keyword.
4575 This regexp will match the headline of any node which has the
4576 exact keyword that is put into the format. The keyword isn't in
4577 any group by default, but the stars and the body are.")
4578 (defconst org-heading-keyword-maybe-regexp-format
4579 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4580 "Printf format for a regexp matching an headline, possibly with some keyword.
4581 This regexp can match any headline with the specified keyword, or
4582 without a keyword. The keyword isn't in any group by default,
4583 but the stars and the body are.")
4585 (defun org-set-regexps-and-options ()
4586 "Precompute regular expressions for current buffer."
4587 (when (derived-mode-p 'org-mode)
4588 (org-set-local 'org-todo-kwd-alist nil)
4589 (org-set-local 'org-todo-key-alist nil)
4590 (org-set-local 'org-todo-key-trigger nil)
4591 (org-set-local 'org-todo-keywords-1 nil)
4592 (org-set-local 'org-done-keywords nil)
4593 (org-set-local 'org-todo-heads nil)
4594 (org-set-local 'org-todo-sets nil)
4595 (org-set-local 'org-todo-log-states nil)
4596 (org-set-local 'org-file-properties nil)
4597 (org-set-local 'org-file-tags nil)
4598 (let ((re (org-make-options-regexp
4599 '("CATEGORY" "TODO" "COLUMNS"
4600 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4601 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4602 "OPTIONS")
4603 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4604 (splitre "[ \t]+")
4605 (scripts org-use-sub-superscripts)
4606 kwds kws0 kwsa key log value cat arch tags const links hw dws
4607 tail sep kws1 prio props ftags drawers beamer-p
4608 ext-setup-or-nil setup-contents (start 0))
4609 (save-excursion
4610 (save-restriction
4611 (widen)
4612 (goto-char (point-min))
4613 (while (or (and ext-setup-or-nil
4614 (string-match re ext-setup-or-nil start)
4615 (setq start (match-end 0)))
4616 (and (setq ext-setup-or-nil nil start 0)
4617 (re-search-forward re nil t)))
4618 (setq key (upcase (match-string 1 ext-setup-or-nil))
4619 value (org-match-string-no-properties 2 ext-setup-or-nil))
4620 (if (stringp value) (setq value (org-trim value)))
4621 (cond
4622 ((equal key "CATEGORY")
4623 (setq cat value))
4624 ((member key '("SEQ_TODO" "TODO"))
4625 (push (cons 'sequence (org-split-string value splitre)) kwds))
4626 ((equal key "TYP_TODO")
4627 (push (cons 'type (org-split-string value splitre)) kwds))
4628 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4629 ;; general TODO-like setup
4630 (push (cons (intern (downcase (match-string 1 key)))
4631 (org-split-string value splitre)) kwds))
4632 ((equal key "TAGS")
4633 (setq tags (append tags (if tags '("\\n") nil)
4634 (org-split-string value splitre))))
4635 ((equal key "COLUMNS")
4636 (org-set-local 'org-columns-default-format value))
4637 ((equal key "LINK")
4638 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4639 (push (cons (match-string 1 value)
4640 (org-trim (match-string 2 value)))
4641 links)))
4642 ((equal key "PRIORITIES")
4643 (setq prio (org-split-string value " +")))
4644 ((equal key "PROPERTY")
4645 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4646 (setq props (org-update-property-plist (match-string 1 value)
4647 (match-string 2 value)
4648 props))))
4649 ((equal key "FILETAGS")
4650 (when (string-match "\\S-" value)
4651 (setq ftags
4652 (append
4653 ftags
4654 (apply 'append
4655 (mapcar (lambda (x) (org-split-string x ":"))
4656 (org-split-string value)))))))
4657 ((equal key "DRAWERS")
4658 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4659 ((equal key "CONSTANTS")
4660 (setq const (append const (org-split-string value splitre))))
4661 ((equal key "STARTUP")
4662 (let ((opts (org-split-string value splitre))
4663 l var val)
4664 (while (setq l (pop opts))
4665 (when (setq l (assoc l org-startup-options))
4666 (setq var (nth 1 l) val (nth 2 l))
4667 (if (not (nth 3 l))
4668 (set (make-local-variable var) val)
4669 (if (not (listp (symbol-value var)))
4670 (set (make-local-variable var) nil))
4671 (set (make-local-variable var) (symbol-value var))
4672 (add-to-list var val))))))
4673 ((equal key "ARCHIVE")
4674 (setq arch value)
4675 (remove-text-properties 0 (length arch)
4676 '(face t fontified t) arch))
4677 ((equal key "LATEX_CLASS")
4678 (setq beamer-p (equal value "beamer")))
4679 ((equal key "OPTIONS")
4680 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4681 (setq scripts (read (match-string 2 value)))))
4682 ((equal key "SETUPFILE")
4683 (setq setup-contents (org-file-contents
4684 (expand-file-name
4685 (org-remove-double-quotes value))
4686 'noerror))
4687 (if (not ext-setup-or-nil)
4688 (setq ext-setup-or-nil setup-contents start 0)
4689 (setq ext-setup-or-nil
4690 (concat (substring ext-setup-or-nil 0 start)
4691 "\n" setup-contents "\n"
4692 (substring ext-setup-or-nil start)))))))
4693 ;; search for property blocks
4694 (goto-char (point-min))
4695 (while (re-search-forward org-block-regexp nil t)
4696 (when (equal "PROPERTY" (upcase (match-string 1)))
4697 (setq value (replace-regexp-in-string
4698 "[\n\r]" " " (match-string 4)))
4699 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4700 (setq props (org-update-property-plist (match-string 1 value)
4701 (match-string 2 value)
4702 props)))))))
4703 (org-set-local 'org-use-sub-superscripts scripts)
4704 (when cat
4705 (org-set-local 'org-category (intern cat))
4706 (push (cons "CATEGORY" cat) props))
4707 (when prio
4708 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4709 (setq prio (mapcar 'string-to-char prio))
4710 (org-set-local 'org-highest-priority (nth 0 prio))
4711 (org-set-local 'org-lowest-priority (nth 1 prio))
4712 (org-set-local 'org-default-priority (nth 2 prio)))
4713 (and props (org-set-local 'org-file-properties (nreverse props)))
4714 (and ftags (org-set-local 'org-file-tags
4715 (mapcar 'org-add-prop-inherited ftags)))
4716 (and drawers (org-set-local 'org-drawers drawers))
4717 (and arch (org-set-local 'org-archive-location arch))
4718 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4719 ;; Process the TODO keywords
4720 (unless kwds
4721 ;; Use the global values as if they had been given locally.
4722 (setq kwds (default-value 'org-todo-keywords))
4723 (if (stringp (car kwds))
4724 (setq kwds (list (cons org-todo-interpretation
4725 (default-value 'org-todo-keywords)))))
4726 (setq kwds (reverse kwds)))
4727 (setq kwds (nreverse kwds))
4728 (let (inter kws kw)
4729 (while (setq kws (pop kwds))
4730 (let ((kws (or
4731 (run-hook-with-args-until-success
4732 'org-todo-setup-filter-hook kws)
4733 kws)))
4734 (setq inter (pop kws) sep (member "|" kws)
4735 kws0 (delete "|" (copy-sequence kws))
4736 kwsa nil
4737 kws1 (mapcar
4738 (lambda (x)
4739 ;; 1 2
4740 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4741 (progn
4742 (setq kw (match-string 1 x)
4743 key (and (match-end 2) (match-string 2 x))
4744 log (org-extract-log-state-settings x))
4745 (push (cons kw (and key (string-to-char key))) kwsa)
4746 (and log (push log org-todo-log-states))
4748 (error "Invalid TODO keyword %s" x)))
4749 kws0)
4750 kwsa (if kwsa (append '((:startgroup))
4751 (nreverse kwsa)
4752 '((:endgroup))))
4753 hw (car kws1)
4754 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4755 tail (list inter hw (car dws) (org-last dws))))
4756 (add-to-list 'org-todo-heads hw 'append)
4757 (push kws1 org-todo-sets)
4758 (setq org-done-keywords (append org-done-keywords dws nil))
4759 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4760 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4761 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4762 (setq org-todo-sets (nreverse org-todo-sets)
4763 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4764 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4765 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4766 ;; Process the constants
4767 (when const
4768 (let (e cst)
4769 (while (setq e (pop const))
4770 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4771 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4772 (setq org-table-formula-constants-local cst)))
4774 ;; Process the tags.
4775 (when tags
4776 (let (e tgs)
4777 (while (setq e (pop tags))
4778 (cond
4779 ((equal e "{") (push '(:startgroup) tgs))
4780 ((equal e "}") (push '(:endgroup) tgs))
4781 ((equal e "\\n") (push '(:newline) tgs))
4782 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4783 (push (cons (match-string 1 e)
4784 (string-to-char (match-string 2 e)))
4785 tgs))
4786 (t (push (list e) tgs))))
4787 (org-set-local 'org-tag-alist nil)
4788 (while (setq e (pop tgs))
4789 (or (and (stringp (car e))
4790 (assoc (car e) org-tag-alist))
4791 (push e org-tag-alist)))))
4793 ;; Compute the regular expressions and other local variables.
4794 ;; Using `org-outline-regexp-bol' would complicate them much,
4795 ;; because of the fixed white space at the end of that string.
4796 (if (not org-done-keywords)
4797 (setq org-done-keywords (and org-todo-keywords-1
4798 (list (org-last org-todo-keywords-1)))))
4799 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4800 (length org-scheduled-string)
4801 (length org-clock-string)
4802 (length org-closed-string)))
4803 org-drawer-regexp
4804 (concat "^[ \t]*:\\("
4805 (mapconcat 'regexp-quote org-drawers "\\|")
4806 "\\):[ \t]*$")
4807 org-not-done-keywords
4808 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4809 org-todo-regexp
4810 (concat "\\("
4811 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4812 "\\)")
4813 org-not-done-regexp
4814 (concat "\\("
4815 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4816 "\\)")
4817 org-not-done-heading-regexp
4818 (format org-heading-keyword-regexp-format org-not-done-regexp)
4819 org-todo-line-regexp
4820 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4821 org-complex-heading-regexp
4822 (concat "^\\(\\*+\\)"
4823 "\\(?: +" org-todo-regexp "\\)?"
4824 "\\(?: +\\(\\[#.\\]\\)\\)?"
4825 "\\(?: +\\(.*?\\)\\)?"
4826 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4827 "[ \t]*$")
4828 org-complex-heading-regexp-format
4829 (concat "^\\(\\*+\\)"
4830 "\\(?: +" org-todo-regexp "\\)?"
4831 "\\(?: +\\(\\[#.\\]\\)\\)?"
4832 "\\(?: +"
4833 ;; Stats cookies can be stuck to body.
4834 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4835 "\\(%s\\)"
4836 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4837 "\\)"
4838 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4839 "[ \t]*$")
4840 org-todo-line-tags-regexp
4841 (concat "^\\(\\*+\\)"
4842 "\\(?: +" org-todo-regexp "\\)?"
4843 "\\(?: +\\(.*?\\)\\)?"
4844 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4845 "[ \t]*$")
4846 org-deadline-regexp (concat "\\<" org-deadline-string)
4847 org-deadline-time-regexp
4848 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4849 org-deadline-line-regexp
4850 (concat "\\<\\(" org-deadline-string "\\).*")
4851 org-scheduled-regexp
4852 (concat "\\<" org-scheduled-string)
4853 org-scheduled-time-regexp
4854 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4855 org-closed-time-regexp
4856 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4857 org-keyword-time-regexp
4858 (concat "\\<\\(" org-scheduled-string
4859 "\\|" org-deadline-string
4860 "\\|" org-closed-string
4861 "\\|" org-clock-string "\\)"
4862 " *[[<]\\([^]>]+\\)[]>]")
4863 org-keyword-time-not-clock-regexp
4864 (concat "\\<\\(" org-scheduled-string
4865 "\\|" org-deadline-string
4866 "\\|" org-closed-string
4867 "\\)"
4868 " *[[<]\\([^]>]+\\)[]>]")
4869 org-maybe-keyword-time-regexp
4870 (concat "\\(\\<\\(" org-scheduled-string
4871 "\\|" org-deadline-string
4872 "\\|" org-closed-string
4873 "\\|" org-clock-string "\\)\\)?"
4874 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4875 org-all-time-keywords
4876 (mapcar (lambda (w) (substring w 0 -1))
4877 (list org-scheduled-string org-deadline-string
4878 org-clock-string org-closed-string))
4880 (org-compute-latex-and-specials-regexp)
4881 (org-set-font-lock-defaults))))
4883 (defun org-file-contents (file &optional noerror)
4884 "Return the contents of FILE, as a string."
4885 (if (or (not file)
4886 (not (file-readable-p file)))
4887 (if noerror
4888 (progn
4889 (message "Cannot read file \"%s\"" file)
4890 (ding) (sit-for 2)
4892 (error "Cannot read file \"%s\"" file))
4893 (with-temp-buffer
4894 (insert-file-contents file)
4895 (buffer-string))))
4897 (defun org-extract-log-state-settings (x)
4898 "Extract the log state setting from a TODO keyword string.
4899 This will extract info from a string like \"WAIT(w@/!)\"."
4900 (let (kw key log1 log2)
4901 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4902 (setq kw (match-string 1 x)
4903 key (and (match-end 2) (match-string 2 x))
4904 log1 (and (match-end 3) (match-string 3 x))
4905 log2 (and (match-end 4) (match-string 4 x)))
4906 (and (or log1 log2)
4907 (list kw
4908 (and log1 (if (equal log1 "!") 'time 'note))
4909 (and log2 (if (equal log2 "!") 'time 'note)))))))
4911 (defun org-remove-keyword-keys (list)
4912 "Remove a pair of parenthesis at the end of each string in LIST."
4913 (mapcar (lambda (x)
4914 (if (string-match "(.*)$" x)
4915 (substring x 0 (match-beginning 0))
4917 list))
4919 (defun org-assign-fast-keys (alist)
4920 "Assign fast keys to a keyword-key alist.
4921 Respect keys that are already there."
4922 (let (new e (alt ?0))
4923 (while (setq e (pop alist))
4924 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4925 (cdr e)) ;; Key already assigned.
4926 (push e new)
4927 (let ((clist (string-to-list (downcase (car e))))
4928 (used (append new alist)))
4929 (when (= (car clist) ?@)
4930 (pop clist))
4931 (while (and clist (rassoc (car clist) used))
4932 (pop clist))
4933 (unless clist
4934 (while (rassoc alt used)
4935 (incf alt)))
4936 (push (cons (car e) (or (car clist) alt)) new))))
4937 (nreverse new)))
4939 ;;; Some variables used in various places
4941 (defvar org-window-configuration nil
4942 "Used in various places to store a window configuration.")
4943 (defvar org-selected-window nil
4944 "Used in various places to store a window configuration.")
4945 (defvar org-finish-function nil
4946 "Function to be called when `C-c C-c' is used.
4947 This is for getting out of special buffers like remember.")
4950 ;; FIXME: Occasionally check by commenting these, to make sure
4951 ;; no other functions uses these, forgetting to let-bind them.
4952 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4953 (defvar org-last-state)
4954 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4956 ;; Defined somewhere in this file, but used before definition.
4957 (defvar org-entities) ;; defined in org-entities.el
4958 (defvar org-struct-menu)
4959 (defvar org-org-menu)
4960 (defvar org-tbl-menu)
4962 ;;;; Define the Org-mode
4964 ;; We use a before-change function to check if a table might need
4965 ;; an update.
4966 (defvar org-table-may-need-update t
4967 "Indicates that a table might need an update.
4968 This variable is set by `org-before-change-function'.
4969 `org-table-align' sets it back to nil.")
4970 (defun org-before-change-function (beg end)
4971 "Every change indicates that a table might need an update."
4972 (setq org-table-may-need-update t))
4973 (defvar org-mode-map)
4974 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4975 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4976 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4977 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4978 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4979 (defvar org-table-buffer-is-an nil)
4981 (defvar bidi-paragraph-direction)
4982 (defvar buffer-face-mode-face)
4984 (require 'outline)
4985 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4986 (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"))
4987 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4989 ;; Other stuff we need.
4990 (require 'time-date)
4991 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4992 (require 'easymenu)
4993 (require 'overlay)
4995 (require 'org-macs)
4996 (require 'org-entities)
4997 ;; (require 'org-compat) moved higher up in the file before it is first used
4998 (require 'org-faces)
4999 (require 'org-list)
5000 (require 'org-pcomplete)
5001 (require 'org-src)
5002 (require 'org-footnote)
5004 ;; babel
5005 (require 'ob)
5006 (require 'ob-table)
5007 (require 'ob-lob)
5008 (require 'ob-ref)
5009 (require 'ob-tangle)
5010 (require 'ob-comint)
5011 (require 'ob-keys)
5013 ;;;###autoload
5014 (define-derived-mode org-mode outline-mode "Org"
5015 "Outline-based notes management and organizer, alias
5016 \"Carsten's outline-mode for keeping track of everything.\"
5018 Org-mode develops organizational tasks around a NOTES file which
5019 contains information about projects as plain text. Org-mode is
5020 implemented on top of outline-mode, which is ideal to keep the content
5021 of large files well structured. It supports ToDo items, deadlines and
5022 time stamps, which magically appear in the diary listing of the Emacs
5023 calendar. Tables are easily created with a built-in table editor.
5024 Plain text URL-like links connect to websites, emails (VM), Usenet
5025 messages (Gnus), BBDB entries, and any files related to the project.
5026 For printing and sharing of notes, an Org-mode file (or a part of it)
5027 can be exported as a structured ASCII or HTML file.
5029 The following commands are available:
5031 \\{org-mode-map}"
5033 ;; Get rid of Outline menus, they are not needed
5034 ;; Need to do this here because define-derived-mode sets up
5035 ;; the keymap so late. Still, it is a waste to call this each time
5036 ;; we switch another buffer into org-mode.
5037 (if (featurep 'xemacs)
5038 (when (boundp 'outline-mode-menu-heading)
5039 ;; Assume this is Greg's port, it uses easymenu
5040 (easy-menu-remove outline-mode-menu-heading)
5041 (easy-menu-remove outline-mode-menu-show)
5042 (easy-menu-remove outline-mode-menu-hide))
5043 (define-key org-mode-map [menu-bar headings] 'undefined)
5044 (define-key org-mode-map [menu-bar hide] 'undefined)
5045 (define-key org-mode-map [menu-bar show] 'undefined))
5047 (org-load-modules-maybe)
5048 (easy-menu-add org-org-menu)
5049 (easy-menu-add org-tbl-menu)
5050 (org-install-agenda-files-menu)
5051 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5052 (add-to-invisibility-spec '(org-cwidth))
5053 (add-to-invisibility-spec '(org-hide-block . t))
5054 (when (featurep 'xemacs)
5055 (org-set-local 'line-move-ignore-invisible t))
5056 (org-set-local 'outline-regexp org-outline-regexp)
5057 (org-set-local 'outline-level 'org-outline-level)
5058 (setq bidi-paragraph-direction 'left-to-right)
5059 (when (and org-ellipsis
5060 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5061 (fboundp 'make-glyph-code))
5062 (unless org-display-table
5063 (setq org-display-table (make-display-table)))
5064 (set-display-table-slot
5065 org-display-table 4
5066 (vconcat (mapcar
5067 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5068 org-ellipsis)))
5069 (if (stringp org-ellipsis) org-ellipsis "..."))))
5070 (setq buffer-display-table org-display-table))
5071 (org-set-regexps-and-options)
5072 (when (and org-tag-faces (not org-tags-special-faces-re))
5073 ;; tag faces set outside customize.... force initialization.
5074 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5075 ;; Calc embedded
5076 (org-set-local 'calc-embedded-open-mode "# ")
5077 (modify-syntax-entry ?@ "w")
5078 (modify-syntax-entry ?\" "\"")
5079 (if org-startup-truncated (setq truncate-lines t))
5080 (org-set-local 'font-lock-unfontify-region-function
5081 'org-unfontify-region)
5082 ;; Activate before-change-function
5083 (org-set-local 'org-table-may-need-update t)
5084 (org-add-hook 'before-change-functions 'org-before-change-function nil
5085 'local)
5086 ;; Check for running clock before killing a buffer
5087 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5088 ;; Initialize macros templates.
5089 (org-macro-initialize-templates)
5090 ;; Initialize radio targets.
5091 (org-update-radio-target-regexp)
5092 ;; Indentation.
5093 (org-set-local 'indent-line-function 'org-indent-line)
5094 (org-set-local 'indent-region-function 'org-indent-region)
5095 ;; Filling and auto-filling.
5096 (org-setup-filling)
5097 ;; Comments.
5098 (org-setup-comments-handling)
5099 ;; Beginning/end of defun
5100 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5101 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5102 ;; Next error for sparse trees
5103 (org-set-local 'next-error-function 'org-occur-next-match)
5104 ;; Make sure dependence stuff works reliably, even for users who set it
5105 ;; too late :-(
5106 (if org-enforce-todo-dependencies
5107 (add-hook 'org-blocker-hook
5108 'org-block-todo-from-children-or-siblings-or-parent)
5109 (remove-hook 'org-blocker-hook
5110 'org-block-todo-from-children-or-siblings-or-parent))
5111 (if org-enforce-todo-checkbox-dependencies
5112 (add-hook 'org-blocker-hook
5113 'org-block-todo-from-checkboxes)
5114 (remove-hook 'org-blocker-hook
5115 'org-block-todo-from-checkboxes))
5117 ;; Align options lines
5118 (org-set-local
5119 'align-mode-rules-list
5120 '((org-in-buffer-settings
5121 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5122 (modes . '(org-mode)))))
5124 ;; Imenu
5125 (org-set-local 'imenu-create-index-function
5126 'org-imenu-get-tree)
5128 ;; Make isearch reveal context
5129 (if (or (featurep 'xemacs)
5130 (not (boundp 'outline-isearch-open-invisible-function)))
5131 ;; Emacs 21 and XEmacs make use of the hook
5132 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5133 ;; Emacs 22 deals with this through a special variable
5134 (org-set-local 'outline-isearch-open-invisible-function
5135 (lambda (&rest ignore) (org-show-context 'isearch))))
5137 ;; Turn on org-beamer-mode?
5138 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5140 ;; Setup the pcomplete hooks
5141 (set (make-local-variable 'pcomplete-command-completion-function)
5142 'org-pcomplete-initial)
5143 (set (make-local-variable 'pcomplete-command-name-function)
5144 'org-command-at-point)
5145 (set (make-local-variable 'pcomplete-default-completion-function)
5146 'ignore)
5147 (set (make-local-variable 'pcomplete-parse-arguments-function)
5148 'org-parse-arguments)
5149 (set (make-local-variable 'pcomplete-termination-string) "")
5150 (when (>= emacs-major-version 23)
5151 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5153 ;; If empty file that did not turn on org-mode automatically, make it to.
5154 (if (and org-insert-mode-line-in-empty-file
5155 (org-called-interactively-p 'any)
5156 (= (point-min) (point-max)))
5157 (insert "# -*- mode: org -*-\n\n"))
5158 (unless org-inhibit-startup
5159 (when org-startup-align-all-tables
5160 (let ((bmp (buffer-modified-p)))
5161 (org-table-map-tables 'org-table-align 'quietly)
5162 (set-buffer-modified-p bmp)))
5163 (when org-startup-with-inline-images
5164 (org-display-inline-images))
5165 (when org-startup-indented
5166 (require 'org-indent)
5167 (org-indent-mode 1))
5168 (unless org-inhibit-startup-visibility-stuff
5169 (org-set-startup-visibility))))
5171 (when (fboundp 'abbrev-table-put)
5172 (abbrev-table-put org-mode-abbrev-table
5173 :parents (list text-mode-abbrev-table)))
5175 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5177 (defun org-current-time ()
5178 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5179 (if (> (car org-time-stamp-rounding-minutes) 1)
5180 (let ((r (car org-time-stamp-rounding-minutes))
5181 (time (decode-time)))
5182 (apply 'encode-time
5183 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5184 (nthcdr 2 time))))
5185 (current-time)))
5187 (defun org-today ()
5188 "Return today date, considering `org-extend-today-until'."
5189 (time-to-days
5190 (time-subtract (current-time)
5191 (list 0 (* 3600 org-extend-today-until) 0))))
5193 ;;;; Font-Lock stuff, including the activators
5195 (defvar org-mouse-map (make-sparse-keymap))
5196 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5197 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5198 (when org-mouse-1-follows-link
5199 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5200 (when org-tab-follows-link
5201 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5202 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5204 (require 'font-lock)
5206 (defconst org-non-link-chars "]\t\n\r<>")
5207 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5208 "shell" "elisp" "doi" "message"))
5209 (defvar org-link-types-re nil
5210 "Matches a link that has a url-like prefix like \"http:\"")
5211 (defvar org-link-re-with-space nil
5212 "Matches a link with spaces, optional angular brackets around it.")
5213 (defvar org-link-re-with-space2 nil
5214 "Matches a link with spaces, optional angular brackets around it.")
5215 (defvar org-link-re-with-space3 nil
5216 "Matches a link with spaces, only for internal part in bracket links.")
5217 (defvar org-angle-link-re nil
5218 "Matches link with angular brackets, spaces are allowed.")
5219 (defvar org-plain-link-re nil
5220 "Matches plain link, without spaces.")
5221 (defvar org-bracket-link-regexp nil
5222 "Matches a link in double brackets.")
5223 (defvar org-bracket-link-analytic-regexp nil
5224 "Regular expression used to analyze links.
5225 Here is what the match groups contain after a match:
5226 1: http:
5227 2: http
5228 3: path
5229 4: [desc]
5230 5: desc")
5231 (defvar org-bracket-link-analytic-regexp++ nil
5232 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5233 (defvar org-any-link-re nil
5234 "Regular expression matching any link.")
5236 (defcustom org-match-sexp-depth 3
5237 "Number of stacked braces for sub/superscript matching.
5238 This has to be set before loading org.el to be effective."
5239 :group 'org-export-translation ; ??????????????????????????/
5240 :type 'integer)
5242 (defun org-create-multibrace-regexp (left right n)
5243 "Create a regular expression which will match a balanced sexp.
5244 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5245 as single character strings.
5246 The regexp returned will match the entire expression including the
5247 delimiters. It will also define a single group which contains the
5248 match except for the outermost delimiters. The maximum depth of
5249 stacked delimiters is N. Escaping delimiters is not possible."
5250 (let* ((nothing (concat "[^" left right "]*?"))
5251 (or "\\|")
5252 (re nothing)
5253 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5254 (while (> n 1)
5255 (setq n (1- n)
5256 re (concat re or next)
5257 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5258 (concat left "\\(" re "\\)" right)))
5260 (defvar org-match-substring-regexp
5261 (concat
5262 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5263 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5264 "\\|"
5265 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5266 "\\|"
5267 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5268 "The regular expression matching a sub- or superscript.")
5270 (defvar org-match-substring-with-braces-regexp
5271 (concat
5272 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5273 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5274 "\\)")
5275 "The regular expression matching a sub- or superscript, forcing braces.")
5277 (defun org-make-link-regexps ()
5278 "Update the link regular expressions.
5279 This should be called after the variable `org-link-types' has changed."
5280 (setq org-link-types-re
5281 (concat
5282 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5283 org-link-re-with-space
5284 (concat
5285 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5286 "\\([^" org-non-link-chars " ]"
5287 "[^" org-non-link-chars "]*"
5288 "[^" org-non-link-chars " ]\\)>?")
5289 org-link-re-with-space2
5290 (concat
5291 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5292 "\\([^" org-non-link-chars " ]"
5293 "[^\t\n\r]*"
5294 "[^" org-non-link-chars " ]\\)>?")
5295 org-link-re-with-space3
5296 (concat
5297 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5298 "\\([^" org-non-link-chars " ]"
5299 "[^\t\n\r]*\\)")
5300 org-angle-link-re
5301 (concat
5302 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5303 "\\([^" org-non-link-chars " ]"
5304 "[^" org-non-link-chars "]*"
5305 "\\)>")
5306 org-plain-link-re
5307 (concat
5308 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5309 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5310 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5311 org-bracket-link-regexp
5312 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5313 org-bracket-link-analytic-regexp
5314 (concat
5315 "\\[\\["
5316 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5317 "\\([^]]+\\)"
5318 "\\]"
5319 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5320 "\\]")
5321 org-bracket-link-analytic-regexp++
5322 (concat
5323 "\\[\\["
5324 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5325 "\\([^]]+\\)"
5326 "\\]"
5327 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5328 "\\]")
5329 org-any-link-re
5330 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5331 org-angle-link-re "\\)\\|\\("
5332 org-plain-link-re "\\)")))
5334 (org-make-link-regexps)
5336 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5337 "Regular expression for fast time stamp matching.")
5338 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5339 "Regular expression for fast time stamp matching.")
5340 (defconst org-ts-regexp0
5341 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5342 "Regular expression matching time strings for analysis.
5343 This one does not require the space after the date, so it can be used
5344 on a string that terminates immediately after the date.")
5345 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5346 "Regular expression matching time strings for analysis.")
5347 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5348 "Regular expression matching time stamps, with groups.")
5349 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5350 "Regular expression matching time stamps (also [..]), with groups.")
5351 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5352 "Regular expression matching a time stamp range.")
5353 (defconst org-tr-regexp-both
5354 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5355 "Regular expression matching a time stamp range.")
5356 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5357 org-ts-regexp "\\)?")
5358 "Regular expression matching a time stamp or time stamp range.")
5359 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5360 org-ts-regexp-both "\\)?")
5361 "Regular expression matching a time stamp or time stamp range.
5362 The time stamps may be either active or inactive.")
5364 (defvar org-emph-face nil)
5366 (defun org-do-emphasis-faces (limit)
5367 "Run through the buffer and add overlays to emphasized strings."
5368 (let (rtn a)
5369 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5370 (if (not (= (char-after (match-beginning 3))
5371 (char-after (match-beginning 4))))
5372 (progn
5373 (setq rtn t)
5374 (setq a (assoc (match-string 3) org-emphasis-alist))
5375 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5376 'face
5377 (nth 1 a))
5378 (and (nth 4 a)
5379 (org-remove-flyspell-overlays-in
5380 (match-beginning 0) (match-end 0)))
5381 (add-text-properties (match-beginning 2) (match-end 2)
5382 '(font-lock-multiline t org-emphasis t))
5383 (when org-hide-emphasis-markers
5384 (add-text-properties (match-end 4) (match-beginning 5)
5385 '(invisible org-link))
5386 (add-text-properties (match-beginning 3) (match-end 3)
5387 '(invisible org-link)))))
5388 (backward-char 1))
5389 rtn))
5391 (defun org-emphasize (&optional char)
5392 "Insert or change an emphasis, i.e. a font like bold or italic.
5393 If there is an active region, change that region to a new emphasis.
5394 If there is no region, just insert the marker characters and position
5395 the cursor between them.
5396 CHAR should be either the marker character, or the first character of the
5397 HTML tag associated with that emphasis. If CHAR is a space, the means
5398 to remove the emphasis of the selected region.
5399 If char is not given (for example in an interactive call) it
5400 will be prompted for."
5401 (interactive)
5402 (let ((eal org-emphasis-alist) e det
5403 (erc org-emphasis-regexp-components)
5404 (prompt "")
5405 (string "") beg end move tag c s)
5406 (if (org-region-active-p)
5407 (setq beg (region-beginning) end (region-end)
5408 string (buffer-substring beg end))
5409 (setq move t))
5411 (while (setq e (pop eal))
5412 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5413 c (aref tag 0))
5414 (push (cons c (string-to-char (car e))) det)
5415 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5416 (substring tag 1)))))
5417 (setq det (nreverse det))
5418 (unless char
5419 (message "%s" (concat "Emphasis marker or tag:" prompt))
5420 (setq char (read-char-exclusive)))
5421 (setq char (or (cdr (assoc char det)) char))
5422 (if (equal char ?\ )
5423 (setq s "" move nil)
5424 (unless (assoc (char-to-string char) org-emphasis-alist)
5425 (error "No such emphasis marker: \"%c\"" char))
5426 (setq s (char-to-string char)))
5427 (while (and (> (length string) 1)
5428 (equal (substring string 0 1) (substring string -1))
5429 (assoc (substring string 0 1) org-emphasis-alist))
5430 (setq string (substring string 1 -1)))
5431 (setq string (concat s string s))
5432 (if beg (delete-region beg end))
5433 (unless (or (bolp)
5434 (string-match (concat "[" (nth 0 erc) "\n]")
5435 (char-to-string (char-before (point)))))
5436 (insert " "))
5437 (unless (or (eobp)
5438 (string-match (concat "[" (nth 1 erc) "\n]")
5439 (char-to-string (char-after (point)))))
5440 (insert " ") (backward-char 1))
5441 (insert string)
5442 (and move (backward-char 1))))
5444 (defconst org-nonsticky-props
5445 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5447 (defsubst org-rear-nonsticky-at (pos)
5448 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5450 (defun org-activate-plain-links (limit)
5451 "Run through the buffer and add overlays to links."
5452 (catch 'exit
5453 (let (f)
5454 (if (and (re-search-forward (concat org-plain-link-re) limit t)
5455 (or (not (member 'bracket org-activate-links))
5456 (save-excursion
5457 (save-match-data
5458 (goto-char (match-beginning 0))
5459 (not (looking-back "\\[\\["))))))
5460 (progn
5461 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5462 (setq f (get-text-property (match-beginning 0) 'face))
5463 (if (or (eq f 'org-tag)
5464 (and (listp f) (memq 'org-tag f)))
5466 (add-text-properties (match-beginning 0) (match-end 0)
5467 (list 'mouse-face 'highlight
5468 'face 'org-link
5469 'keymap org-mouse-map))
5470 (org-rear-nonsticky-at (match-end 0)))
5471 t)))))
5473 (defun org-activate-code (limit)
5474 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5475 (progn
5476 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5477 (remove-text-properties (match-beginning 0) (match-end 0)
5478 '(display t invisible t intangible t))
5479 t)))
5481 (defcustom org-src-fontify-natively nil
5482 "When non-nil, fontify code in code blocks."
5483 :type 'boolean
5484 :version "24.1"
5485 :group 'org-appearance
5486 :group 'org-babel)
5488 (defcustom org-allow-promoting-top-level-subtree nil
5489 "When non-nil, allow promoting a top level subtree.
5490 The leading star of the top level headline will be replaced
5491 by a #."
5492 :type 'boolean
5493 :version "24.1"
5494 :group 'org-appearance)
5496 (defun org-fontify-meta-lines-and-blocks (limit)
5497 (condition-case nil
5498 (org-fontify-meta-lines-and-blocks-1 limit)
5499 (error (message "org-mode fontification error"))))
5501 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5502 "Fontify #+ lines and blocks, in the correct ways."
5503 (let ((case-fold-search t))
5504 (if (re-search-forward
5505 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5506 limit t)
5507 (let ((beg (match-beginning 0))
5508 (block-start (match-end 0))
5509 (block-end nil)
5510 (lang (match-string 7))
5511 (beg1 (line-beginning-position 2))
5512 (dc1 (downcase (match-string 2)))
5513 (dc3 (downcase (match-string 3)))
5514 end end1 quoting block-type ovl)
5515 (cond
5516 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5517 ;; a single line of backend-specific content
5518 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5519 (remove-text-properties (match-beginning 0) (match-end 0)
5520 '(display t invisible t intangible t))
5521 (add-text-properties (match-beginning 1) (match-end 3)
5522 '(font-lock-fontified t face org-meta-line))
5523 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5524 '(font-lock-fontified t face org-block))
5525 ; for backend-specific code
5527 ((and (match-end 4) (equal dc3 "+begin"))
5528 ;; Truly a block
5529 (setq block-type (downcase (match-string 5))
5530 quoting (member block-type org-protecting-blocks))
5531 (when (re-search-forward
5532 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5533 nil t) ;; on purpose, we look further than LIMIT
5534 (setq end (min (point-max) (match-end 0))
5535 end1 (min (point-max) (1- (match-beginning 0))))
5536 (setq block-end (match-beginning 0))
5537 (when quoting
5538 (remove-text-properties beg end
5539 '(display t invisible t intangible t)))
5540 (add-text-properties
5541 beg end
5542 '(font-lock-fontified t font-lock-multiline t))
5543 (add-text-properties beg beg1 '(face org-meta-line))
5544 (add-text-properties end1 (min (point-max) (1+ end))
5545 '(face org-meta-line)) ; for end_src
5546 (cond
5547 ((and lang (not (string= lang "")) org-src-fontify-natively)
5548 (org-src-font-lock-fontify-block lang block-start block-end)
5549 ;; remove old background overlays
5550 (mapc (lambda (ov)
5551 (if (eq (overlay-get ov 'face) 'org-block-background)
5552 (delete-overlay ov)))
5553 (overlays-at (/ (+ beg1 block-end) 2)))
5554 ;; add a background overlay
5555 (setq ovl (make-overlay beg1 block-end))
5556 (overlay-put ovl 'face 'org-block-background)
5557 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5558 (quoting
5559 (add-text-properties beg1 (min (point-max) (1+ end1))
5560 '(face org-block))) ; end of source block
5561 ((not org-fontify-quote-and-verse-blocks))
5562 ((string= block-type "quote")
5563 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5564 ((string= block-type "verse")
5565 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5566 (add-text-properties beg beg1 '(face org-block-begin-line))
5567 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5568 '(face org-block-end-line))
5570 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5571 (add-text-properties
5572 beg (match-end 3)
5573 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5574 '(font-lock-fontified t invisible t)
5575 '(font-lock-fontified t face org-document-info-keyword)))
5576 (add-text-properties
5577 (match-beginning 6) (match-end 6)
5578 (if (string-equal dc1 "+title:")
5579 '(font-lock-fontified t face org-document-title)
5580 '(font-lock-fontified t face org-document-info))))
5581 ((or (equal dc1 "+results")
5582 (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 (re-latex
5777 (if org-export-with-LaTeX-fragments
5778 (mapcar (lambda (x) (nth 1 x)) latexs)))
5779 (re-macros
5780 (if org-export-with-TeX-macros
5781 (list (concat "\\\\"
5782 (regexp-opt
5783 (append
5785 (delq nil
5786 (mapcar 'car-safe
5787 (append org-entities-user
5788 org-entities)))
5789 (if (boundp 'org-latex-entities)
5790 (mapcar (lambda (x)
5791 (or (car-safe x) x))
5792 org-latex-entities)
5793 nil))
5794 'words))) ; FIXME
5796 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5797 (re-special (if org-export-with-special-strings
5798 (mapcar (lambda (x) (car x))
5799 org-export-html-special-string-regexps)))
5800 (re-rest
5801 (delq nil
5802 (list
5803 (if org-export-html-expand "@<[^>\n]+>")
5804 ))))
5805 (org-set-local
5806 'org-latex-and-specials-regexp
5807 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5808 re-rest) "\\|")))))
5810 (defun org-do-latex-and-special-faces (limit)
5811 "Run through the buffer and add overlays to links."
5812 (when org-latex-and-specials-regexp
5813 (let (rtn d)
5814 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5815 limit t))
5816 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5817 'face))
5818 '(org-code org-verbatim underline)))
5819 (progn
5820 (setq rtn t
5821 d (cond ((member (char-after (1+ (match-beginning 0)))
5822 '(?_ ?^)) 1)
5823 (t 0)))
5824 (font-lock-prepend-text-property
5825 (+ d (match-beginning 0)) (match-end 0)
5826 'face 'org-latex-and-export-specials)
5827 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5828 '(font-lock-multiline t)))))
5829 rtn)))
5831 (defun org-restart-font-lock ()
5832 "Restart `font-lock-mode', to force refontification."
5833 (when (and (boundp 'font-lock-mode) font-lock-mode)
5834 (font-lock-mode -1)
5835 (font-lock-mode 1)))
5837 (defun org-all-targets (&optional radio)
5838 "Return a list of all targets in this file.
5839 With optional argument RADIO, only find radio targets."
5840 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5841 rtn)
5842 (save-excursion
5843 (goto-char (point-min))
5844 (while (re-search-forward re nil t)
5845 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5846 rtn)))
5848 (defun org-make-target-link-regexp (targets)
5849 "Make regular expression matching all strings in TARGETS.
5850 The regular expression finds the targets also if there is a line break
5851 between words."
5852 (and targets
5853 (concat
5854 "\\<\\("
5855 (mapconcat
5856 (lambda (x)
5857 (setq x (regexp-quote x))
5858 (while (string-match " +" x)
5859 (setq x (replace-match "\\s-+" t t x)))
5861 targets
5862 "\\|")
5863 "\\)\\>")))
5865 (defun org-activate-tags (limit)
5866 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5867 (progn
5868 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5869 (add-text-properties (match-beginning 1) (match-end 1)
5870 (list 'mouse-face 'highlight
5871 'keymap org-mouse-map))
5872 (org-rear-nonsticky-at (match-end 1))
5873 t)))
5875 (defun org-outline-level ()
5876 "Compute the outline level of the heading at point.
5877 This function assumes that the cursor is at the beginning of a line matched
5878 by `outline-regexp'. Otherwise it returns garbage.
5879 If this is called at a normal headline, the level is the number of stars.
5880 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5881 (save-excursion
5882 (looking-at org-outline-regexp)
5883 (1- (- (match-end 0) (match-beginning 0)))))
5885 (defvar org-font-lock-keywords nil)
5887 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5888 "Regular expression matching a property line.")
5890 (defvar org-font-lock-hook nil
5891 "Functions to be called for special font lock stuff.")
5893 (defvar org-font-lock-set-keywords-hook nil
5894 "Functions that can manipulate `org-font-lock-extra-keywords'.
5895 This is called after `org-font-lock-extra-keywords' is defined, but before
5896 it is installed to be used by font lock. This can be useful if something
5897 needs to be inserted at a specific position in the font-lock sequence.")
5899 (defun org-font-lock-hook (limit)
5900 (run-hook-with-args 'org-font-lock-hook limit))
5902 (defun org-set-font-lock-defaults ()
5903 (let* ((em org-fontify-emphasized-text)
5904 (lk org-activate-links)
5905 (org-font-lock-extra-keywords
5906 (list
5907 ;; Call the hook
5908 '(org-font-lock-hook)
5909 ;; Headlines
5910 `(,(if org-fontify-whole-heading-line
5911 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5912 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5913 (1 (org-get-level-face 1))
5914 (2 (org-get-level-face 2))
5915 (3 (org-get-level-face 3)))
5916 ;; Table lines
5917 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5918 (1 'org-table t))
5919 ;; Table internals
5920 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5921 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5922 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5923 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5924 ;; Drawers
5925 (list org-drawer-regexp '(0 'org-special-keyword t))
5926 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5927 ;; Properties
5928 (list org-property-re
5929 '(1 'org-special-keyword t)
5930 '(3 'org-property-value t))
5931 ;; Links
5932 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5933 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5934 (if (memq 'plain lk) '(org-activate-plain-links))
5935 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5936 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5937 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5938 (if (memq 'footnote lk) '(org-activate-footnote-links))
5939 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5940 '(org-hide-wide-columns (0 nil append))
5941 ;; TODO keyword
5942 (list (format org-heading-keyword-regexp-format
5943 org-todo-regexp)
5944 '(2 (org-get-todo-face 2) t))
5945 ;; DONE
5946 (if org-fontify-done-headline
5947 (list (format org-heading-keyword-regexp-format
5948 (concat
5949 "\\(?:"
5950 (mapconcat 'regexp-quote org-done-keywords "\\|")
5951 "\\)"))
5952 '(2 'org-headline-done t))
5953 nil)
5954 ;; Priorities
5955 '(org-font-lock-add-priority-faces)
5956 ;; Tags
5957 '(org-font-lock-add-tag-faces)
5958 ;; Special keywords
5959 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5960 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5961 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5962 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5963 ;; Emphasis
5964 (if em
5965 (if (featurep 'xemacs)
5966 '(org-do-emphasis-faces (0 nil append))
5967 '(org-do-emphasis-faces)))
5968 ;; Checkboxes
5969 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5970 1 'org-checkbox prepend)
5971 (if (cdr (assq 'checkbox org-list-automatic-rules))
5972 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5973 (0 (org-get-checkbox-statistics-face) t)))
5974 ;; Description list items
5975 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5976 1 'org-list-dt prepend)
5977 ;; ARCHIVEd headings
5978 (list (concat
5979 org-outline-regexp-bol
5980 "\\(.*:" org-archive-tag ":.*\\)")
5981 '(1 'org-archived prepend))
5982 ;; Specials
5983 '(org-do-latex-and-special-faces)
5984 '(org-fontify-entities)
5985 '(org-raise-scripts)
5986 ;; Code
5987 '(org-activate-code (1 'org-code t))
5988 ;; COMMENT
5989 (list (format org-heading-keyword-regexp-format
5990 (concat "\\("
5991 org-comment-string "\\|" org-quote-string
5992 "\\)"))
5993 '(2 'org-special-keyword t))
5994 ;; Blocks and meta lines
5995 '(org-fontify-meta-lines-and-blocks)
5997 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5998 (run-hooks 'org-font-lock-set-keywords-hook)
5999 ;; Now set the full font-lock-keywords
6000 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6001 (org-set-local 'font-lock-defaults
6002 '(org-font-lock-keywords t nil nil backward-paragraph))
6003 (kill-local-variable 'font-lock-keywords) nil))
6005 (defun org-toggle-pretty-entities ()
6006 "Toggle the composition display of entities as UTF8 characters."
6007 (interactive)
6008 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6009 (org-restart-font-lock)
6010 (if org-pretty-entities
6011 (message "Entities are displayed as UTF8 characters")
6012 (save-restriction
6013 (widen)
6014 (org-decompose-region (point-min) (point-max))
6015 (message "Entities are displayed plain"))))
6017 (defvar org-custom-properties-overlays nil
6018 "List of overlays used for custom properties.")
6019 (make-variable-buffer-local 'org-custom-properties-overlays)
6021 (defun org-toggle-custom-properties-visibility ()
6022 "Display or hide properties in `org-custom-properties'."
6023 (interactive)
6024 (if org-custom-properties-overlays
6025 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6026 (setq org-custom-properties-overlays nil))
6027 (unless (not org-custom-properties)
6028 (save-excursion
6029 (save-restriction
6030 (widen)
6031 (goto-char (point-min))
6032 (while (re-search-forward org-property-re nil t)
6033 (mapc (lambda(p)
6034 (when (equal p (substring (match-string 1) 1 -1))
6035 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6036 (overlay-put o 'invisible t)
6037 (overlay-put o 'org-custom-property t)
6038 (push o org-custom-properties-overlays))))
6039 org-custom-properties)))))))
6041 (defun org-fontify-entities (limit)
6042 "Find an entity to fontify."
6043 (let (ee)
6044 (when org-pretty-entities
6045 (catch 'match
6046 (while (re-search-forward
6047 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6048 limit t)
6049 (if (and (not (org-in-indented-comment-line))
6050 (setq ee (org-entity-get (match-string 1)))
6051 (= (length (nth 6 ee)) 1))
6052 (let*
6053 ((end (if (equal (match-string 2) "{}")
6054 (match-end 2)
6055 (match-end 1))))
6056 (add-text-properties
6057 (match-beginning 0) end
6058 (list 'font-lock-fontified t))
6059 (compose-region (match-beginning 0) end
6060 (nth 6 ee) nil)
6061 (backward-char 1)
6062 (throw 'match t))))
6063 nil))))
6065 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6066 "Fontify string S like in Org-mode."
6067 (with-temp-buffer
6068 (insert s)
6069 (let ((org-odd-levels-only odd-levels))
6070 (org-mode)
6071 (font-lock-fontify-buffer)
6072 (buffer-string))))
6074 (defvar org-m nil)
6075 (defvar org-l nil)
6076 (defvar org-f nil)
6077 (defun org-get-level-face (n)
6078 "Get the right face for match N in font-lock matching of headlines."
6079 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6080 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6081 (if org-cycle-level-faces
6082 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6083 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6084 (cond
6085 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6086 ((eq n 2) org-f)
6087 (t (if org-level-color-stars-only nil org-f))))
6090 (defun org-get-todo-face (kwd)
6091 "Get the right face for a TODO keyword KWD.
6092 If KWD is a number, get the corresponding match group."
6093 (if (numberp kwd) (setq kwd (match-string kwd)))
6094 (or (org-face-from-face-or-color
6095 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6096 (and (member kwd org-done-keywords) 'org-done)
6097 'org-todo))
6099 (defun org-face-from-face-or-color (context inherit face-or-color)
6100 "Create a face list that inherits INHERIT, but sets the foreground color.
6101 When FACE-OR-COLOR is not a string, just return it."
6102 (if (stringp face-or-color)
6103 (list :inherit inherit
6104 (cdr (assoc context org-faces-easy-properties))
6105 face-or-color)
6106 face-or-color))
6108 (defun org-font-lock-add-tag-faces (limit)
6109 "Add the special tag faces."
6110 (when (and org-tag-faces org-tags-special-faces-re)
6111 (while (re-search-forward org-tags-special-faces-re limit t)
6112 (add-text-properties (match-beginning 1) (match-end 1)
6113 (list 'face (org-get-tag-face 1)
6114 'font-lock-fontified t))
6115 (backward-char 1))))
6117 (defun org-font-lock-add-priority-faces (limit)
6118 "Add the special priority faces."
6119 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6120 (when (save-match-data (org-at-heading-p))
6121 (add-text-properties
6122 (match-beginning 0) (match-end 0)
6123 (list 'face (or (org-face-from-face-or-color
6124 'priority 'org-special-keyword
6125 (cdr (assoc (char-after (match-beginning 1))
6126 org-priority-faces)))
6127 'org-special-keyword)
6128 'font-lock-fontified t)))))
6130 (defun org-get-tag-face (kwd)
6131 "Get the right face for a TODO keyword KWD.
6132 If KWD is a number, get the corresponding match group."
6133 (if (numberp kwd) (setq kwd (match-string kwd)))
6134 (or (org-face-from-face-or-color
6135 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6136 'org-tag))
6138 (defun org-unfontify-region (beg end &optional maybe_loudly)
6139 "Remove fontification and activation overlays from links."
6140 (font-lock-default-unfontify-region beg end)
6141 (let* ((buffer-undo-list t)
6142 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6143 (inhibit-modification-hooks t)
6144 deactivate-mark buffer-file-name buffer-file-truename)
6145 (org-decompose-region beg end)
6146 (remove-text-properties beg end
6147 '(mouse-face t keymap t org-linked-text t
6148 invisible t intangible t
6149 org-no-flyspell t org-emphasis t))
6150 (org-remove-font-lock-display-properties beg end)))
6152 (defconst org-script-display '(((raise -0.3) (height 0.7))
6153 ((raise 0.3) (height 0.7))
6154 ((raise -0.5))
6155 ((raise 0.5)))
6156 "Display properties for showing superscripts and subscripts.")
6158 (defun org-remove-font-lock-display-properties (beg end)
6159 "Remove specific display properties that have been added by font lock.
6160 The will remove the raise properties that are used to show superscripts
6161 and subscripts."
6162 (let (next prop)
6163 (while (< beg end)
6164 (setq next (next-single-property-change beg 'display nil end)
6165 prop (get-text-property beg 'display))
6166 (if (member prop org-script-display)
6167 (put-text-property beg next 'display nil))
6168 (setq beg next))))
6170 (defun org-raise-scripts (limit)
6171 "Add raise properties to sub/superscripts."
6172 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6173 (if (re-search-forward
6174 (if (eq org-use-sub-superscripts t)
6175 org-match-substring-regexp
6176 org-match-substring-with-braces-regexp)
6177 limit t)
6178 (let* ((pos (point)) table-p comment-p
6179 (mpos (match-beginning 3))
6180 (emph-p (get-text-property mpos 'org-emphasis))
6181 (link-p (get-text-property mpos 'mouse-face))
6182 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6183 (goto-char (point-at-bol))
6184 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6185 comment-p (org-looking-at-p "[ \t]*#"))
6186 (goto-char pos)
6187 ;; FIXME: Should we go back one character here, for a_b^c
6188 ;; (goto-char (1- pos)) ;????????????????????
6189 (if (or comment-p emph-p link-p keyw-p)
6191 (put-text-property (match-beginning 3) (match-end 0)
6192 'display
6193 (if (equal (char-after (match-beginning 2)) ?^)
6194 (nth (if table-p 3 1) org-script-display)
6195 (nth (if table-p 2 0) org-script-display)))
6196 (add-text-properties (match-beginning 2) (match-end 2)
6197 (list 'invisible t
6198 'org-dwidth t 'org-dwidth-n 1))
6199 (if (and (eq (char-after (match-beginning 3)) ?{)
6200 (eq (char-before (match-end 3)) ?}))
6201 (progn
6202 (add-text-properties
6203 (match-beginning 3) (1+ (match-beginning 3))
6204 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6205 (add-text-properties
6206 (1- (match-end 3)) (match-end 3)
6207 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6208 t)))))
6210 ;;;; Visibility cycling, including org-goto and indirect buffer
6212 ;;; Cycling
6214 (defvar org-cycle-global-status nil)
6215 (make-variable-buffer-local 'org-cycle-global-status)
6216 (defvar org-cycle-subtree-status nil)
6217 (make-variable-buffer-local 'org-cycle-subtree-status)
6219 ;;;###autoload
6221 (defvar org-inlinetask-min-level)
6223 (defun org-cycle (&optional arg)
6224 "TAB-action and visibility cycling for Org-mode.
6226 This is the command invoked in Org-mode by the TAB key. Its main purpose
6227 is outline visibility cycling, but it also invokes other actions
6228 in special contexts.
6230 - When this function is called with a prefix argument, rotate the entire
6231 buffer through 3 states (global cycling)
6232 1. OVERVIEW: Show only top-level headlines.
6233 2. CONTENTS: Show all headlines of all levels, but no body text.
6234 3. SHOW ALL: Show everything.
6235 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6236 determined by the variable `org-startup-folded', and by any VISIBILITY
6237 properties in the buffer.
6238 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6239 including any drawers.
6241 - When inside a table, re-align the table and move to the next field.
6243 - When point is at the beginning of a headline, rotate the subtree started
6244 by this line through 3 different states (local cycling)
6245 1. FOLDED: Only the main headline is shown.
6246 2. CHILDREN: The main headline and the direct children are shown.
6247 From this state, you can move to one of the children
6248 and zoom in further.
6249 3. SUBTREE: Show the entire subtree, including body text.
6250 If there is no subtree, switch directly from CHILDREN to FOLDED.
6252 - When point is at the beginning of an empty headline and the variable
6253 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6254 of the headline by demoting and promoting it to likely levels. This
6255 speeds up creation document structure by pressing TAB once or several
6256 times right after creating a new headline.
6258 - When there is a numeric prefix, go up to a heading with level ARG, do
6259 a `show-subtree' and return to the previous cursor position. If ARG
6260 is negative, go up that many levels.
6262 - When point is not at the beginning of a headline, execute the global
6263 binding for TAB, which is re-indenting the line. See the option
6264 `org-cycle-emulate-tab' for details.
6266 - Special case: if point is at the beginning of the buffer and there is
6267 no headline in line 1, this function will act as if called with prefix arg
6268 (C-u TAB, same as S-TAB) also when called without prefix arg.
6269 But only if also the variable `org-cycle-global-at-bob' is t."
6270 (interactive "P")
6271 (org-load-modules-maybe)
6272 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6273 (and org-cycle-level-after-item/entry-creation
6274 (or (org-cycle-level)
6275 (org-cycle-item-indentation))))
6276 (let* ((limit-level
6277 (or org-cycle-max-level
6278 (and (boundp 'org-inlinetask-min-level)
6279 org-inlinetask-min-level
6280 (1- org-inlinetask-min-level))))
6281 (nstars (and limit-level
6282 (if org-odd-levels-only
6283 (and limit-level (1- (* limit-level 2)))
6284 limit-level)))
6285 (org-outline-regexp
6286 (if (not (derived-mode-p 'org-mode))
6287 outline-regexp
6288 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6289 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6290 (not (looking-at org-outline-regexp))))
6291 (org-cycle-hook
6292 (if bob-special
6293 (delq 'org-optimize-window-after-visibility-change
6294 (copy-sequence org-cycle-hook))
6295 org-cycle-hook))
6296 (pos (point)))
6298 (if (or bob-special (equal arg '(4)))
6299 ;; special case: use global cycling
6300 (setq arg t))
6302 (cond
6304 ((equal arg '(16))
6305 (setq last-command 'dummy)
6306 (org-set-startup-visibility)
6307 (message "Startup visibility, plus VISIBILITY properties"))
6309 ((equal arg '(64))
6310 (show-all)
6311 (message "Entire buffer visible, including drawers"))
6313 ;; Table: enter it or move to the next field.
6314 ((org-at-table-p 'any)
6315 (if (org-at-table.el-p)
6316 (message "Use C-c ' to edit table.el tables")
6317 (if arg (org-table-edit-field t)
6318 (org-table-justify-field-maybe)
6319 (call-interactively 'org-table-next-field))))
6321 ((run-hook-with-args-until-success
6322 'org-tab-after-check-for-table-hook))
6324 ;; Global cycling: delegate to `org-cycle-internal-global'.
6325 ((eq arg t) (org-cycle-internal-global))
6327 ;; Drawers: delegate to `org-flag-drawer'.
6328 ((and org-drawers org-drawer-regexp
6329 (save-excursion
6330 (beginning-of-line 1)
6331 (looking-at org-drawer-regexp)))
6332 (org-flag-drawer ; toggle block visibility
6333 (not (get-char-property (match-end 0) 'invisible))))
6335 ;; Show-subtree, ARG levels up from here.
6336 ((integerp arg)
6337 (save-excursion
6338 (org-back-to-heading)
6339 (outline-up-heading (if (< arg 0) (- arg)
6340 (- (funcall outline-level) arg)))
6341 (org-show-subtree)))
6343 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6344 ((and (featurep 'org-inlinetask)
6345 (org-inlinetask-at-task-p)
6346 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6347 (org-inlinetask-toggle-visibility))
6349 ((org-try-cdlatex-tab))
6351 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6352 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6353 (save-excursion (beginning-of-line 1)
6354 (looking-at org-outline-regexp)))
6355 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6356 (org-cycle-internal-local))
6358 ;; From there: TAB emulation and template completion.
6359 (buffer-read-only (org-back-to-heading))
6361 ((run-hook-with-args-until-success
6362 'org-tab-after-check-for-cycling-hook))
6364 ((org-try-structure-completion))
6366 ((run-hook-with-args-until-success
6367 'org-tab-before-tab-emulation-hook))
6369 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6370 (or (not (bolp))
6371 (not (looking-at org-outline-regexp))))
6372 (call-interactively (global-key-binding "\t")))
6374 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6375 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6376 (or (and (eq org-cycle-emulate-tab 'white)
6377 (= (match-end 0) (point-at-eol)))
6378 (and (eq org-cycle-emulate-tab 'whitestart)
6379 (>= (match-end 0) pos))))
6381 (eq org-cycle-emulate-tab t))
6382 (call-interactively (global-key-binding "\t")))
6384 (t (save-excursion
6385 (org-back-to-heading)
6386 (org-cycle)))))))
6388 (defun org-cycle-internal-global ()
6389 "Do the global cycling action."
6390 ;; Hack to avoid display of messages for .org attachments in Gnus
6391 (let ((ga (string-match "\\*fontification" (buffer-name))))
6392 (cond
6393 ((and (eq last-command this-command)
6394 (eq org-cycle-global-status 'overview))
6395 ;; We just created the overview - now do table of contents
6396 ;; This can be slow in very large buffers, so indicate action
6397 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6398 (unless ga (message "CONTENTS..."))
6399 (org-content)
6400 (unless ga (message "CONTENTS...done"))
6401 (setq org-cycle-global-status 'contents)
6402 (run-hook-with-args 'org-cycle-hook 'contents))
6404 ((and (eq last-command this-command)
6405 (eq org-cycle-global-status 'contents))
6406 ;; We just showed the table of contents - now show everything
6407 (run-hook-with-args 'org-pre-cycle-hook 'all)
6408 (show-all)
6409 (unless ga (message "SHOW ALL"))
6410 (setq org-cycle-global-status 'all)
6411 (run-hook-with-args 'org-cycle-hook 'all))
6414 ;; Default action: go to overview
6415 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6416 (org-overview)
6417 (unless ga (message "OVERVIEW"))
6418 (setq org-cycle-global-status 'overview)
6419 (run-hook-with-args 'org-cycle-hook 'overview)))))
6421 (defun org-cycle-internal-local ()
6422 "Do the local cycling action."
6423 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6424 ;; First, determine end of headline (EOH), end of subtree or item
6425 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6426 (save-excursion
6427 (if (org-at-item-p)
6428 (progn
6429 (beginning-of-line)
6430 (setq struct (org-list-struct))
6431 (setq eoh (point-at-eol))
6432 (setq eos (org-list-get-item-end-before-blank (point) struct))
6433 (setq has-children (org-list-has-child-p (point) struct)))
6434 (org-back-to-heading)
6435 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6436 (setq eos (save-excursion
6437 (org-end-of-subtree t)
6438 (unless (eobp)
6439 (skip-chars-forward " \t\n"))
6440 (if (eobp) (point) (1- (point)))))
6441 (setq has-children
6442 (or (save-excursion
6443 (let ((level (funcall outline-level)))
6444 (outline-next-heading)
6445 (and (org-at-heading-p t)
6446 (> (funcall outline-level) level))))
6447 (save-excursion
6448 (org-list-search-forward (org-item-beginning-re) eos t)))))
6449 ;; Determine end invisible part of buffer (EOL)
6450 (beginning-of-line 2)
6451 ;; XEmacs doesn't have `next-single-char-property-change'
6452 (if (featurep 'xemacs)
6453 (while (and (not (eobp)) ;; this is like `next-line'
6454 (get-char-property (1- (point)) 'invisible))
6455 (beginning-of-line 2))
6456 (while (and (not (eobp)) ;; this is like `next-line'
6457 (get-char-property (1- (point)) 'invisible))
6458 (goto-char (next-single-char-property-change (point) 'invisible))
6459 (and (eolp) (beginning-of-line 2))))
6460 (setq eol (point)))
6461 ;; Find out what to do next and set `this-command'
6462 (cond
6463 ((= eos eoh)
6464 ;; Nothing is hidden behind this heading
6465 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6466 (message "EMPTY ENTRY")
6467 (setq org-cycle-subtree-status nil)
6468 (save-excursion
6469 (goto-char eos)
6470 (outline-next-heading)
6471 (if (outline-invisible-p) (org-flag-heading nil))))
6472 ((and (or (>= eol eos)
6473 (not (string-match "\\S-" (buffer-substring eol eos))))
6474 (or has-children
6475 (not (setq children-skipped
6476 org-cycle-skip-children-state-if-no-children))))
6477 ;; Entire subtree is hidden in one line: children view
6478 (run-hook-with-args 'org-pre-cycle-hook 'children)
6479 (if (org-at-item-p)
6480 (org-list-set-item-visibility (point-at-bol) struct 'children)
6481 (org-show-entry)
6482 (org-with-limited-levels (show-children))
6483 ;; FIXME: This slows down the func way too much.
6484 ;; How keep drawers hidden in subtree anyway?
6485 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6486 ;; (org-cycle-hide-drawers 'subtree))
6488 ;; Fold every list in subtree to top-level items.
6489 (when (eq org-cycle-include-plain-lists 'integrate)
6490 (save-excursion
6491 (org-back-to-heading)
6492 (while (org-list-search-forward (org-item-beginning-re) eos t)
6493 (beginning-of-line 1)
6494 (let* ((struct (org-list-struct))
6495 (prevs (org-list-prevs-alist struct))
6496 (end (org-list-get-bottom-point struct)))
6497 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6498 (org-list-get-all-items (point) struct prevs))
6499 (goto-char end))))))
6500 (message "CHILDREN")
6501 (save-excursion
6502 (goto-char eos)
6503 (outline-next-heading)
6504 (if (outline-invisible-p) (org-flag-heading nil)))
6505 (setq org-cycle-subtree-status 'children)
6506 (run-hook-with-args 'org-cycle-hook 'children))
6507 ((or children-skipped
6508 (and (eq last-command this-command)
6509 (eq org-cycle-subtree-status 'children)))
6510 ;; We just showed the children, or no children are there,
6511 ;; now show everything.
6512 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6513 (outline-flag-region eoh eos nil)
6514 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6515 (setq org-cycle-subtree-status 'subtree)
6516 (run-hook-with-args 'org-cycle-hook 'subtree))
6518 ;; Default action: hide the subtree.
6519 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6520 (outline-flag-region eoh eos t)
6521 (message "FOLDED")
6522 (setq org-cycle-subtree-status 'folded)
6523 (run-hook-with-args 'org-cycle-hook 'folded)))))
6525 ;;;###autoload
6526 (defun org-global-cycle (&optional arg)
6527 "Cycle the global visibility. For details see `org-cycle'.
6528 With \\[universal-argument] prefix arg, switch to startup visibility.
6529 With a numeric prefix, show all headlines up to that level."
6530 (interactive "P")
6531 (let ((org-cycle-include-plain-lists
6532 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6533 (cond
6534 ((integerp arg)
6535 (show-all)
6536 (hide-sublevels arg)
6537 (setq org-cycle-global-status 'contents))
6538 ((equal arg '(4))
6539 (org-set-startup-visibility)
6540 (message "Startup visibility, plus VISIBILITY properties."))
6542 (org-cycle '(4))))))
6544 (defun org-set-startup-visibility ()
6545 "Set the visibility required by startup options and properties."
6546 (cond
6547 ((eq org-startup-folded t)
6548 (org-cycle '(4)))
6549 ((eq org-startup-folded 'content)
6550 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6551 (org-cycle '(4)) (org-cycle '(4)))))
6552 (unless (eq org-startup-folded 'showeverything)
6553 (if org-hide-block-startup (org-hide-block-all))
6554 (org-set-visibility-according-to-property 'no-cleanup)
6555 (org-cycle-hide-archived-subtrees 'all)
6556 (org-cycle-hide-drawers 'all)
6557 (org-cycle-show-empty-lines t)))
6559 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6560 "Switch subtree visibilities according to :VISIBILITY: property."
6561 (interactive)
6562 (let (org-show-entry-below state)
6563 (save-excursion
6564 (goto-char (point-min))
6565 (while (re-search-forward
6566 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6567 nil t)
6568 (setq state (match-string 1))
6569 (save-excursion
6570 (org-back-to-heading t)
6571 (hide-subtree)
6572 (org-reveal)
6573 (cond
6574 ((equal state '("fold" "folded"))
6575 (hide-subtree))
6576 ((equal state "children")
6577 (org-show-hidden-entry)
6578 (show-children))
6579 ((equal state "content")
6580 (save-excursion
6581 (save-restriction
6582 (org-narrow-to-subtree)
6583 (org-content))))
6584 ((member state '("all" "showall"))
6585 (show-subtree)))))
6586 (unless no-cleanup
6587 (org-cycle-hide-archived-subtrees 'all)
6588 (org-cycle-hide-drawers 'all)
6589 (org-cycle-show-empty-lines 'all)))))
6591 ;; This function uses outline-regexp instead of the more fundamental
6592 ;; org-outline-regexp so that org-cycle-global works outside of Org
6593 ;; buffers, where outline-regexp is needed.
6594 (defun org-overview ()
6595 "Switch to overview mode, showing only top-level headlines.
6596 Really, this shows all headlines with level equal or greater than the level
6597 of the first headline in the buffer. This is important, because if the
6598 first headline is not level one, then (hide-sublevels 1) gives confusing
6599 results."
6600 (interactive)
6601 (let ((level (save-excursion
6602 (goto-char (point-min))
6603 (if (re-search-forward (concat "^" outline-regexp) nil t)
6604 (progn
6605 (goto-char (match-beginning 0))
6606 (funcall outline-level))))))
6607 (and level (hide-sublevels level))))
6609 (defun org-content (&optional arg)
6610 "Show all headlines in the buffer, like a table of contents.
6611 With numerical argument N, show content up to level N."
6612 (interactive "P")
6613 (save-excursion
6614 ;; Visit all headings and show their offspring
6615 (and (integerp arg) (org-overview))
6616 (goto-char (point-max))
6617 (catch 'exit
6618 (while (and (progn (condition-case nil
6619 (outline-previous-visible-heading 1)
6620 (error (goto-char (point-min))))
6622 (looking-at org-outline-regexp))
6623 (if (integerp arg)
6624 (show-children (1- arg))
6625 (show-branches))
6626 (if (bobp) (throw 'exit nil))))))
6629 (defun org-optimize-window-after-visibility-change (state)
6630 "Adjust the window after a change in outline visibility.
6631 This function is the default value of the hook `org-cycle-hook'."
6632 (when (get-buffer-window (current-buffer))
6633 (cond
6634 ((eq state 'content) nil)
6635 ((eq state 'all) nil)
6636 ((eq state 'folded) nil)
6637 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6638 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6640 (defun org-remove-empty-overlays-at (pos)
6641 "Remove outline overlays that do not contain non-white stuff."
6642 (mapc
6643 (lambda (o)
6644 (and (eq 'outline (overlay-get o 'invisible))
6645 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6646 (overlay-end o))))
6647 (delete-overlay o)))
6648 (overlays-at pos)))
6650 (defun org-clean-visibility-after-subtree-move ()
6651 "Fix visibility issues after moving a subtree."
6652 ;; First, find a reasonable region to look at:
6653 ;; Start two siblings above, end three below
6654 (let* ((beg (save-excursion
6655 (and (org-get-last-sibling)
6656 (org-get-last-sibling))
6657 (point)))
6658 (end (save-excursion
6659 (and (org-get-next-sibling)
6660 (org-get-next-sibling)
6661 (org-get-next-sibling))
6662 (if (org-at-heading-p)
6663 (point-at-eol)
6664 (point))))
6665 (level (looking-at "\\*+"))
6666 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6667 (save-excursion
6668 (save-restriction
6669 (narrow-to-region beg end)
6670 (when re
6671 ;; Properly fold already folded siblings
6672 (goto-char (point-min))
6673 (while (re-search-forward re nil t)
6674 (if (and (not (outline-invisible-p))
6675 (save-excursion
6676 (goto-char (point-at-eol)) (outline-invisible-p)))
6677 (hide-entry))))
6678 (org-cycle-show-empty-lines 'overview)
6679 (org-cycle-hide-drawers 'overview)))))
6681 (defun org-cycle-show-empty-lines (state)
6682 "Show empty lines above all visible headlines.
6683 The region to be covered depends on STATE when called through
6684 `org-cycle-hook'. Lisp program can use t for STATE to get the
6685 entire buffer covered. Note that an empty line is only shown if there
6686 are at least `org-cycle-separator-lines' empty lines before the headline."
6687 (when (not (= org-cycle-separator-lines 0))
6688 (save-excursion
6689 (let* ((n (abs org-cycle-separator-lines))
6690 (re (cond
6691 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6692 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6693 (t (let ((ns (number-to-string (- n 2))))
6694 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6695 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6696 beg end b e)
6697 (cond
6698 ((memq state '(overview contents t))
6699 (setq beg (point-min) end (point-max)))
6700 ((memq state '(children folded))
6701 (setq beg (point) end (progn (org-end-of-subtree t t)
6702 (beginning-of-line 2)
6703 (point)))))
6704 (when beg
6705 (goto-char beg)
6706 (while (re-search-forward re end t)
6707 (unless (get-char-property (match-end 1) 'invisible)
6708 (setq e (match-end 1))
6709 (if (< org-cycle-separator-lines 0)
6710 (setq b (save-excursion
6711 (goto-char (match-beginning 0))
6712 (org-back-over-empty-lines)
6713 (if (save-excursion
6714 (goto-char (max (point-min) (1- (point))))
6715 (org-at-heading-p))
6716 (1- (point))
6717 (point))))
6718 (setq b (match-beginning 1)))
6719 (outline-flag-region b e nil)))))))
6720 ;; Never hide empty lines at the end of the file.
6721 (save-excursion
6722 (goto-char (point-max))
6723 (outline-previous-heading)
6724 (outline-end-of-heading)
6725 (if (and (looking-at "[ \t\n]+")
6726 (= (match-end 0) (point-max)))
6727 (outline-flag-region (point) (match-end 0) nil))))
6729 (defun org-show-empty-lines-in-parent ()
6730 "Move to the parent and re-show empty lines before visible headlines."
6731 (save-excursion
6732 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6733 (org-cycle-show-empty-lines context))))
6735 (defun org-files-list ()
6736 "Return `org-agenda-files' list, plus all open org-mode files.
6737 This is useful for operations that need to scan all of a user's
6738 open and agenda-wise Org files."
6739 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6740 (dolist (buf (buffer-list))
6741 (with-current-buffer buf
6742 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6743 (let ((file (expand-file-name (buffer-file-name))))
6744 (unless (member file files)
6745 (push file files))))))
6746 files))
6748 (defsubst org-entry-beginning-position ()
6749 "Return the beginning position of the current entry."
6750 (save-excursion (outline-back-to-heading t) (point)))
6752 (defsubst org-entry-end-position ()
6753 "Return the end position of the current entry."
6754 (save-excursion (outline-next-heading) (point)))
6756 (defun org-cycle-hide-drawers (state)
6757 "Re-hide all drawers after a visibility state change."
6758 (when (and (derived-mode-p 'org-mode)
6759 (not (memq state '(overview folded contents))))
6760 (save-excursion
6761 (let* ((globalp (memq state '(contents all)))
6762 (beg (if globalp (point-min) (point)))
6763 (end (if globalp (point-max)
6764 (if (eq state 'children)
6765 (save-excursion (outline-next-heading) (point))
6766 (org-end-of-subtree t)))))
6767 (goto-char beg)
6768 (while (re-search-forward org-drawer-regexp end t)
6769 (org-flag-drawer t))))))
6771 (defun org-flag-drawer (flag)
6772 "When FLAG is non-nil, hide the drawer we are within.
6773 Otherwise make it visible."
6774 (save-excursion
6775 (beginning-of-line 1)
6776 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6777 (let ((b (match-end 0)))
6778 (if (re-search-forward
6779 "^[ \t]*:END:"
6780 (save-excursion (outline-next-heading) (point)) t)
6781 (outline-flag-region b (point-at-eol) flag)
6782 (error ":END: line missing at position %s" b))))))
6784 (defun org-subtree-end-visible-p ()
6785 "Is the end of the current subtree visible?"
6786 (pos-visible-in-window-p
6787 (save-excursion (org-end-of-subtree t) (point))))
6789 (defun org-first-headline-recenter (&optional N)
6790 "Move cursor to the first headline and recenter the headline.
6791 Optional argument N means put the headline into the Nth line of the window."
6792 (goto-char (point-min))
6793 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6794 (beginning-of-line)
6795 (recenter (prefix-numeric-value N))))
6797 ;;; Saving and restoring visibility
6799 (defun org-outline-overlay-data (&optional use-markers)
6800 "Return a list of the locations of all outline overlays.
6801 These are overlays with the `invisible' property value `outline'.
6802 The return value is a list of cons cells, with start and stop
6803 positions for each overlay.
6804 If USE-MARKERS is set, return the positions as markers."
6805 (let (beg end)
6806 (save-excursion
6807 (save-restriction
6808 (widen)
6809 (delq nil
6810 (mapcar (lambda (o)
6811 (when (eq (overlay-get o 'invisible) 'outline)
6812 (setq beg (overlay-start o)
6813 end (overlay-end o))
6814 (and beg end (> end beg)
6815 (if use-markers
6816 (cons (move-marker (make-marker) beg)
6817 (move-marker (make-marker) end))
6818 (cons beg end)))))
6819 (overlays-in (point-min) (point-max))))))))
6821 (defun org-set-outline-overlay-data (data)
6822 "Create visibility overlays for all positions in DATA.
6823 DATA should have been made by `org-outline-overlay-data'."
6824 (let (o)
6825 (save-excursion
6826 (save-restriction
6827 (widen)
6828 (show-all)
6829 (mapc (lambda (c)
6830 (outline-flag-region (car c) (cdr c) t))
6831 data)))))
6833 ;;; Folding of blocks
6835 (defvar org-hide-block-overlays nil
6836 "Overlays hiding blocks.")
6837 (make-variable-buffer-local 'org-hide-block-overlays)
6839 (defun org-block-map (function &optional start end)
6840 "Call FUNCTION at the head of all source blocks in the current buffer.
6841 Optional arguments START and END can be used to limit the range."
6842 (let ((start (or start (point-min)))
6843 (end (or end (point-max))))
6844 (save-excursion
6845 (goto-char start)
6846 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6847 (save-excursion
6848 (save-match-data
6849 (goto-char (match-beginning 0))
6850 (funcall function)))))))
6852 (defun org-hide-block-toggle-all ()
6853 "Toggle the visibility of all blocks in the current buffer."
6854 (org-block-map #'org-hide-block-toggle))
6856 (defun org-hide-block-all ()
6857 "Fold all blocks in the current buffer."
6858 (interactive)
6859 (org-show-block-all)
6860 (org-block-map #'org-hide-block-toggle-maybe))
6862 (defun org-show-block-all ()
6863 "Unfold all blocks in the current buffer."
6864 (interactive)
6865 (mapc 'delete-overlay org-hide-block-overlays)
6866 (setq org-hide-block-overlays nil))
6868 (defun org-hide-block-toggle-maybe ()
6869 "Toggle visibility of block at point."
6870 (interactive)
6871 (let ((case-fold-search t))
6872 (if (save-excursion
6873 (beginning-of-line 1)
6874 (looking-at org-block-regexp))
6875 (progn (org-hide-block-toggle)
6876 t) ;; to signal that we took action
6877 nil))) ;; to signal that we did not
6879 (defun org-hide-block-toggle (&optional force)
6880 "Toggle the visibility of the current block."
6881 (interactive)
6882 (save-excursion
6883 (beginning-of-line)
6884 (if (re-search-forward org-block-regexp nil t)
6885 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6886 (end (match-end 0)) ;; end of entire body
6888 (if (memq t (mapcar (lambda (overlay)
6889 (eq (overlay-get overlay 'invisible)
6890 'org-hide-block))
6891 (overlays-at start)))
6892 (if (or (not force) (eq force 'off))
6893 (mapc (lambda (ov)
6894 (when (member ov org-hide-block-overlays)
6895 (setq org-hide-block-overlays
6896 (delq ov org-hide-block-overlays)))
6897 (when (eq (overlay-get ov 'invisible)
6898 'org-hide-block)
6899 (delete-overlay ov)))
6900 (overlays-at start)))
6901 (setq ov (make-overlay start end))
6902 (overlay-put ov 'invisible 'org-hide-block)
6903 ;; make the block accessible to isearch
6904 (overlay-put
6905 ov 'isearch-open-invisible
6906 (lambda (ov)
6907 (when (member ov org-hide-block-overlays)
6908 (setq org-hide-block-overlays
6909 (delq ov org-hide-block-overlays)))
6910 (when (eq (overlay-get ov 'invisible)
6911 'org-hide-block)
6912 (delete-overlay ov))))
6913 (push ov org-hide-block-overlays)))
6914 (error "Not looking at a source block"))))
6916 ;; org-tab-after-check-for-cycling-hook
6917 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6918 ;; Remove overlays when changing major mode
6919 (add-hook 'org-mode-hook
6920 (lambda () (org-add-hook 'change-major-mode-hook
6921 'org-show-block-all 'append 'local)))
6923 ;;; Org-goto
6925 (defvar org-goto-window-configuration nil)
6926 (defvar org-goto-marker nil)
6927 (defvar org-goto-map
6928 (let ((map (make-sparse-keymap)))
6929 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6930 (while (setq cmd (pop cmds))
6931 (substitute-key-definition cmd cmd map global-map)))
6932 (suppress-keymap map)
6933 (org-defkey map "\C-m" 'org-goto-ret)
6934 (org-defkey map [(return)] 'org-goto-ret)
6935 (org-defkey map [(left)] 'org-goto-left)
6936 (org-defkey map [(right)] 'org-goto-right)
6937 (org-defkey map [(control ?g)] 'org-goto-quit)
6938 (org-defkey map "\C-i" 'org-cycle)
6939 (org-defkey map [(tab)] 'org-cycle)
6940 (org-defkey map [(down)] 'outline-next-visible-heading)
6941 (org-defkey map [(up)] 'outline-previous-visible-heading)
6942 (if org-goto-auto-isearch
6943 (if (fboundp 'define-key-after)
6944 (define-key-after map [t] 'org-goto-local-auto-isearch)
6945 nil)
6946 (org-defkey map "q" 'org-goto-quit)
6947 (org-defkey map "n" 'outline-next-visible-heading)
6948 (org-defkey map "p" 'outline-previous-visible-heading)
6949 (org-defkey map "f" 'outline-forward-same-level)
6950 (org-defkey map "b" 'outline-backward-same-level)
6951 (org-defkey map "u" 'outline-up-heading))
6952 (org-defkey map "/" 'org-occur)
6953 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6954 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6955 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6956 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6957 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6958 map))
6960 (defconst org-goto-help
6961 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6962 RET=jump to location [Q]uit and return to previous location
6963 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6965 (defvar org-goto-start-pos) ; dynamically scoped parameter
6967 ;; FIXME: Docstring does not mention both interfaces
6968 (defun org-goto (&optional alternative-interface)
6969 "Look up a different location in the current file, keeping current visibility.
6971 When you want look-up or go to a different location in a
6972 document, the fastest way is often to fold the entire buffer and
6973 then dive into the tree. This method has the disadvantage, that
6974 the previous location will be folded, which may not be what you
6975 want.
6977 This command works around this by showing a copy of the current
6978 buffer in an indirect buffer, in overview mode. You can dive
6979 into the tree in that copy, use org-occur and incremental search
6980 to find a location. When pressing RET or `Q', the command
6981 returns to the original buffer in which the visibility is still
6982 unchanged. After RET it will also jump to the location selected
6983 in the indirect buffer and expose the headline hierarchy above.
6985 With a prefix argument, use the alternative interface: e.g. if
6986 `org-goto-interface' is 'outline use 'outline-path-completion."
6987 (interactive "P")
6988 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6989 (org-refile-use-outline-path t)
6990 (org-refile-target-verify-function nil)
6991 (interface
6992 (if (not alternative-interface)
6993 org-goto-interface
6994 (if (eq org-goto-interface 'outline)
6995 'outline-path-completion
6996 'outline)))
6997 (org-goto-start-pos (point))
6998 (selected-point
6999 (if (eq interface 'outline)
7000 (car (org-get-location (current-buffer) org-goto-help))
7001 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7002 (org-refile-check-position pa)
7003 (nth 3 pa)))))
7004 (if selected-point
7005 (progn
7006 (org-mark-ring-push org-goto-start-pos)
7007 (goto-char selected-point)
7008 (if (or (outline-invisible-p) (org-invisible-p2))
7009 (org-show-context 'org-goto)))
7010 (message "Quit"))))
7012 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7013 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7014 (defvar org-goto-local-auto-isearch-map) ; defined below
7016 (defun org-get-location (buf help)
7017 "Let the user select a location in the Org-mode buffer BUF.
7018 This function uses a recursive edit. It returns the selected position
7019 or nil."
7020 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7021 (isearch-hide-immediately nil)
7022 (isearch-search-fun-function
7023 (lambda () 'org-goto-local-search-headings))
7024 (org-goto-selected-point org-goto-exit-command)
7025 (pop-up-frames nil)
7026 (special-display-buffer-names nil)
7027 (special-display-regexps nil)
7028 (special-display-function nil))
7029 (save-excursion
7030 (save-window-excursion
7031 (delete-other-windows)
7032 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7033 (org-pop-to-buffer-same-window
7034 (condition-case nil
7035 (make-indirect-buffer (current-buffer) "*org-goto*")
7036 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7037 (with-output-to-temp-buffer "*Help*"
7038 (princ help))
7039 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7040 (setq buffer-read-only nil)
7041 (let ((org-startup-truncated t)
7042 (org-startup-folded nil)
7043 (org-startup-align-all-tables nil))
7044 (org-mode)
7045 (org-overview))
7046 (setq buffer-read-only t)
7047 (if (and (boundp 'org-goto-start-pos)
7048 (integer-or-marker-p org-goto-start-pos))
7049 (let ((org-show-hierarchy-above t)
7050 (org-show-siblings t)
7051 (org-show-following-heading t))
7052 (goto-char org-goto-start-pos)
7053 (and (outline-invisible-p) (org-show-context)))
7054 (goto-char (point-min)))
7055 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7056 (message "Select location and press RET")
7057 (use-local-map org-goto-map)
7058 (recursive-edit)
7060 (kill-buffer "*org-goto*")
7061 (cons org-goto-selected-point org-goto-exit-command)))
7063 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7064 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7065 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7066 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7068 (defun org-goto-local-search-headings (string bound noerror)
7069 "Search and make sure that any matches are in headlines."
7070 (catch 'return
7071 (while (if isearch-forward
7072 (search-forward string bound noerror)
7073 (search-backward string bound noerror))
7074 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7075 (and (member :headline context)
7076 (not (member :tags context))))
7077 (throw 'return (point))))))
7079 (defun org-goto-local-auto-isearch ()
7080 "Start isearch."
7081 (interactive)
7082 (goto-char (point-min))
7083 (let ((keys (this-command-keys)))
7084 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7085 (isearch-mode t)
7086 (isearch-process-search-char (string-to-char keys)))))
7088 (defun org-goto-ret (&optional arg)
7089 "Finish `org-goto' by going to the new location."
7090 (interactive "P")
7091 (setq org-goto-selected-point (point)
7092 org-goto-exit-command 'return)
7093 (throw 'exit nil))
7095 (defun org-goto-left ()
7096 "Finish `org-goto' by going to the new location."
7097 (interactive)
7098 (if (org-at-heading-p)
7099 (progn
7100 (beginning-of-line 1)
7101 (setq org-goto-selected-point (point)
7102 org-goto-exit-command 'left)
7103 (throw 'exit nil))
7104 (error "Not on a heading")))
7106 (defun org-goto-right ()
7107 "Finish `org-goto' by going to the new location."
7108 (interactive)
7109 (if (org-at-heading-p)
7110 (progn
7111 (setq org-goto-selected-point (point)
7112 org-goto-exit-command 'right)
7113 (throw 'exit nil))
7114 (error "Not on a heading")))
7116 (defun org-goto-quit ()
7117 "Finish `org-goto' without cursor motion."
7118 (interactive)
7119 (setq org-goto-selected-point nil)
7120 (setq org-goto-exit-command 'quit)
7121 (throw 'exit nil))
7123 ;;; Indirect buffer display of subtrees
7125 (defvar org-indirect-dedicated-frame nil
7126 "This is the frame being used for indirect tree display.")
7127 (defvar org-last-indirect-buffer nil)
7129 (defun org-tree-to-indirect-buffer (&optional arg)
7130 "Create indirect buffer and narrow it to current subtree.
7131 With numerical prefix ARG, go up to this level and then take that tree.
7132 If ARG is negative, go up that many levels.
7133 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7134 indirect buffer previously made with this command, to avoid proliferation of
7135 indirect buffers. However, when you call the command with a \
7136 \\[universal-argument] prefix, or
7137 when `org-indirect-buffer-display' is `new-frame', the last buffer
7138 is kept so that you can work with several indirect buffers at the same time.
7139 If `org-indirect-buffer-display' is `dedicated-frame', the \
7140 \\[universal-argument] prefix also
7141 requests that a new frame be made for the new buffer, so that the dedicated
7142 frame is not changed."
7143 (interactive "P")
7144 (let ((cbuf (current-buffer))
7145 (cwin (selected-window))
7146 (pos (point))
7147 beg end level heading ibuf)
7148 (save-excursion
7149 (org-back-to-heading t)
7150 (when (numberp arg)
7151 (setq level (org-outline-level))
7152 (if (< arg 0) (setq arg (+ level arg)))
7153 (while (> (setq level (org-outline-level)) arg)
7154 (outline-up-heading 1 t)))
7155 (setq beg (point)
7156 heading (org-get-heading))
7157 (org-end-of-subtree t t)
7158 (if (org-at-heading-p) (backward-char 1))
7159 (setq end (point)))
7160 (if (and (buffer-live-p org-last-indirect-buffer)
7161 (not (eq org-indirect-buffer-display 'new-frame))
7162 (not arg))
7163 (kill-buffer org-last-indirect-buffer))
7164 (setq ibuf (org-get-indirect-buffer cbuf)
7165 org-last-indirect-buffer ibuf)
7166 (cond
7167 ((or (eq org-indirect-buffer-display 'new-frame)
7168 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7169 (select-frame (make-frame))
7170 (delete-other-windows)
7171 (org-pop-to-buffer-same-window ibuf)
7172 (org-set-frame-title heading))
7173 ((eq org-indirect-buffer-display 'dedicated-frame)
7174 (raise-frame
7175 (select-frame (or (and org-indirect-dedicated-frame
7176 (frame-live-p org-indirect-dedicated-frame)
7177 org-indirect-dedicated-frame)
7178 (setq org-indirect-dedicated-frame (make-frame)))))
7179 (delete-other-windows)
7180 (org-pop-to-buffer-same-window ibuf)
7181 (org-set-frame-title (concat "Indirect: " heading)))
7182 ((eq org-indirect-buffer-display 'current-window)
7183 (org-pop-to-buffer-same-window ibuf))
7184 ((eq org-indirect-buffer-display 'other-window)
7185 (pop-to-buffer ibuf))
7186 (t (error "Invalid value")))
7187 (if (featurep 'xemacs)
7188 (save-excursion (org-mode) (turn-on-font-lock)))
7189 (narrow-to-region beg end)
7190 (show-all)
7191 (goto-char pos)
7192 (run-hook-with-args 'org-cycle-hook 'all)
7193 (and (window-live-p cwin) (select-window cwin))))
7195 (defun org-get-indirect-buffer (&optional buffer)
7196 (setq buffer (or buffer (current-buffer)))
7197 (let ((n 1) (base (buffer-name buffer)) bname)
7198 (while (buffer-live-p
7199 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7200 (setq n (1+ n)))
7201 (condition-case nil
7202 (make-indirect-buffer buffer bname 'clone)
7203 (error (make-indirect-buffer buffer bname)))))
7205 (defun org-set-frame-title (title)
7206 "Set the title of the current frame to the string TITLE."
7207 ;; FIXME: how to name a single frame in XEmacs???
7208 (unless (featurep 'xemacs)
7209 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7211 ;;;; Structure editing
7213 ;;; Inserting headlines
7215 (defun org-previous-line-empty-p ()
7216 (save-excursion
7217 (and (not (bobp))
7218 (or (beginning-of-line 0) t)
7219 (save-match-data
7220 (looking-at "[ \t]*$")))))
7222 (defun org-insert-heading (&optional force-heading invisible-ok)
7223 "Insert a new heading or item with same depth at point.
7224 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7225 If point is at the beginning of a headline, insert a sibling before the
7226 current headline. If point is not at the beginning, split the line,
7227 create the new headline with the text in the current line after point
7228 \(but see also the variable `org-M-RET-may-split-line').
7230 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7231 This is important for non-interactive uses of the command."
7232 (interactive "P")
7233 (if (or (= (buffer-size) 0)
7234 (and (not (save-excursion
7235 (and (ignore-errors (org-back-to-heading invisible-ok))
7236 (org-at-heading-p))))
7237 (or force-heading (not (org-in-item-p)))))
7238 (progn
7239 (insert "\n* ")
7240 (run-hooks 'org-insert-heading-hook))
7241 (when (or force-heading (not (org-insert-item)))
7242 (let* ((empty-line-p nil)
7243 (level nil)
7244 (on-heading (org-at-heading-p))
7245 (head (save-excursion
7246 (condition-case nil
7247 (progn
7248 (org-back-to-heading invisible-ok)
7249 (when (and (not on-heading)
7250 (featurep 'org-inlinetask)
7251 (integerp org-inlinetask-min-level)
7252 (>= (length (match-string 0))
7253 org-inlinetask-min-level))
7254 ;; Find a heading level before the inline task
7255 (while (and (setq level (org-up-heading-safe))
7256 (>= level org-inlinetask-min-level)))
7257 (if (org-at-heading-p)
7258 (org-back-to-heading invisible-ok)
7259 (error "This should not happen")))
7260 (setq empty-line-p (org-previous-line-empty-p))
7261 (match-string 0))
7262 (error "*"))))
7263 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7264 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7265 pos hide-previous previous-pos)
7266 (cond
7267 ((and (org-at-heading-p) (bolp)
7268 (or (bobp)
7269 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7270 ;; insert before the current line
7271 (open-line (if blank 2 1)))
7272 ((and (bolp)
7273 (not org-insert-heading-respect-content)
7274 (or (bobp)
7275 (save-excursion
7276 (backward-char 1) (not (outline-invisible-p)))))
7277 ;; insert right here
7278 nil)
7280 ;; somewhere in the line
7281 (save-excursion
7282 (setq previous-pos (point-at-bol))
7283 (end-of-line)
7284 (setq hide-previous (outline-invisible-p)))
7285 (and org-insert-heading-respect-content (org-show-subtree))
7286 (let ((split
7287 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7288 (save-excursion
7289 (let ((p (point)))
7290 (goto-char (point-at-bol))
7291 (and (looking-at org-complex-heading-regexp)
7292 (match-beginning 4)
7293 (> p (match-beginning 4)))))))
7294 tags pos)
7295 (cond
7296 (org-insert-heading-respect-content
7297 (org-end-of-subtree nil t)
7298 (when (featurep 'org-inlinetask)
7299 (while (and (not (eobp))
7300 (looking-at "\\(\\*+\\)[ \t]+")
7301 (>= (length (match-string 1))
7302 org-inlinetask-min-level))
7303 (org-end-of-subtree nil t)))
7304 (or (bolp) (newline))
7305 (or (org-previous-line-empty-p)
7306 (and blank (newline)))
7307 (open-line 1))
7308 ((org-at-heading-p)
7309 (when hide-previous
7310 (show-children)
7311 (org-show-entry))
7312 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7313 (setq tags (and (match-end 2) (match-string 2)))
7314 (and (match-end 1)
7315 (delete-region (match-beginning 1) (match-end 1)))
7316 (setq pos (point-at-bol))
7317 (or split (end-of-line 1))
7318 (delete-horizontal-space)
7319 (if (string-match "\\`\\*+\\'"
7320 (buffer-substring (point-at-bol) (point)))
7321 (insert " "))
7322 (newline (if blank 2 1))
7323 (when tags
7324 (save-excursion
7325 (goto-char pos)
7326 (end-of-line 1)
7327 (insert " " tags)
7328 (org-set-tags nil 'align))))
7330 (or split (end-of-line 1))
7331 (newline (if blank 2 1)))))))
7332 (insert head) (just-one-space)
7333 (setq pos (point))
7334 (end-of-line 1)
7335 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7336 (when (and org-insert-heading-respect-content hide-previous)
7337 (save-excursion
7338 (goto-char previous-pos)
7339 (hide-subtree)))
7340 (run-hooks 'org-insert-heading-hook)))))
7342 (defun org-get-heading (&optional no-tags no-todo)
7343 "Return the heading of the current entry, without the stars.
7344 When NO-TAGS is non-nil, don't include tags.
7345 When NO-TODO is non-nil, don't include TODO keywords."
7346 (save-excursion
7347 (org-back-to-heading t)
7348 (cond
7349 ((and no-tags no-todo)
7350 (looking-at org-complex-heading-regexp)
7351 (match-string 4))
7352 (no-tags
7353 (looking-at (concat org-outline-regexp
7354 "\\(.*?\\)"
7355 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7356 (match-string 1))
7357 (no-todo
7358 (looking-at org-todo-line-regexp)
7359 (match-string 3))
7360 (t (looking-at org-heading-regexp)
7361 (match-string 2)))))
7363 (defun org-heading-components ()
7364 "Return the components of the current heading.
7365 This is a list with the following elements:
7366 - the level as an integer
7367 - the reduced level, different if `org-odd-levels-only' is set.
7368 - the TODO keyword, or nil
7369 - the priority character, like ?A, or nil if no priority is given
7370 - the headline text itself, or the tags string if no headline text
7371 - the tags string, or nil."
7372 (save-excursion
7373 (org-back-to-heading t)
7374 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7375 (list (length (match-string 1))
7376 (org-reduced-level (length (match-string 1)))
7377 (org-match-string-no-properties 2)
7378 (and (match-end 3) (aref (match-string 3) 2))
7379 (org-match-string-no-properties 4)
7380 (org-match-string-no-properties 5)))))
7382 (defun org-get-entry ()
7383 "Get the entry text, after heading, entire subtree."
7384 (save-excursion
7385 (org-back-to-heading t)
7386 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7388 (defun org-insert-heading-after-current ()
7389 "Insert a new heading with same level as current, after current subtree."
7390 (interactive)
7391 (org-back-to-heading)
7392 (org-insert-heading)
7393 (org-move-subtree-down)
7394 (end-of-line 1))
7396 (defun org-insert-heading-respect-content ()
7397 (interactive)
7398 (let ((org-insert-heading-respect-content t))
7399 (org-insert-heading t)))
7401 (defun org-insert-todo-heading-respect-content (&optional force-state)
7402 (interactive "P")
7403 (let ((org-insert-heading-respect-content t))
7404 (org-insert-todo-heading force-state t)))
7406 (defun org-insert-todo-heading (arg &optional force-heading)
7407 "Insert a new heading with the same level and TODO state as current heading.
7408 If the heading has no TODO state, or if the state is DONE, use the first
7409 state (TODO by default). Also with prefix arg, force first state."
7410 (interactive "P")
7411 (when (or force-heading (not (org-insert-item 'checkbox)))
7412 (org-insert-heading force-heading)
7413 (save-excursion
7414 (org-back-to-heading)
7415 (outline-previous-heading)
7416 (looking-at org-todo-line-regexp))
7417 (let*
7418 ((new-mark-x
7419 (if (or arg
7420 (not (match-beginning 2))
7421 (member (match-string 2) org-done-keywords))
7422 (car org-todo-keywords-1)
7423 (match-string 2)))
7424 (new-mark
7426 (run-hook-with-args-until-success
7427 'org-todo-get-default-hook new-mark-x nil)
7428 new-mark-x)))
7429 (beginning-of-line 1)
7430 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7431 (if org-treat-insert-todo-heading-as-state-change
7432 (org-todo new-mark)
7433 (insert new-mark " "))))
7434 (when org-provide-todo-statistics
7435 (org-update-parent-todo-statistics))))
7437 (defun org-insert-subheading (arg)
7438 "Insert a new subheading and demote it.
7439 Works for outline headings and for plain lists alike."
7440 (interactive "P")
7441 (org-insert-heading arg)
7442 (cond
7443 ((org-at-heading-p) (org-do-demote))
7444 ((org-at-item-p) (org-indent-item))))
7446 (defun org-insert-todo-subheading (arg)
7447 "Insert a new subheading with TODO keyword or checkbox and demote it.
7448 Works for outline headings and for plain lists alike."
7449 (interactive "P")
7450 (org-insert-todo-heading arg)
7451 (cond
7452 ((org-at-heading-p) (org-do-demote))
7453 ((org-at-item-p) (org-indent-item))))
7455 ;;; Promotion and Demotion
7457 (defvar org-after-demote-entry-hook nil
7458 "Hook run after an entry has been demoted.
7459 The cursor will be at the beginning of the entry.
7460 When a subtree is being demoted, the hook will be called for each node.")
7462 (defvar org-after-promote-entry-hook nil
7463 "Hook run after an entry has been promoted.
7464 The cursor will be at the beginning of the entry.
7465 When a subtree is being promoted, the hook will be called for each node.")
7467 (defun org-promote-subtree ()
7468 "Promote the entire subtree.
7469 See also `org-promote'."
7470 (interactive)
7471 (save-excursion
7472 (org-with-limited-levels (org-map-tree 'org-promote)))
7473 (org-fix-position-after-promote))
7475 (defun org-demote-subtree ()
7476 "Demote the entire subtree. See `org-demote'.
7477 See also `org-promote'."
7478 (interactive)
7479 (save-excursion
7480 (org-with-limited-levels (org-map-tree 'org-demote)))
7481 (org-fix-position-after-promote))
7484 (defun org-do-promote ()
7485 "Promote the current heading higher up the tree.
7486 If the region is active in `transient-mark-mode', promote all headings
7487 in the region."
7488 (interactive)
7489 (save-excursion
7490 (if (org-region-active-p)
7491 (org-map-region 'org-promote (region-beginning) (region-end))
7492 (org-promote)))
7493 (org-fix-position-after-promote))
7495 (defun org-do-demote ()
7496 "Demote the current heading lower down the tree.
7497 If the region is active in `transient-mark-mode', demote all headings
7498 in the region."
7499 (interactive)
7500 (save-excursion
7501 (if (org-region-active-p)
7502 (org-map-region 'org-demote (region-beginning) (region-end))
7503 (org-demote)))
7504 (org-fix-position-after-promote))
7506 (defun org-fix-position-after-promote ()
7507 "Make sure that after pro/demotion cursor position is right."
7508 (let ((pos (point)))
7509 (when (save-excursion
7510 (beginning-of-line 1)
7511 (looking-at org-todo-line-regexp)
7512 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7513 (cond ((eobp) (insert " "))
7514 ((eolp) (insert " "))
7515 ((equal (char-after) ?\ ) (forward-char 1))))))
7517 (defun org-current-level ()
7518 "Return the level of the current entry, or nil if before the first headline.
7519 The level is the number of stars at the beginning of the headline."
7520 (save-excursion
7521 (org-with-limited-levels
7522 (if (ignore-errors (org-back-to-heading t))
7523 (funcall outline-level)))))
7525 (defun org-get-previous-line-level ()
7526 "Return the outline depth of the last headline before the current line.
7527 Returns 0 for the first headline in the buffer, and nil if before the
7528 first headline."
7529 (let ((current-level (org-current-level))
7530 (prev-level (when (> (line-number-at-pos) 1)
7531 (save-excursion
7532 (beginning-of-line 0)
7533 (org-current-level)))))
7534 (cond ((null current-level) nil) ; Before first headline
7535 ((null prev-level) 0) ; At first headline
7536 (prev-level))))
7538 (defun org-reduced-level (l)
7539 "Compute the effective level of a heading.
7540 This takes into account the setting of `org-odd-levels-only'."
7541 (cond
7542 ((zerop l) 0)
7543 (org-odd-levels-only (1+ (floor (/ l 2))))
7544 (t l)))
7546 (defun org-level-increment ()
7547 "Return the number of stars that will be added or removed at a
7548 time to headlines when structure editing, based on the value of
7549 `org-odd-levels-only'."
7550 (if org-odd-levels-only 2 1))
7552 (defun org-get-valid-level (level &optional change)
7553 "Rectify a level change under the influence of `org-odd-levels-only'
7554 LEVEL is a current level, CHANGE is by how much the level should be
7555 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7556 even level numbers will become the next higher odd number."
7557 (if org-odd-levels-only
7558 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7559 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7560 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7561 (max 1 (+ level (or change 0)))))
7563 (if (boundp 'define-obsolete-function-alias)
7564 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7565 (define-obsolete-function-alias 'org-get-legal-level
7566 'org-get-valid-level)
7567 (define-obsolete-function-alias 'org-get-legal-level
7568 'org-get-valid-level "23.1")))
7570 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7571 ;; ̀org-with-limited-levels'
7572 (defun org-promote ()
7573 "Promote the current heading higher up the tree.
7574 If the region is active in `transient-mark-mode', promote all headings
7575 in the region."
7576 (org-back-to-heading t)
7577 (let* ((level (save-match-data (funcall outline-level)))
7578 (after-change-functions (remove 'flyspell-after-change-function
7579 after-change-functions))
7580 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7581 (diff (abs (- level (length up-head) -1))))
7582 (cond ((and (= level 1) org-called-with-limited-levels
7583 org-allow-promoting-top-level-subtree)
7584 (replace-match "# " nil t))
7585 ((= level 1)
7586 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7587 (t (replace-match up-head nil t)))
7588 ;; Fixup tag positioning
7589 (unless (= level 1)
7590 (and org-auto-align-tags (org-set-tags nil t))
7591 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7592 (run-hooks 'org-after-promote-entry-hook)))
7594 (defun org-demote ()
7595 "Demote the current heading lower down the tree.
7596 If the region is active in `transient-mark-mode', demote all headings
7597 in the region."
7598 (org-back-to-heading t)
7599 (let* ((level (save-match-data (funcall outline-level)))
7600 (after-change-functions (remove 'flyspell-after-change-function
7601 after-change-functions))
7602 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7603 (diff (abs (- level (length down-head) -1))))
7604 (replace-match down-head nil t)
7605 ;; Fixup tag positioning
7606 (and org-auto-align-tags (org-set-tags nil t))
7607 (if org-adapt-indentation (org-fixup-indentation diff))
7608 (run-hooks 'org-after-demote-entry-hook)))
7610 (defun org-cycle-level ()
7611 "Cycle the level of an empty headline through possible states.
7612 This goes first to child, then to parent, level, then up the hierarchy.
7613 After top level, it switches back to sibling level."
7614 (interactive)
7615 (let ((org-adapt-indentation nil))
7616 (when (org-point-at-end-of-empty-headline)
7617 (setq this-command 'org-cycle-level) ; Only needed for caching
7618 (let ((cur-level (org-current-level))
7619 (prev-level (org-get-previous-line-level)))
7620 (cond
7621 ;; If first headline in file, promote to top-level.
7622 ((= prev-level 0)
7623 (loop repeat (/ (- cur-level 1) (org-level-increment))
7624 do (org-do-promote)))
7625 ;; If same level as prev, demote one.
7626 ((= prev-level cur-level)
7627 (org-do-demote))
7628 ;; If parent is top-level, promote to top level if not already.
7629 ((= prev-level 1)
7630 (loop repeat (/ (- cur-level 1) (org-level-increment))
7631 do (org-do-promote)))
7632 ;; If top-level, return to prev-level.
7633 ((= cur-level 1)
7634 (loop repeat (/ (- prev-level 1) (org-level-increment))
7635 do (org-do-demote)))
7636 ;; If less than prev-level, promote one.
7637 ((< cur-level prev-level)
7638 (org-do-promote))
7639 ;; If deeper than prev-level, promote until higher than
7640 ;; prev-level.
7641 ((> cur-level prev-level)
7642 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7643 do (org-do-promote))))
7644 t))))
7646 (defun org-map-tree (fun)
7647 "Call FUN for every heading underneath the current one."
7648 (org-back-to-heading)
7649 (let ((level (funcall outline-level)))
7650 (save-excursion
7651 (funcall fun)
7652 (while (and (progn
7653 (outline-next-heading)
7654 (> (funcall outline-level) level))
7655 (not (eobp)))
7656 (funcall fun)))))
7658 (defun org-map-region (fun beg end)
7659 "Call FUN for every heading between BEG and END."
7660 (let ((org-ignore-region t))
7661 (save-excursion
7662 (setq end (copy-marker end))
7663 (goto-char beg)
7664 (if (and (re-search-forward org-outline-regexp-bol nil t)
7665 (< (point) end))
7666 (funcall fun))
7667 (while (and (progn
7668 (outline-next-heading)
7669 (< (point) end))
7670 (not (eobp)))
7671 (funcall fun)))))
7673 (defvar org-property-end-re) ; silence byte-compiler
7674 (defun org-fixup-indentation (diff)
7675 "Change the indentation in the current entry by DIFF.
7676 However, if any line in the current entry has no indentation, or if it
7677 would end up with no indentation after the change, nothing at all is done."
7678 (save-excursion
7679 (let ((end (save-excursion (outline-next-heading)
7680 (point-marker)))
7681 (prohibit (if (> diff 0)
7682 "^\\S-"
7683 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7684 col)
7685 (unless (save-excursion (end-of-line 1)
7686 (re-search-forward prohibit end t))
7687 (while (and (< (point) end)
7688 (re-search-forward "^[ \t]+" end t))
7689 (goto-char (match-end 0))
7690 (setq col (current-column))
7691 (if (< diff 0) (replace-match ""))
7692 (org-indent-to-column (+ diff col))))
7693 (move-marker end nil))))
7695 (defun org-convert-to-odd-levels ()
7696 "Convert an org-mode file with all levels allowed to one with odd levels.
7697 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7698 level 5 etc."
7699 (interactive)
7700 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7701 (let ((outline-level 'org-outline-level)
7702 (org-odd-levels-only nil) n)
7703 (save-excursion
7704 (goto-char (point-min))
7705 (while (re-search-forward "^\\*\\*+ " nil t)
7706 (setq n (- (length (match-string 0)) 2))
7707 (while (>= (setq n (1- n)) 0)
7708 (org-demote))
7709 (end-of-line 1))))))
7711 (defun org-convert-to-oddeven-levels ()
7712 "Convert an org-mode file with only odd levels to one with odd/even levels.
7713 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7714 file contains a section with an even level, conversion would
7715 destroy the structure of the file. An error is signaled in this
7716 case."
7717 (interactive)
7718 (goto-char (point-min))
7719 ;; First check if there are no even levels
7720 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7721 (org-show-context t)
7722 (error "Not all levels are odd in this file. Conversion not possible"))
7723 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7724 (let ((outline-regexp org-outline-regexp)
7725 (outline-level 'org-outline-level)
7726 (org-odd-levels-only nil) n)
7727 (save-excursion
7728 (goto-char (point-min))
7729 (while (re-search-forward "^\\*\\*+ " nil t)
7730 (setq n (/ (1- (length (match-string 0))) 2))
7731 (while (>= (setq n (1- n)) 0)
7732 (org-promote))
7733 (end-of-line 1))))))
7735 (defun org-tr-level (n)
7736 "Make N odd if required."
7737 (if org-odd-levels-only (1+ (/ n 2)) n))
7739 ;;; Vertical tree motion, cutting and pasting of subtrees
7741 (defun org-move-subtree-up (&optional arg)
7742 "Move the current subtree up past ARG headlines of the same level."
7743 (interactive "p")
7744 (org-move-subtree-down (- (prefix-numeric-value arg))))
7746 (defun org-move-subtree-down (&optional arg)
7747 "Move the current subtree down past ARG headlines of the same level."
7748 (interactive "p")
7749 (setq arg (prefix-numeric-value arg))
7750 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7751 'org-get-last-sibling))
7752 (ins-point (make-marker))
7753 (cnt (abs arg))
7754 (col (current-column))
7755 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7756 ;; Select the tree
7757 (org-back-to-heading)
7758 (setq beg0 (point))
7759 (save-excursion
7760 (setq ne-beg (org-back-over-empty-lines))
7761 (setq beg (point)))
7762 (save-match-data
7763 (save-excursion (outline-end-of-heading)
7764 (setq folded (outline-invisible-p)))
7765 (outline-end-of-subtree))
7766 (outline-next-heading)
7767 (setq ne-end (org-back-over-empty-lines))
7768 (setq end (point))
7769 (goto-char beg0)
7770 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7771 ;; include less whitespace
7772 (save-excursion
7773 (goto-char beg)
7774 (forward-line (- ne-beg ne-end))
7775 (setq beg (point))))
7776 ;; Find insertion point, with error handling
7777 (while (> cnt 0)
7778 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7779 (progn (goto-char beg0)
7780 (error "Cannot move past superior level or buffer limit")))
7781 (setq cnt (1- cnt)))
7782 (if (> arg 0)
7783 ;; Moving forward - still need to move over subtree
7784 (progn (org-end-of-subtree t t)
7785 (save-excursion
7786 (org-back-over-empty-lines)
7787 (or (bolp) (newline)))))
7788 (setq ne-ins (org-back-over-empty-lines))
7789 (move-marker ins-point (point))
7790 (setq txt (buffer-substring beg end))
7791 (org-save-markers-in-region beg end)
7792 (delete-region beg end)
7793 (org-remove-empty-overlays-at beg)
7794 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7795 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7796 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7797 (let ((bbb (point)))
7798 (insert-before-markers txt)
7799 (org-reinstall-markers-in-region bbb)
7800 (move-marker ins-point bbb))
7801 (or (bolp) (insert "\n"))
7802 (setq ins-end (point))
7803 (goto-char ins-point)
7804 (org-skip-whitespace)
7805 (when (and (< arg 0)
7806 (org-first-sibling-p)
7807 (> ne-ins ne-beg))
7808 ;; Move whitespace back to beginning
7809 (save-excursion
7810 (goto-char ins-end)
7811 (let ((kill-whole-line t))
7812 (kill-line (- ne-ins ne-beg)) (point)))
7813 (insert (make-string (- ne-ins ne-beg) ?\n)))
7814 (move-marker ins-point nil)
7815 (if folded
7816 (hide-subtree)
7817 (org-show-entry)
7818 (show-children)
7819 (org-cycle-hide-drawers 'children))
7820 (org-clean-visibility-after-subtree-move)
7821 ;; move back to the initial column we were at
7822 (move-to-column col)))
7824 (defvar org-subtree-clip ""
7825 "Clipboard for cut and paste of subtrees.
7826 This is actually only a copy of the kill, because we use the normal kill
7827 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7829 (defvar org-subtree-clip-folded nil
7830 "Was the last copied subtree folded?
7831 This is used to fold the tree back after pasting.")
7833 (defun org-cut-subtree (&optional n)
7834 "Cut the current subtree into the clipboard.
7835 With prefix arg N, cut this many sequential subtrees.
7836 This is a short-hand for marking the subtree and then cutting it."
7837 (interactive "p")
7838 (org-copy-subtree n 'cut))
7840 (defun org-copy-subtree (&optional n cut force-store-markers)
7841 "Cut the current subtree into the clipboard.
7842 With prefix arg N, cut this many sequential subtrees.
7843 This is a short-hand for marking the subtree and then copying it.
7844 If CUT is non-nil, actually cut the subtree.
7845 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7846 of some markers in the region, even if CUT is non-nil. This is
7847 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7848 (interactive "p")
7849 (let (beg end folded (beg0 (point)))
7850 (if (org-called-interactively-p 'any)
7851 (org-back-to-heading nil) ; take what looks like a subtree
7852 (org-back-to-heading t)) ; take what is really there
7853 (org-back-over-empty-lines)
7854 (setq beg (point))
7855 (skip-chars-forward " \t\r\n")
7856 (save-match-data
7857 (save-excursion (outline-end-of-heading)
7858 (setq folded (outline-invisible-p)))
7859 (condition-case nil
7860 (org-forward-heading-same-level (1- n) t)
7861 (error nil))
7862 (org-end-of-subtree t t))
7863 (org-back-over-empty-lines)
7864 (setq end (point))
7865 (goto-char beg0)
7866 (when (> end beg)
7867 (setq org-subtree-clip-folded folded)
7868 (when (or cut force-store-markers)
7869 (org-save-markers-in-region beg end))
7870 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7871 (setq org-subtree-clip (current-kill 0))
7872 (message "%s: Subtree(s) with %d characters"
7873 (if cut "Cut" "Copied")
7874 (length org-subtree-clip)))))
7876 (defun org-paste-subtree (&optional level tree for-yank)
7877 "Paste the clipboard as a subtree, with modification of headline level.
7878 The entire subtree is promoted or demoted in order to match a new headline
7879 level.
7881 If the cursor is at the beginning of a headline, the same level as
7882 that headline is used to paste the tree
7884 If not, the new level is derived from the *visible* headings
7885 before and after the insertion point, and taken to be the inferior headline
7886 level of the two. So if the previous visible heading is level 3 and the
7887 next is level 4 (or vice versa), level 4 will be used for insertion.
7888 This makes sure that the subtree remains an independent subtree and does
7889 not swallow low level entries.
7891 You can also force a different level, either by using a numeric prefix
7892 argument, or by inserting the heading marker by hand. For example, if the
7893 cursor is after \"*****\", then the tree will be shifted to level 5.
7895 If optional TREE is given, use this text instead of the kill ring.
7897 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7898 move back over whitespace before inserting, and move point to the end of
7899 the inserted text when done."
7900 (interactive "P")
7901 (setq tree (or tree (and kill-ring (current-kill 0))))
7902 (unless (org-kill-is-subtree-p tree)
7903 (error "%s"
7904 (substitute-command-keys
7905 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7906 (org-with-limited-levels
7907 (let* ((visp (not (outline-invisible-p)))
7908 (txt tree)
7909 (^re_ "\\(\\*+\\)[ \t]*")
7910 (old-level (if (string-match org-outline-regexp-bol txt)
7911 (- (match-end 0) (match-beginning 0) 1)
7912 -1))
7913 (force-level (cond (level (prefix-numeric-value level))
7914 ((and (looking-at "[ \t]*$")
7915 (string-match
7916 "^\\*+$" (buffer-substring
7917 (point-at-bol) (point))))
7918 (- (match-end 1) (match-beginning 1)))
7919 ((and (bolp)
7920 (looking-at org-outline-regexp))
7921 (- (match-end 0) (point) 1))))
7922 (previous-level (save-excursion
7923 (condition-case nil
7924 (progn
7925 (outline-previous-visible-heading 1)
7926 (if (looking-at ^re_)
7927 (- (match-end 0) (match-beginning 0) 1)
7929 (error 1))))
7930 (next-level (save-excursion
7931 (condition-case nil
7932 (progn
7933 (or (looking-at org-outline-regexp)
7934 (outline-next-visible-heading 1))
7935 (if (looking-at ^re_)
7936 (- (match-end 0) (match-beginning 0) 1)
7938 (error 1))))
7939 (new-level (or force-level (max previous-level next-level)))
7940 (shift (if (or (= old-level -1)
7941 (= new-level -1)
7942 (= old-level new-level))
7944 (- new-level old-level)))
7945 (delta (if (> shift 0) -1 1))
7946 (func (if (> shift 0) 'org-demote 'org-promote))
7947 (org-odd-levels-only nil)
7948 beg end newend)
7949 ;; Remove the forced level indicator
7950 (if force-level
7951 (delete-region (point-at-bol) (point)))
7952 ;; Paste
7953 (beginning-of-line (if (bolp) 1 2))
7954 (unless for-yank (org-back-over-empty-lines))
7955 (setq beg (point))
7956 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7957 (insert-before-markers txt)
7958 (unless (string-match "\n\\'" txt) (insert "\n"))
7959 (setq newend (point))
7960 (org-reinstall-markers-in-region beg)
7961 (setq end (point))
7962 (goto-char beg)
7963 (skip-chars-forward " \t\n\r")
7964 (setq beg (point))
7965 (if (and (outline-invisible-p) visp)
7966 (save-excursion (outline-show-heading)))
7967 ;; Shift if necessary
7968 (unless (= shift 0)
7969 (save-restriction
7970 (narrow-to-region beg end)
7971 (while (not (= shift 0))
7972 (org-map-region func (point-min) (point-max))
7973 (setq shift (+ delta shift)))
7974 (goto-char (point-min))
7975 (setq newend (point-max))))
7976 (when (or (org-called-interactively-p 'interactive) for-yank)
7977 (message "Clipboard pasted as level %d subtree" new-level))
7978 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7979 kill-ring
7980 (eq org-subtree-clip (current-kill 0))
7981 org-subtree-clip-folded)
7982 ;; The tree was folded before it was killed/copied
7983 (hide-subtree))
7984 (and for-yank (goto-char newend)))))
7986 (defun org-kill-is-subtree-p (&optional txt)
7987 "Check if the current kill is an outline subtree, or a set of trees.
7988 Returns nil if kill does not start with a headline, or if the first
7989 headline level is not the largest headline level in the tree.
7990 So this will actually accept several entries of equal levels as well,
7991 which is OK for `org-paste-subtree'.
7992 If optional TXT is given, check this string instead of the current kill."
7993 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7994 (re (org-get-limited-outline-regexp))
7995 (^re (concat "^" re))
7996 (start-level (and kill
7997 (string-match
7998 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7999 kill)
8000 (- (match-end 2) (match-beginning 2) 1)))
8001 (start (1+ (or (match-beginning 2) -1))))
8002 (if (not start-level)
8003 (progn
8004 nil) ;; does not even start with a heading
8005 (catch 'exit
8006 (while (setq start (string-match ^re kill (1+ start)))
8007 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8008 (throw 'exit nil)))
8009 t))))
8011 (defvar org-markers-to-move nil
8012 "Markers that should be moved with a cut-and-paste operation.
8013 Those markers are stored together with their positions relative to
8014 the start of the region.")
8016 (defun org-save-markers-in-region (beg end)
8017 "Check markers in region.
8018 If these markers are between BEG and END, record their position relative
8019 to BEG, so that after moving the block of text, we can put the markers back
8020 into place.
8021 This function gets called just before an entry or tree gets cut from the
8022 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8023 called immediately, to move the markers with the entries."
8024 (setq org-markers-to-move nil)
8025 (when (featurep 'org-clock)
8026 (org-clock-save-markers-for-cut-and-paste beg end))
8027 (when (featurep 'org-agenda)
8028 (org-agenda-save-markers-for-cut-and-paste beg end)))
8030 (defun org-check-and-save-marker (marker beg end)
8031 "Check if MARKER is between BEG and END.
8032 If yes, remember the marker and the distance to BEG."
8033 (when (and (marker-buffer marker)
8034 (equal (marker-buffer marker) (current-buffer)))
8035 (if (and (>= marker beg) (< marker end))
8036 (push (cons marker (- marker beg)) org-markers-to-move))))
8038 (defun org-reinstall-markers-in-region (beg)
8039 "Move all remembered markers to their position relative to BEG."
8040 (mapc (lambda (x)
8041 (move-marker (car x) (+ beg (cdr x))))
8042 org-markers-to-move)
8043 (setq org-markers-to-move nil))
8045 (defun org-narrow-to-subtree ()
8046 "Narrow buffer to the current subtree."
8047 (interactive)
8048 (save-excursion
8049 (save-match-data
8050 (org-with-limited-levels
8051 (narrow-to-region
8052 (progn (org-back-to-heading t) (point))
8053 (progn (org-end-of-subtree t t)
8054 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8055 (point)))))))
8057 (defun org-narrow-to-block ()
8058 "Narrow buffer to the current block."
8059 (interactive)
8060 (let* ((case-fold-search t)
8061 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8062 "^[ \t]*#\\+end_.*")))
8063 (if blockp
8064 (narrow-to-region (car blockp) (cdr blockp))
8065 (error "Not in a block"))))
8067 (eval-when-compile
8068 (defvar org-property-drawer-re))
8070 (defvar org-property-start-re) ;; defined below
8071 (defun org-clone-subtree-with-time-shift (n &optional shift)
8072 "Clone the task (subtree) at point N times.
8073 The clones will be inserted as siblings.
8075 In interactive use, the user will be prompted for the number of
8076 clones to be produced, and for a time SHIFT, which may be a
8077 repeater as used in time stamps, for example `+3d'.
8079 When a valid repeater is given and the entry contains any time
8080 stamps, the clones will become a sequence in time, with time
8081 stamps in the subtree shifted for each clone produced. If SHIFT
8082 is nil or the empty string, time stamps will be left alone. The
8083 ID property of the original subtree is removed.
8085 If the original subtree did contain time stamps with a repeater,
8086 the following will happen:
8087 - the repeater will be removed in each clone
8088 - an additional clone will be produced, with the current, unshifted
8089 date(s) in the entry.
8090 - the original entry will be placed *after* all the clones, with
8091 repeater intact.
8092 - the start days in the repeater in the original entry will be shifted
8093 to past the last clone.
8094 In this way you can spell out a number of instances of a repeating task,
8095 and still retain the repeater to cover future instances of the task."
8096 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8097 (let (beg end template task idprop
8098 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8099 (drawer-re org-drawer-regexp))
8100 (if (not (and (integerp n) (> n 0)))
8101 (error "Invalid number of replications %s" n))
8102 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8103 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8104 shift)))
8105 (error "Invalid shift specification %s" shift))
8106 (when doshift
8107 (setq shift-n (string-to-number (match-string 1 shift))
8108 shift-what (cdr (assoc (match-string 2 shift)
8109 '(("d" . day) ("w" . week)
8110 ("m" . month) ("y" . year))))))
8111 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8112 (setq nmin 1 nmax n)
8113 (org-back-to-heading t)
8114 (setq beg (point))
8115 (setq idprop (org-entry-get nil "ID"))
8116 (org-end-of-subtree t t)
8117 (or (bolp) (insert "\n"))
8118 (setq end (point))
8119 (setq template (buffer-substring beg end))
8120 (when (and doshift
8121 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8122 (delete-region beg end)
8123 (setq end beg)
8124 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8125 (goto-char end)
8126 (loop for n from nmin to nmax do
8127 ;; prepare clone
8128 (with-temp-buffer
8129 (insert template)
8130 (org-mode)
8131 (goto-char (point-min))
8132 (org-show-subtree)
8133 (and idprop (if org-clone-delete-id
8134 (org-entry-delete nil "ID")
8135 (org-id-get-create t)))
8136 (unless (= n 0)
8137 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8138 (kill-whole-line))
8139 (goto-char (point-min))
8140 (while (re-search-forward drawer-re nil t)
8141 (mapc (lambda (d)
8142 (org-remove-empty-drawer-at d (point))) org-drawers)))
8143 (goto-char (point-min))
8144 (when doshift
8145 (while (re-search-forward org-ts-regexp-both nil t)
8146 (org-timestamp-change (* n shift-n) shift-what))
8147 (unless (= n n-no-remove)
8148 (goto-char (point-min))
8149 (while (re-search-forward org-ts-regexp nil t)
8150 (save-excursion
8151 (goto-char (match-beginning 0))
8152 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8153 (delete-region (match-beginning 1) (match-end 1)))))))
8154 (setq task (buffer-string)))
8155 (insert task))
8156 (goto-char beg)))
8158 ;;; Outline Sorting
8160 (defun org-sort (with-case)
8161 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8162 Optional argument WITH-CASE means sort case-sensitively."
8163 (interactive "P")
8164 (cond
8165 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8166 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8168 (org-call-with-arg 'org-sort-entries with-case))))
8170 (defun org-sort-remove-invisible (s)
8171 (remove-text-properties 0 (length s) org-rm-props s)
8172 (while (string-match org-bracket-link-regexp s)
8173 (setq s (replace-match (if (match-end 2)
8174 (match-string 3 s)
8175 (match-string 1 s)) t t s)))
8178 (defvar org-priority-regexp) ; defined later in the file
8180 (defvar org-after-sorting-entries-or-items-hook nil
8181 "Hook that is run after a bunch of entries or items have been sorted.
8182 When children are sorted, the cursor is in the parent line when this
8183 hook gets called. When a region or a plain list is sorted, the cursor
8184 will be in the first entry of the sorted region/list.")
8186 (defun org-sort-entries
8187 (&optional with-case sorting-type getkey-func compare-func property)
8188 "Sort entries on a certain level of an outline tree.
8189 If there is an active region, the entries in the region are sorted.
8190 Else, if the cursor is before the first entry, sort the top-level items.
8191 Else, the children of the entry at point are sorted.
8193 Sorting can be alphabetically, numerically, by date/time as given by
8194 a time stamp, by a property or by priority.
8196 The command prompts for the sorting type unless it has been given to the
8197 function through the SORTING-TYPE argument, which needs to be a character,
8198 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8199 precise meaning of each character:
8201 n Numerically, by converting the beginning of the entry/item to a number.
8202 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8203 t By date/time, either the first active time stamp in the entry, or, if
8204 none exist, by the first inactive one.
8205 s By the scheduled date/time.
8206 d By deadline date/time.
8207 c By creation time, which is assumed to be the first inactive time stamp
8208 at the beginning of a line.
8209 p By priority according to the cookie.
8210 r By the value of a property.
8212 Capital letters will reverse the sort order.
8214 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8215 called with point at the beginning of the record. It must return either
8216 a string or a number that should serve as the sorting key for that record.
8218 Comparing entries ignores case by default. However, with an optional argument
8219 WITH-CASE, the sorting considers case as well."
8220 (interactive "P")
8221 (let ((case-func (if with-case 'identity 'downcase))
8222 start beg end stars re re2
8223 txt what tmp)
8224 ;; Find beginning and end of region to sort
8225 (cond
8226 ((org-region-active-p)
8227 ;; we will sort the region
8228 (setq end (region-end)
8229 what "region")
8230 (goto-char (region-beginning))
8231 (if (not (org-at-heading-p)) (outline-next-heading))
8232 (setq start (point)))
8233 ((or (org-at-heading-p)
8234 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8235 ;; we will sort the children of the current headline
8236 (org-back-to-heading)
8237 (setq start (point)
8238 end (progn (org-end-of-subtree t t)
8239 (or (bolp) (insert "\n"))
8240 (org-back-over-empty-lines)
8241 (point))
8242 what "children")
8243 (goto-char start)
8244 (show-subtree)
8245 (outline-next-heading))
8247 ;; we will sort the top-level entries in this file
8248 (goto-char (point-min))
8249 (or (org-at-heading-p) (outline-next-heading))
8250 (setq start (point))
8251 (goto-char (point-max))
8252 (beginning-of-line 1)
8253 (when (looking-at ".*?\\S-")
8254 ;; File ends in a non-white line
8255 (end-of-line 1)
8256 (insert "\n"))
8257 (setq end (point-max))
8258 (setq what "top-level")
8259 (goto-char start)
8260 (show-all)))
8262 (setq beg (point))
8263 (if (>= beg end) (error "Nothing to sort"))
8265 (looking-at "\\(\\*+\\)")
8266 (setq stars (match-string 1)
8267 re (concat "^" (regexp-quote stars) " +")
8268 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8269 txt (buffer-substring beg end))
8270 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8271 (if (and (not (equal stars "*")) (string-match re2 txt))
8272 (error "Region to sort contains a level above the first entry"))
8274 (unless sorting-type
8275 (message
8276 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8277 [t]ime [s]cheduled [d]eadline [c]reated
8278 A/N/T/S/D/C/P/O/F means reversed:"
8279 what)
8280 (setq sorting-type (read-char-exclusive))
8282 (and (= (downcase sorting-type) ?f)
8283 (setq getkey-func
8284 (org-icompleting-read "Sort using function: "
8285 obarray 'fboundp t nil nil))
8286 (setq getkey-func (intern getkey-func)))
8288 (and (= (downcase sorting-type) ?r)
8289 (setq property
8290 (org-icompleting-read "Property: "
8291 (mapcar 'list (org-buffer-property-keys t))
8292 nil t))))
8294 (message "Sorting entries...")
8296 (save-restriction
8297 (narrow-to-region start end)
8298 (let ((dcst (downcase sorting-type))
8299 (case-fold-search nil)
8300 (now (current-time)))
8301 (sort-subr
8302 (/= dcst sorting-type)
8303 ;; This function moves to the beginning character of the "record" to
8304 ;; be sorted.
8305 (lambda nil
8306 (if (re-search-forward re nil t)
8307 (goto-char (match-beginning 0))
8308 (goto-char (point-max))))
8309 ;; This function moves to the last character of the "record" being
8310 ;; sorted.
8311 (lambda nil
8312 (save-match-data
8313 (condition-case nil
8314 (outline-forward-same-level 1)
8315 (error
8316 (goto-char (point-max))))))
8317 ;; This function returns the value that gets sorted against.
8318 (lambda nil
8319 (cond
8320 ((= dcst ?n)
8321 (if (looking-at org-complex-heading-regexp)
8322 (string-to-number (match-string 4))
8323 nil))
8324 ((= dcst ?a)
8325 (if (looking-at org-complex-heading-regexp)
8326 (funcall case-func (match-string 4))
8327 nil))
8328 ((= dcst ?t)
8329 (let ((end (save-excursion (outline-next-heading) (point))))
8330 (if (or (re-search-forward org-ts-regexp end t)
8331 (re-search-forward org-ts-regexp-both end t))
8332 (org-time-string-to-seconds (match-string 0))
8333 (org-float-time now))))
8334 ((= dcst ?c)
8335 (let ((end (save-excursion (outline-next-heading) (point))))
8336 (if (re-search-forward
8337 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8338 end t)
8339 (org-time-string-to-seconds (match-string 0))
8340 (org-float-time now))))
8341 ((= dcst ?s)
8342 (let ((end (save-excursion (outline-next-heading) (point))))
8343 (if (re-search-forward org-scheduled-time-regexp end t)
8344 (org-time-string-to-seconds (match-string 1))
8345 (org-float-time now))))
8346 ((= dcst ?d)
8347 (let ((end (save-excursion (outline-next-heading) (point))))
8348 (if (re-search-forward org-deadline-time-regexp end t)
8349 (org-time-string-to-seconds (match-string 1))
8350 (org-float-time now))))
8351 ((= dcst ?p)
8352 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8353 (string-to-char (match-string 2))
8354 org-default-priority))
8355 ((= dcst ?r)
8356 (or (org-entry-get nil property) ""))
8357 ((= dcst ?o)
8358 (if (looking-at org-complex-heading-regexp)
8359 (- 9999 (length (member (match-string 2)
8360 org-todo-keywords-1)))))
8361 ((= dcst ?f)
8362 (if getkey-func
8363 (progn
8364 (setq tmp (funcall getkey-func))
8365 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8366 tmp)
8367 (error "Invalid key function `%s'" getkey-func)))
8368 (t (error "Invalid sorting type `%c'" sorting-type))))
8370 (cond
8371 ((= dcst ?a) 'string<)
8372 ((= dcst ?f) compare-func)
8373 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8374 (run-hooks 'org-after-sorting-entries-or-items-hook)
8375 (message "Sorting entries...done")))
8377 (defun org-do-sort (table what &optional with-case sorting-type)
8378 "Sort TABLE of WHAT according to SORTING-TYPE.
8379 The user will be prompted for the SORTING-TYPE if the call to this
8380 function does not specify it. WHAT is only for the prompt, to indicate
8381 what is being sorted. The sorting key will be extracted from
8382 the car of the elements of the table.
8383 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8384 (unless sorting-type
8385 (message
8386 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8387 what)
8388 (setq sorting-type (read-char-exclusive)))
8389 (let ((dcst (downcase sorting-type))
8390 extractfun comparefun)
8391 ;; Define the appropriate functions
8392 (cond
8393 ((= dcst ?n)
8394 (setq extractfun 'string-to-number
8395 comparefun (if (= dcst sorting-type) '< '>)))
8396 ((= dcst ?a)
8397 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8398 (lambda(x) (downcase (org-sort-remove-invisible x))))
8399 comparefun (if (= dcst sorting-type)
8400 'string<
8401 (lambda (a b) (and (not (string< a b))
8402 (not (string= a b)))))))
8403 ((= dcst ?t)
8404 (setq extractfun
8405 (lambda (x)
8406 (if (or (string-match org-ts-regexp x)
8407 (string-match org-ts-regexp-both x))
8408 (org-float-time
8409 (org-time-string-to-time (match-string 0 x)))
8411 comparefun (if (= dcst sorting-type) '< '>)))
8412 (t (error "Invalid sorting type `%c'" sorting-type)))
8414 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8415 table)
8416 (lambda (a b) (funcall comparefun (car a) (car b))))))
8419 ;;; The orgstruct minor mode
8421 ;; Define a minor mode which can be used in other modes in order to
8422 ;; integrate the org-mode structure editing commands.
8424 ;; This is really a hack, because the org-mode structure commands use
8425 ;; keys which normally belong to the major mode. Here is how it
8426 ;; works: The minor mode defines all the keys necessary to operate the
8427 ;; structure commands, but wraps the commands into a function which
8428 ;; tests if the cursor is currently at a headline or a plain list
8429 ;; item. If that is the case, the structure command is used,
8430 ;; temporarily setting many Org-mode variables like regular
8431 ;; expressions for filling etc. However, when any of those keys is
8432 ;; used at a different location, function uses `key-binding' to look
8433 ;; up if the key has an associated command in another currently active
8434 ;; keymap (minor modes, major mode, global), and executes that
8435 ;; command. There might be problems if any of the keys is otherwise
8436 ;; used as a prefix key.
8438 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8439 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8440 ;; addresses this by checking explicitly for both bindings.
8442 (defvar orgstruct-mode-map (make-sparse-keymap)
8443 "Keymap for the minor `orgstruct-mode'.")
8445 (defvar org-local-vars nil
8446 "List of local variables, for use by `orgstruct-mode'.")
8448 ;;;###autoload
8449 (define-minor-mode orgstruct-mode
8450 "Toggle the minor mode `orgstruct-mode'.
8451 This mode is for using Org-mode structure commands in other
8452 modes. The following keys behave as if Org-mode were active, if
8453 the cursor is on a headline, or on a plain list item (both as
8454 defined by Org-mode).
8456 M-up Move entry/item up
8457 M-down Move entry/item down
8458 M-left Promote
8459 M-right Demote
8460 M-S-up Move entry/item up
8461 M-S-down Move entry/item down
8462 M-S-left Promote subtree
8463 M-S-right Demote subtree
8464 M-q Fill paragraph and items like in Org-mode
8465 C-c ^ Sort entries
8466 C-c - Cycle list bullet
8467 TAB Cycle item visibility
8468 M-RET Insert new heading/item
8469 S-M-RET Insert new TODO heading / Checkbox item
8470 C-c C-c Set tags / toggle checkbox"
8471 nil " OrgStruct" nil
8472 (org-load-modules-maybe)
8473 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8475 ;;;###autoload
8476 (defun turn-on-orgstruct ()
8477 "Unconditionally turn on `orgstruct-mode'."
8478 (orgstruct-mode 1))
8480 (defvar org-fb-vars nil)
8481 (make-variable-buffer-local 'org-fb-vars)
8482 (defun orgstruct++-mode (&optional arg)
8483 "Toggle `orgstruct-mode', the enhanced version of it.
8484 In addition to setting orgstruct-mode, this also exports all
8485 indentation and autofilling variables from org-mode into the
8486 buffer. It will also recognize item context in multiline items."
8487 (interactive "P")
8488 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8489 (if (< arg 1)
8490 (progn (orgstruct-mode -1)
8491 (mapc (lambda(v)
8492 (org-set-local (car v)
8493 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8494 org-fb-vars))
8495 (orgstruct-mode 1)
8496 (setq org-fb-vars nil)
8497 (let (var val)
8498 (mapc
8499 (lambda (x)
8500 (when (string-match
8501 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8502 (symbol-name (car x)))
8503 (setq var (car x) val (nth 1 x))
8504 (push (list var `(quote ,(eval var))) org-fb-vars)
8505 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8506 org-local-vars)
8507 (org-set-local 'orgstruct-is-++ t))))
8509 (defvar orgstruct-is-++ nil
8510 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8511 (make-variable-buffer-local 'orgstruct-is-++)
8513 ;;;###autoload
8514 (defun turn-on-orgstruct++ ()
8515 "Unconditionally turn on `orgstruct++-mode'."
8516 (orgstruct++-mode 1))
8518 (defun orgstruct-error ()
8519 "Error when there is no default binding for a structure key."
8520 (interactive)
8521 (error "This key has no function outside structure elements"))
8523 (defun orgstruct-setup ()
8524 "Setup orgstruct keymaps."
8525 (let ((nfunc 0)
8526 (bindings
8527 (list
8528 '([(meta up)] org-metaup)
8529 '([(meta down)] org-metadown)
8530 '([(meta left)] org-metaleft)
8531 '([(meta right)] org-metaright)
8532 '([(meta shift up)] org-shiftmetaup)
8533 '([(meta shift down)] org-shiftmetadown)
8534 '([(meta shift left)] org-shiftmetaleft)
8535 '([(meta shift right)] org-shiftmetaright)
8536 '([?\e (up)] org-metaup)
8537 '([?\e (down)] org-metadown)
8538 '([?\e (left)] org-metaleft)
8539 '([?\e (right)] org-metaright)
8540 '([?\e (shift up)] org-shiftmetaup)
8541 '([?\e (shift down)] org-shiftmetadown)
8542 '([?\e (shift left)] org-shiftmetaleft)
8543 '([?\e (shift right)] org-shiftmetaright)
8544 '([(shift up)] org-shiftup)
8545 '([(shift down)] org-shiftdown)
8546 '([(shift left)] org-shiftleft)
8547 '([(shift right)] org-shiftright)
8548 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8549 '("\M-q" fill-paragraph)
8550 '("\C-c^" org-sort)
8551 '("\C-c-" org-cycle-list-bullet)))
8552 elt key fun cmd)
8553 (while (setq elt (pop bindings))
8554 (setq nfunc (1+ nfunc))
8555 (setq key (org-key (car elt))
8556 fun (nth 1 elt)
8557 cmd (orgstruct-make-binding fun nfunc key))
8558 (org-defkey orgstruct-mode-map key cmd))
8560 ;; Prevent an error for users who forgot to make autoloads
8561 (require 'org-element)
8563 ;; Special treatment needed for TAB and RET
8564 (org-defkey orgstruct-mode-map [(tab)]
8565 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8566 (org-defkey orgstruct-mode-map "\C-i"
8567 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8569 (org-defkey orgstruct-mode-map "\M-\C-m"
8570 (orgstruct-make-binding 'org-insert-heading 105
8571 "\M-\C-m" [(meta return)]))
8572 (org-defkey orgstruct-mode-map [(meta return)]
8573 (orgstruct-make-binding 'org-insert-heading 106
8574 [(meta return)] "\M-\C-m"))
8576 (org-defkey orgstruct-mode-map [(shift meta return)]
8577 (orgstruct-make-binding 'org-insert-todo-heading 107
8578 [(meta return)] "\M-\C-m"))
8580 (org-defkey orgstruct-mode-map "\e\C-m"
8581 (orgstruct-make-binding 'org-insert-heading 108
8582 "\e\C-m" [?\e (return)]))
8583 (org-defkey orgstruct-mode-map [?\e (return)]
8584 (orgstruct-make-binding 'org-insert-heading 109
8585 [?\e (return)] "\e\C-m"))
8586 (org-defkey orgstruct-mode-map [?\e (shift return)]
8587 (orgstruct-make-binding 'org-insert-todo-heading 110
8588 [?\e (return)] "\e\C-m"))
8590 (unless org-local-vars
8591 (setq org-local-vars (org-get-local-variables)))
8595 (defun orgstruct-make-binding (fun n &rest keys)
8596 "Create a function for binding in the structure minor mode.
8597 FUN is the command to call inside a table. N is used to create a unique
8598 command name. KEYS are keys that should be checked in for a command
8599 to execute outside of tables."
8600 (eval
8601 (list 'defun
8602 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8603 '(arg)
8604 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8605 "Outside of structure, run the binding of `"
8606 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8607 "'.")
8608 '(interactive "p")
8609 (list 'if
8610 `(org-context-p 'headline 'item
8611 (and orgstruct-is-++
8612 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8613 'item-body))
8614 (list 'org-run-like-in-org-mode (list 'quote fun))
8615 (list 'let '(orgstruct-mode)
8616 (list 'call-interactively
8617 (append '(or)
8618 (mapcar (lambda (k)
8619 (list 'key-binding k))
8620 keys)
8621 '('orgstruct-error))))))))
8623 (defun org-contextualize-keys (alist contexts)
8624 "Return valid elements in ALIST depending on CONTEXTS.
8626 `org-agenda-custom-commands' or `org-capture-templates' are the
8627 values used for ALIST, and `org-agenda-custom-commands-contexts'
8628 or `org-capture-templates-contexts' are the associated contexts
8629 definitions."
8630 (let ((contexts
8631 ;; normalize contexts
8632 (mapcar
8633 (lambda(c) (cond ((listp (cadr c))
8634 (list (car c) (car c) (cadr c)))
8635 ((string= "" (cadr c))
8636 (list (car c) (car c) (caddr c)))
8637 (t c))) contexts))
8638 (a alist) c r s)
8639 ;; loop over all commands or templates
8640 (while (setq c (pop a))
8641 (let (vrules repl)
8642 (cond
8643 ((not (assoc (car c) contexts))
8644 (push c r))
8645 ((and (assoc (car c) contexts)
8646 (setq vrules (org-contextualize-validate-key
8647 (car c) contexts)))
8648 (mapc (lambda (vr)
8649 (when (not (equal (car vr) (cadr vr)))
8650 (setq repl vr))) vrules)
8651 (if (not repl) (push c r)
8652 (push (cadr repl) s)
8653 (push
8654 (cons (car c)
8655 (cdr (or (assoc (cadr repl) alist)
8656 (error "Undefined key `%s' as contextual replacement for `%s'"
8657 (cadr repl) (car c)))))
8658 r))))))
8659 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8660 (delq
8662 (delete-dups
8663 (mapcar (lambda (x)
8664 (let ((tpl (car x)))
8665 (when (not (delq
8667 (mapcar (lambda(y)
8668 (equal y tpl)) s))) x)))
8669 (reverse r))))))
8671 (defun org-contextualize-validate-key (key contexts)
8672 "Check CONTEXTS for agenda or capture KEY."
8673 (let (r rr res)
8674 (while (setq r (pop contexts))
8675 (mapc
8676 (lambda (rr)
8677 (when
8678 (and (equal key (car r))
8679 (if (functionp rr) (funcall rr)
8680 (or (and (eq (car rr) 'in-file)
8681 (buffer-file-name)
8682 (string-match (cdr rr) (buffer-file-name)))
8683 (and (eq (car rr) 'in-mode)
8684 (string-match (cdr rr) (symbol-name major-mode)))
8685 (when (and (eq (car rr) 'not-in-file)
8686 (buffer-file-name))
8687 (not (string-match (cdr rr) (buffer-file-name))))
8688 (when (eq (car rr) 'not-in-mode)
8689 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8690 (push r res)))
8691 (car (last r))))
8692 (delete-dups (delq nil res))))
8694 (defun org-context-p (&rest contexts)
8695 "Check if local context is any of CONTEXTS.
8696 Possible values in the list of contexts are `table', `headline', and `item'."
8697 (let ((pos (point)))
8698 (goto-char (point-at-bol))
8699 (prog1 (or (and (memq 'table contexts)
8700 (looking-at "[ \t]*|"))
8701 (and (memq 'headline contexts)
8702 (looking-at org-outline-regexp))
8703 (and (memq 'item contexts)
8704 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8705 (and (memq 'item-body contexts)
8706 (org-in-item-p)))
8707 (goto-char pos))))
8709 (defun org-get-local-variables ()
8710 "Return a list of all local variables in an Org mode buffer."
8711 (let (varlist)
8712 (with-current-buffer (get-buffer-create "*Org tmp*")
8713 (erase-buffer)
8714 (org-mode)
8715 (setq varlist (buffer-local-variables)))
8716 (kill-buffer "*Org tmp*")
8717 (delq nil
8718 (mapcar
8719 (lambda (x)
8720 (setq x
8721 (if (symbolp x)
8722 (list x)
8723 (list (car x) (list 'quote (cdr x)))))
8724 (if (string-match
8725 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8726 (symbol-name (car x)))
8727 x nil))
8728 varlist))))
8730 (defun org-clone-local-variables (from-buffer &optional regexp)
8731 "Clone local variables from FROM-BUFFER.
8732 Optional argument REGEXP selects variables to clone."
8733 (mapc
8734 (lambda (pair)
8735 (and (symbolp (car pair))
8736 (or (null regexp)
8737 (string-match regexp (symbol-name (car pair))))
8738 (set (make-local-variable (car pair))
8739 (cdr pair))))
8740 (buffer-local-variables from-buffer)))
8742 ;;;###autoload
8743 (defun org-run-like-in-org-mode (cmd)
8744 "Run a command, pretending that the current buffer is in Org-mode.
8745 This will temporarily bind local variables that are typically bound in
8746 Org-mode to the values they have in Org-mode, and then interactively
8747 call CMD."
8748 (org-load-modules-maybe)
8749 (unless org-local-vars
8750 (setq org-local-vars (org-get-local-variables)))
8751 (eval (list 'let org-local-vars
8752 (list 'call-interactively (list 'quote cmd)))))
8754 ;;;; Archiving
8756 (defun org-get-category (&optional pos force-refresh)
8757 "Get the category applying to position POS."
8758 (save-match-data
8759 (if force-refresh (org-refresh-category-properties))
8760 (let ((pos (or pos (point))))
8761 (or (get-text-property pos 'org-category)
8762 (progn (org-refresh-category-properties)
8763 (get-text-property pos 'org-category))))))
8765 (defun org-refresh-category-properties ()
8766 "Refresh category text properties in the buffer."
8767 (let ((case-fold-search t)
8768 (inhibit-read-only t)
8769 (def-cat (cond
8770 ((null org-category)
8771 (if buffer-file-name
8772 (file-name-sans-extension
8773 (file-name-nondirectory buffer-file-name))
8774 "???"))
8775 ((symbolp org-category) (symbol-name org-category))
8776 (t org-category)))
8777 beg end cat pos optionp)
8778 (org-unmodified
8779 (save-excursion
8780 (save-restriction
8781 (widen)
8782 (goto-char (point-min))
8783 (put-text-property (point) (point-max) 'org-category def-cat)
8784 (while (re-search-forward
8785 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8786 (setq pos (match-end 0)
8787 optionp (equal (char-after (match-beginning 0)) ?#)
8788 cat (org-trim (match-string 2)))
8789 (if optionp
8790 (setq beg (point-at-bol) end (point-max))
8791 (org-back-to-heading t)
8792 (setq beg (point) end (org-end-of-subtree t t)))
8793 (put-text-property beg end 'org-category cat)
8794 (put-text-property beg end 'org-category-position beg)
8795 (goto-char pos)))))))
8798 ;;;; Link Stuff
8800 ;;; Link abbreviations
8802 (defun org-link-expand-abbrev (link)
8803 "Apply replacements as defined in `org-link-abbrev-alist'."
8804 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8805 (let* ((key (match-string 1 link))
8806 (as (or (assoc key org-link-abbrev-alist-local)
8807 (assoc key org-link-abbrev-alist)))
8808 (tag (and (match-end 2) (match-string 3 link)))
8809 rpl)
8810 (if (not as)
8811 link
8812 (setq rpl (cdr as))
8813 (cond
8814 ((symbolp rpl) (funcall rpl tag))
8815 ((string-match "%(\\([^)]+\\))" rpl)
8816 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8817 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8818 ((string-match "%h" rpl)
8819 (replace-match (url-hexify-string (or tag "")) t t rpl))
8820 (t (concat rpl tag)))))
8821 link))
8823 ;;; Storing and inserting links
8825 (defvar org-insert-link-history nil
8826 "Minibuffer history for links inserted with `org-insert-link'.")
8828 (defvar org-stored-links nil
8829 "Contains the links stored with `org-store-link'.")
8831 (defvar org-store-link-plist nil
8832 "Plist with info about the most recently link created with `org-store-link'.")
8834 (defvar org-link-protocols nil
8835 "Link protocols added to Org-mode using `org-add-link-type'.")
8837 (defvar org-store-link-functions nil
8838 "List of functions that are called to create and store a link.
8839 Each function will be called in turn until one returns a non-nil
8840 value. Each function should check if it is responsible for creating
8841 this link (for example by looking at the major mode).
8842 If not, it must exit and return nil.
8843 If yes, it should return a non-nil value after a calling
8844 `org-store-link-props' with a list of properties and values.
8845 Special properties are:
8847 :type The link prefix, like \"http\". This must be given.
8848 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8849 This is obligatory as well.
8850 :description Optional default description for the second pair
8851 of brackets in an Org-mode link. The user can still change
8852 this when inserting this link into an Org-mode buffer.
8854 In addition to these, any additional properties can be specified
8855 and then used in remember templates.")
8857 (defun org-add-link-type (type &optional follow export)
8858 "Add TYPE to the list of `org-link-types'.
8859 Re-compute all regular expressions depending on `org-link-types'
8861 FOLLOW and EXPORT are two functions.
8863 FOLLOW should take the link path as the single argument and do whatever
8864 is necessary to follow the link, for example find a file or display
8865 a mail message.
8867 EXPORT should format the link path for export to one of the export formats.
8868 It should be a function accepting three arguments:
8870 path the path of the link, the text after the prefix (like \"http:\")
8871 desc the description of the link, if any, or a description added by
8872 org-export-normalize-links if there is none
8873 format the export format, a symbol like `html' or `latex' or `ascii'..
8875 The function may use the FORMAT information to return different values
8876 depending on the format. The return value will be put literally into
8877 the exported file. If the return value is nil, this means Org should
8878 do what it normally does with links which do not have EXPORT defined.
8880 Org-mode has a built-in default for exporting links. If you are happy with
8881 this default, there is no need to define an export function for the link
8882 type. For a simple example of an export function, see `org-bbdb.el'."
8883 (add-to-list 'org-link-types type t)
8884 (org-make-link-regexps)
8885 (if (assoc type org-link-protocols)
8886 (setcdr (assoc type org-link-protocols) (list follow export))
8887 (push (list type follow export) org-link-protocols)))
8889 (defvar org-agenda-buffer-name)
8891 ;;;###autoload
8892 (defun org-store-link (arg)
8893 "\\<org-mode-map>Store an org-link to the current location.
8894 This link is added to `org-stored-links' and can later be inserted
8895 into an org-buffer with \\[org-insert-link].
8897 For some link types, a prefix arg is interpreted:
8898 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8899 For file links, arg negates `org-context-in-file-links'."
8900 (interactive "P")
8901 (org-load-modules-maybe)
8902 (setq org-store-link-plist nil) ; reset
8903 (org-with-limited-levels
8904 (let (link cpltxt desc description search txt custom-id agenda-link)
8905 (cond
8907 ((run-hook-with-args-until-success 'org-store-link-functions)
8908 (setq link (plist-get org-store-link-plist :link)
8909 desc (or (plist-get org-store-link-plist :description) link)))
8911 ((org-src-edit-buffer-p)
8912 (let (label gc)
8913 (while (or (not label)
8914 (save-excursion
8915 (save-restriction
8916 (widen)
8917 (goto-char (point-min))
8918 (re-search-forward
8919 (regexp-quote (format org-coderef-label-format label))
8920 nil t))))
8921 (when label (message "Label exists already") (sit-for 2))
8922 (setq label (read-string "Code line label: " label)))
8923 (end-of-line 1)
8924 (setq link (format org-coderef-label-format label))
8925 (setq gc (- 79 (length link)))
8926 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8927 (insert link)
8928 (setq link (concat "(" label ")") desc nil)))
8930 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8931 ;; We are in the agenda, link to referenced location
8932 (let ((m (or (get-text-property (point) 'org-hd-marker)
8933 (get-text-property (point) 'org-marker))))
8934 (when m
8935 (org-with-point-at m
8936 (setq agenda-link
8937 (if (org-called-interactively-p 'any)
8938 (call-interactively 'org-store-link)
8939 (org-store-link nil)))))))
8941 ((eq major-mode 'calendar-mode)
8942 (let ((cd (calendar-cursor-to-date)))
8943 (setq link
8944 (format-time-string
8945 (car org-time-stamp-formats)
8946 (apply 'encode-time
8947 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8948 nil nil nil))))
8949 (org-store-link-props :type "calendar" :date cd)))
8951 ((eq major-mode 'help-mode)
8952 (setq link (concat "help:" (save-excursion
8953 (goto-char (point-min))
8954 (looking-at "^[^ ]+")
8955 (match-string 0))))
8956 (org-store-link-props :type "help"))
8958 ((eq major-mode 'w3-mode)
8959 (setq cpltxt (if (and (buffer-name)
8960 (not (string-match "Untitled" (buffer-name))))
8961 (buffer-name)
8962 (url-view-url t))
8963 link (url-view-url t))
8964 (org-store-link-props :type "w3" :url (url-view-url t)))
8966 ((eq major-mode 'w3m-mode)
8967 (setq cpltxt (or w3m-current-title w3m-current-url)
8968 link w3m-current-url)
8969 (org-store-link-props :type "w3m" :url (url-view-url t)))
8971 ((setq search (run-hook-with-args-until-success
8972 'org-create-file-search-functions))
8973 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8974 "::" search))
8975 (setq cpltxt (or description link)))
8977 ((eq major-mode 'image-mode)
8978 (setq cpltxt (concat "file:"
8979 (abbreviate-file-name buffer-file-name))
8980 link cpltxt)
8981 (org-store-link-props :type "image" :file buffer-file-name))
8983 ((eq major-mode 'dired-mode)
8984 ;; link to the file in the current line
8985 (let ((file (dired-get-filename nil t)))
8986 (setq file (if file
8987 (abbreviate-file-name
8988 (expand-file-name (dired-get-filename nil t)))
8989 ;; otherwise, no file so use current directory.
8990 default-directory))
8991 (setq cpltxt (concat "file:" file)
8992 link cpltxt)))
8994 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8995 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8996 (cond
8997 ((org-in-regexp "<<\\(.*?\\)>>")
8998 (setq cpltxt
8999 (concat "file:"
9000 (abbreviate-file-name
9001 (buffer-file-name (buffer-base-buffer)))
9002 "::" (match-string 1))
9003 link cpltxt))
9004 ((and (featurep 'org-id)
9005 (or (eq org-link-to-org-use-id t)
9006 (and (org-called-interactively-p 'any)
9007 (or (eq org-link-to-org-use-id 'create-if-interactive)
9008 (and (eq org-link-to-org-use-id
9009 'create-if-interactive-and-no-custom-id)
9010 (not custom-id))))
9011 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9012 ;; We can make a link using the ID.
9013 (setq link (condition-case nil
9014 (prog1 (org-id-store-link)
9015 (setq desc (plist-get org-store-link-plist :description)))
9016 (error
9017 ;; probably before first headline, link to file only
9018 (concat "file:"
9019 (abbreviate-file-name
9020 (buffer-file-name (buffer-base-buffer))))))))
9022 ;; Just link to current headline
9023 (setq cpltxt (concat "file:"
9024 (abbreviate-file-name
9025 (buffer-file-name (buffer-base-buffer)))))
9026 ;; Add a context search string
9027 (when (org-xor org-context-in-file-links arg)
9028 (setq txt (cond
9029 ((org-at-heading-p) nil)
9030 ((org-region-active-p)
9031 (buffer-substring (region-beginning) (region-end)))))
9032 (when (or (null txt) (string-match "\\S-" txt))
9033 (setq cpltxt
9034 (concat cpltxt "::"
9035 (condition-case nil
9036 (org-make-org-heading-search-string txt)
9037 (error "")))
9038 desc (or (nth 4 (ignore-errors
9039 (org-heading-components))) "NONE"))))
9040 (if (string-match "::\\'" cpltxt)
9041 (setq cpltxt (substring cpltxt 0 -2)))
9042 (setq link cpltxt))))
9044 ((buffer-file-name (buffer-base-buffer))
9045 ;; Just link to this file here.
9046 (setq cpltxt (concat "file:"
9047 (abbreviate-file-name
9048 (buffer-file-name (buffer-base-buffer)))))
9049 ;; Add a context string
9050 (when (org-xor org-context-in-file-links arg)
9051 (setq txt (if (org-region-active-p)
9052 (buffer-substring (region-beginning) (region-end))
9053 (buffer-substring (point-at-bol) (point-at-eol))))
9054 ;; Only use search option if there is some text.
9055 (when (string-match "\\S-" txt)
9056 (setq cpltxt
9057 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9058 desc "NONE")))
9059 (setq link cpltxt))
9061 ((org-called-interactively-p 'interactive)
9062 (error "Cannot link to a buffer which is not visiting a file"))
9064 (t (setq link nil)))
9066 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9067 (setq link (or link cpltxt)
9068 desc (or desc cpltxt))
9069 (if (equal desc "NONE") (setq desc nil))
9071 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9072 (progn
9073 (setq org-stored-links
9074 (cons (list link desc) org-stored-links))
9075 (message "Stored: %s" (or desc link))
9076 (when custom-id
9077 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9078 "::#" custom-id))
9079 (setq org-stored-links
9080 (cons (list link desc) org-stored-links))))
9081 (or agenda-link (and link (org-make-link-string link desc)))))))
9083 (defun org-store-link-props (&rest plist)
9084 "Store link properties, extract names and addresses."
9085 (let (x adr)
9086 (when (setq x (plist-get plist :from))
9087 (setq adr (mail-extract-address-components x))
9088 (setq plist (plist-put plist :fromname (car adr)))
9089 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9090 (when (setq x (plist-get plist :to))
9091 (setq adr (mail-extract-address-components x))
9092 (setq plist (plist-put plist :toname (car adr)))
9093 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9094 (let ((from (plist-get plist :from))
9095 (to (plist-get plist :to)))
9096 (when (and from to org-from-is-user-regexp)
9097 (setq plist
9098 (plist-put plist :fromto
9099 (if (string-match org-from-is-user-regexp from)
9100 (concat "to %t")
9101 (concat "from %f"))))))
9102 (setq org-store-link-plist plist))
9104 (defun org-add-link-props (&rest plist)
9105 "Add these properties to the link property list."
9106 (let (key value)
9107 (while plist
9108 (setq key (pop plist) value (pop plist))
9109 (setq org-store-link-plist
9110 (plist-put org-store-link-plist key value)))))
9112 (defun org-email-link-description (&optional fmt)
9113 "Return the description part of an email link.
9114 This takes information from `org-store-link-plist' and formats it
9115 according to FMT (default from `org-email-link-description-format')."
9116 (setq fmt (or fmt org-email-link-description-format))
9117 (let* ((p org-store-link-plist)
9118 (to (plist-get p :toaddress))
9119 (from (plist-get p :fromaddress))
9120 (table
9121 (list
9122 (cons "%c" (plist-get p :fromto))
9123 (cons "%F" (plist-get p :from))
9124 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9125 (cons "%T" (plist-get p :to))
9126 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9127 (cons "%s" (plist-get p :subject))
9128 (cons "%d" (plist-get p :date))
9129 (cons "%m" (plist-get p :message-id)))))
9130 (when (string-match "%c" fmt)
9131 ;; Check if the user wrote this message
9132 (if (and org-from-is-user-regexp from to
9133 (save-match-data (string-match org-from-is-user-regexp from)))
9134 (setq fmt (replace-match "to %t" t t fmt))
9135 (setq fmt (replace-match "from %f" t t fmt))))
9136 (org-replace-escapes fmt table)))
9138 (defun org-make-org-heading-search-string (&optional string heading)
9139 "Make search string for STRING or current headline."
9140 (interactive)
9141 (let ((s (or string (org-get-heading)))
9142 (lines org-context-in-file-links))
9143 (unless (and string (not heading))
9144 ;; We are using a headline, clean up garbage in there.
9145 (if (string-match org-todo-regexp s)
9146 (setq s (replace-match "" t t s)))
9147 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9148 (setq s (replace-match "" t t s)))
9149 (setq s (org-trim s))
9150 (if (string-match (concat "^\\(" org-quote-string "\\|"
9151 org-comment-string "\\)") s)
9152 (setq s (replace-match "" t t s)))
9153 (while (string-match org-ts-regexp s)
9154 (setq s (replace-match "" t t s))))
9155 (or string (setq s (concat "*" s))) ; Add * for headlines
9156 (when (and string (integerp lines) (> lines 0))
9157 (let ((slines (org-split-string s "\n")))
9158 (when (< lines (length slines))
9159 (setq s (mapconcat
9160 'identity
9161 (reverse (nthcdr (- (length slines) lines)
9162 (reverse slines))) "\n")))))
9163 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9165 (defun org-make-link-string (link &optional description)
9166 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9167 (unless (string-match "\\S-" link)
9168 (error "Empty link"))
9169 (when (and description
9170 (stringp description)
9171 (not (string-match "\\S-" description)))
9172 (setq description nil))
9173 (when (stringp description)
9174 ;; Remove brackets from the description, they are fatal.
9175 (while (string-match "\\[" description)
9176 (setq description (replace-match "{" t t description)))
9177 (while (string-match "\\]" description)
9178 (setq description (replace-match "}" t t description))))
9179 (when (equal link description)
9180 ;; No description needed, it is identical
9181 (setq description nil))
9182 (when (and (not description)
9183 (not (string-match (org-image-file-name-regexp) link))
9184 (not (equal link (org-link-escape link))))
9185 (setq description (org-extract-attributes link)))
9186 (setq link
9187 (cond ((string-match (org-image-file-name-regexp) link) link)
9188 ((string-match org-link-types-re link)
9189 (concat (match-string 1 link)
9190 (org-link-escape (substring link (match-end 1)))))
9191 (t (org-link-escape link))))
9192 (concat "[[" link "]"
9193 (if description (concat "[" description "]") "")
9194 "]"))
9196 (defconst org-link-escape-chars
9197 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9198 "List of characters that should be escaped in link.
9199 This is the list that is used for internal purposes.")
9201 (defconst org-link-escape-chars-browser
9202 '(?\ )
9203 "List of escapes for characters that are problematic in links.
9204 This is the list that is used before handing over to the browser.")
9206 (defun org-link-escape (text &optional table merge)
9207 "Return percent escaped representation of TEXT.
9208 TEXT is a string with the text to escape.
9209 Optional argument TABLE is a list with characters that should be
9210 escaped. When nil, `org-link-escape-chars' is used.
9211 If optional argument MERGE is set, merge TABLE into
9212 `org-link-escape-chars'."
9213 (cond
9214 ((and table merge)
9215 (mapc (lambda (defchr)
9216 (unless (member defchr table)
9217 (setq table (cons defchr table)))) org-link-escape-chars))
9218 ((null table)
9219 (setq table org-link-escape-chars)))
9220 (mapconcat
9221 (lambda (char)
9222 (if (or (member char table)
9223 (and (or (< char 32) (= char 37) (> char 126))
9224 org-url-hexify-p))
9225 (mapconcat (lambda (sequence-element)
9226 (format "%%%.2X" sequence-element))
9227 (or (encode-coding-char char 'utf-8)
9228 (error "Unable to percent escape character: %s"
9229 (char-to-string char))) "")
9230 (char-to-string char))) text ""))
9232 (defun org-link-unescape (str)
9233 "Unhex hexified Unicode strings as returned from the JavaScript function
9234 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9235 (unless (and (null str) (string= "" str))
9236 (let ((pos 0) (case-fold-search t) unhexed)
9237 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9238 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9239 (setq str (replace-match unhexed t t str))
9240 (setq pos (+ pos (length unhexed))))))
9241 str)
9243 (defun org-link-unescape-compound (hex)
9244 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9245 Note: this function also decodes single byte encodings like
9246 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9247 (save-match-data
9248 (let* ((bytes (cdr (split-string hex "%")))
9249 (ret "")
9250 (eat 0)
9251 (sum 0))
9252 (while bytes
9253 (let* ((val (string-to-number (pop bytes) 16))
9254 (shift-xor
9255 (if (= 0 eat)
9256 (cond
9257 ((>= val 252) (cons 6 252))
9258 ((>= val 248) (cons 5 248))
9259 ((>= val 240) (cons 4 240))
9260 ((>= val 224) (cons 3 224))
9261 ((>= val 192) (cons 2 192))
9262 (t (cons 0 0)))
9263 (cons 6 128))))
9264 (if (>= val 192) (setq eat (car shift-xor)))
9265 (setq val (logxor val (cdr shift-xor)))
9266 (setq sum (+ (lsh sum (car shift-xor)) val))
9267 (if (> eat 0) (setq eat (- eat 1)))
9268 (cond
9269 ((= 0 eat) ;multi byte
9270 (setq ret (concat ret (org-char-to-string sum)))
9271 (setq sum 0))
9272 ((not bytes) ; single byte(s)
9273 (setq ret (org-link-unescape-single-byte-sequence hex))))
9274 )) ;; end (while bytes
9275 ret )))
9277 (defun org-link-unescape-single-byte-sequence (hex)
9278 "Unhexify hex-encoded single byte character sequences."
9279 (mapconcat (lambda (byte)
9280 (char-to-string (string-to-number byte 16)))
9281 (cdr (split-string hex "%")) ""))
9283 (defun org-xor (a b)
9284 "Exclusive or."
9285 (if a (not b) b))
9287 (defun org-fixup-message-id-for-http (s)
9288 "Replace special characters in a message id, so it can be used in an http query."
9289 (when (string-match "%" s)
9290 (setq s (mapconcat (lambda (c)
9291 (if (eq c ?%)
9292 "%25"
9293 (char-to-string c)))
9294 s "")))
9295 (while (string-match "<" s)
9296 (setq s (replace-match "%3C" t t s)))
9297 (while (string-match ">" s)
9298 (setq s (replace-match "%3E" t t s)))
9299 (while (string-match "@" s)
9300 (setq s (replace-match "%40" t t s)))
9303 (defun org-link-prettify (link)
9304 "Return a human-readable representation of LINK.
9305 The car of LINK must be a raw link the cdr of LINK must be either
9306 a link description or nil."
9307 (let ((desc (or (cadr link) "<no description>")))
9308 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9309 "<" (car link) ">")))
9311 ;;;###autoload
9312 (defun org-insert-link-global ()
9313 "Insert a link like Org-mode does.
9314 This command can be called in any mode to insert a link in Org-mode syntax."
9315 (interactive)
9316 (org-load-modules-maybe)
9317 (org-run-like-in-org-mode 'org-insert-link))
9319 (defun org-insert-all-links (&optional keep)
9320 "Insert all links in `org-stored-links'."
9321 (interactive "P")
9322 (let ((links (copy-sequence org-stored-links)) l)
9323 (while (setq l (if keep (pop links) (pop org-stored-links)))
9324 (insert "- ")
9325 (org-insert-link nil (car l) (cadr l))
9326 (insert "\n"))))
9328 (defun org-link-fontify-links-to-this-file ()
9329 "Fontify links to the current file in `org-stored-links'."
9330 (let ((f (buffer-file-name)) a b)
9331 (setq a (mapcar (lambda(l)
9332 (let ((ll (car l)))
9333 (when (and (string-match "^file:\\(.+\\)::" ll)
9334 (equal f (expand-file-name (match-string 1 ll))))
9335 ll)))
9336 org-stored-links))
9337 (when (featurep 'org-id)
9338 (setq b (mapcar (lambda(l)
9339 (let ((ll (car l)))
9340 (when (and (string-match "^id:\\(.+\\)$" ll)
9341 (equal f (expand-file-name
9342 (or (org-id-find-id-file
9343 (match-string 1 ll)) ""))))
9344 ll)))
9345 org-stored-links)))
9346 (mapcar (lambda(l)
9347 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9348 (delq nil (append a b)))))
9350 (defvar org-link-links-in-this-file nil)
9351 (defun org-insert-link (&optional complete-file link-location default-description)
9352 "Insert a link. At the prompt, enter the link.
9354 Completion can be used to insert any of the link protocol prefixes like
9355 http or ftp in use.
9357 The history can be used to select a link previously stored with
9358 `org-store-link'. When the empty string is entered (i.e. if you just
9359 press RET at the prompt), the link defaults to the most recently
9360 stored link. As SPC triggers completion in the minibuffer, you need to
9361 use M-SPC or C-q SPC to force the insertion of a space character.
9363 You will also be prompted for a description, and if one is given, it will
9364 be displayed in the buffer instead of the link.
9366 If there is already a link at point, this command will allow you to edit link
9367 and description parts.
9369 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9370 be selected using completion. The path to the file will be relative to the
9371 current directory if the file is in the current directory or a subdirectory.
9372 Otherwise, the link will be the absolute path as completed in the minibuffer
9373 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9374 option `org-link-file-path-type'.
9376 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9377 the current directory or below.
9379 With three \\[universal-argument] prefixes, negate the meaning of
9380 `org-keep-stored-link-after-insertion'.
9382 If `org-make-link-description-function' is non-nil, this function will be
9383 called with the link target, and the result will be the default
9384 link description.
9386 If the LINK-LOCATION parameter is non-nil, this value will be
9387 used as the link location instead of reading one interactively.
9389 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9390 be used as the default description."
9391 (interactive "P")
9392 (let* ((wcf (current-window-configuration))
9393 (region (if (org-region-active-p)
9394 (buffer-substring (region-beginning) (region-end))))
9395 (remove (and region (list (region-beginning) (region-end))))
9396 (desc region)
9397 tmphist ; byte-compile incorrectly complains about this
9398 (link link-location)
9399 (abbrevs org-link-abbrev-alist-local)
9400 entry file all-prefixes auto-desc)
9401 (cond
9402 (link-location) ; specified by arg, just use it.
9403 ((org-in-regexp org-bracket-link-regexp 1)
9404 ;; We do have a link at point, and we are going to edit it.
9405 (setq remove (list (match-beginning 0) (match-end 0)))
9406 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9407 (setq link (read-string "Link: "
9408 (org-link-unescape
9409 (org-match-string-no-properties 1)))))
9410 ((or (org-in-regexp org-angle-link-re)
9411 (org-in-regexp org-plain-link-re))
9412 ;; Convert to bracket link
9413 (setq remove (list (match-beginning 0) (match-end 0))
9414 link (read-string "Link: "
9415 (org-remove-angle-brackets (match-string 0)))))
9416 ((member complete-file '((4) (16)))
9417 ;; Completing read for file names.
9418 (setq link (org-file-complete-link complete-file)))
9420 ;; Read link, with completion for stored links.
9421 (org-link-fontify-links-to-this-file)
9422 (org-switch-to-buffer-other-window "*Org Links*")
9423 (with-current-buffer "*Org Links*"
9424 (erase-buffer)
9425 (insert "Insert a link.
9426 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9427 (when org-stored-links
9428 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9429 (insert (mapconcat 'org-link-prettify
9430 (reverse org-stored-links) "\n")))
9431 (goto-char (point-min)))
9432 (let ((cw (selected-window)))
9433 (select-window (get-buffer-window "*Org Links*" 'visible))
9434 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9435 (unless (pos-visible-in-window-p (point-max))
9436 (org-fit-window-to-buffer))
9437 (and (window-live-p cw) (select-window cw)))
9438 ;; Fake a link history, containing the stored links.
9439 (setq tmphist (append (mapcar 'car org-stored-links)
9440 org-insert-link-history))
9441 (setq all-prefixes (append (mapcar 'car abbrevs)
9442 (mapcar 'car org-link-abbrev-alist)
9443 org-link-types))
9444 (unwind-protect
9445 (progn
9446 (setq link
9447 (let ((org-completion-use-ido nil)
9448 (org-completion-use-iswitchb nil))
9449 (org-completing-read
9450 "Link: "
9451 (append
9452 (mapcar (lambda (x) (list (concat x ":")))
9453 all-prefixes)
9454 (mapcar 'car org-stored-links)
9455 (mapcar 'cadr org-stored-links))
9456 nil nil nil
9457 'tmphist
9458 (caar org-stored-links))))
9459 (if (not (string-match "\\S-" link))
9460 (error "No link selected"))
9461 (mapc (lambda(l)
9462 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9463 org-stored-links)
9464 (if (or (member link all-prefixes)
9465 (and (equal ":" (substring link -1))
9466 (member (substring link 0 -1) all-prefixes)
9467 (setq link (substring link 0 -1))))
9468 (setq link (org-link-try-special-completion link))))
9469 (set-window-configuration wcf)
9470 (kill-buffer "*Org Links*"))
9471 (setq entry (assoc link org-stored-links))
9472 (or entry (push link org-insert-link-history))
9473 (setq desc (or desc (nth 1 entry)))))
9475 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9476 (not org-keep-stored-link-after-insertion))
9477 (setq org-stored-links (delq (assoc link org-stored-links)
9478 org-stored-links)))
9480 (if (string-match org-plain-link-re link)
9481 ;; URL-like link, normalize the use of angular brackets.
9482 (setq link (org-remove-angle-brackets link)))
9484 ;; Check if we are linking to the current file with a search option
9485 ;; If yes, simplify the link by using only the search option.
9486 (when (and buffer-file-name
9487 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9488 (let* ((path (match-string 1 link))
9489 (case-fold-search nil)
9490 (search (match-string 2 link)))
9491 (save-match-data
9492 (if (equal (file-truename buffer-file-name) (file-truename path))
9493 ;; We are linking to this same file, with a search option
9494 (setq link search)))))
9496 ;; Check if we can/should use a relative path. If yes, simplify the link
9497 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9498 (let* ((type (match-string 1 link))
9499 (path (match-string 2 link))
9500 (origpath path)
9501 (case-fold-search nil))
9502 (cond
9503 ((or (eq org-link-file-path-type 'absolute)
9504 (equal complete-file '(16)))
9505 (setq path (abbreviate-file-name (expand-file-name path))))
9506 ((eq org-link-file-path-type 'noabbrev)
9507 (setq path (expand-file-name path)))
9508 ((eq org-link-file-path-type 'relative)
9509 (setq path (file-relative-name path)))
9511 (save-match-data
9512 (if (string-match (concat "^" (regexp-quote
9513 (expand-file-name
9514 (file-name-as-directory
9515 default-directory))))
9516 (expand-file-name path))
9517 ;; We are linking a file with relative path name.
9518 (setq path (substring (expand-file-name path)
9519 (match-end 0)))
9520 (setq path (abbreviate-file-name (expand-file-name path)))))))
9521 (setq link (concat type path))
9522 (if (equal desc origpath)
9523 (setq desc path))))
9525 (if org-make-link-description-function
9526 (setq desc (funcall org-make-link-description-function link desc))
9527 (if default-description (setq desc default-description)
9528 (setq desc (or (and auto-desc desc)
9529 (read-string "Description: " desc)))))
9531 (unless (string-match "\\S-" desc) (setq desc nil))
9532 (if remove (apply 'delete-region remove))
9533 (insert (org-make-link-string link desc))))
9535 (defun org-link-try-special-completion (type)
9536 "If there is completion support for link type TYPE, offer it."
9537 (let ((fun (intern (concat "org-" type "-complete-link"))))
9538 (if (functionp fun)
9539 (funcall fun)
9540 (read-string "Link (no completion support): " (concat type ":")))))
9542 (defun org-file-complete-link (&optional arg)
9543 "Create a file link using completion."
9544 (let (file link)
9545 (setq file (read-file-name "File: "))
9546 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9547 (pwd1 (file-name-as-directory (abbreviate-file-name
9548 (expand-file-name ".")))))
9549 (cond
9550 ((equal arg '(16))
9551 (setq link (concat
9552 "file:"
9553 (abbreviate-file-name (expand-file-name file)))))
9554 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9555 (setq link (concat "file:" (match-string 1 file))))
9556 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9557 (expand-file-name file))
9558 (setq link (concat
9559 "file:" (match-string 1 (expand-file-name file)))))
9560 (t (setq link (concat "file:" file)))))
9561 link))
9563 (defun org-completing-read (&rest args)
9564 "Completing-read with SPACE being a normal character."
9565 (let ((enable-recursive-minibuffers t)
9566 (minibuffer-local-completion-map
9567 (copy-keymap minibuffer-local-completion-map)))
9568 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9569 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9570 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9571 (apply 'org-icompleting-read args)))
9573 (defun org-completing-read-no-i (&rest args)
9574 (let (org-completion-use-ido org-completion-use-iswitchb)
9575 (apply 'org-completing-read args)))
9577 (defun org-iswitchb-completing-read (prompt choices &rest args)
9578 "Use iswitch as a completing-read replacement to choose from choices.
9579 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9580 from."
9581 (let* ((iswitchb-use-virtual-buffers nil)
9582 (iswitchb-make-buflist-hook
9583 (lambda ()
9584 (setq iswitchb-temp-buflist choices))))
9585 (iswitchb-read-buffer prompt)))
9587 (defun org-icompleting-read (&rest args)
9588 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9589 (org-without-partial-completion
9590 (if (and org-completion-use-ido
9591 (fboundp 'ido-completing-read)
9592 (boundp 'ido-mode) ido-mode
9593 (listp (second args)))
9594 (let ((ido-enter-matching-directory nil))
9595 (apply 'ido-completing-read (concat (car args))
9596 (if (consp (car (nth 1 args)))
9597 (mapcar 'car (nth 1 args))
9598 (nth 1 args))
9599 (cddr args)))
9600 (if (and org-completion-use-iswitchb
9601 (boundp 'iswitchb-mode) iswitchb-mode
9602 (listp (second args)))
9603 (apply 'org-iswitchb-completing-read (concat (car args))
9604 (if (consp (car (nth 1 args)))
9605 (mapcar 'car (nth 1 args))
9606 (nth 1 args))
9607 (cddr args))
9608 (apply 'completing-read args)))))
9610 (defun org-extract-attributes (s)
9611 "Extract the attributes cookie from a string and set as text property."
9612 (let (a attr (start 0) key value)
9613 (save-match-data
9614 (when (string-match "{{\\([^}]+\\)}}$" s)
9615 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9616 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9617 (setq key (match-string 1 a) value (match-string 2 a)
9618 start (match-end 0)
9619 attr (plist-put attr (intern key) value))))
9620 (org-add-props s nil 'org-attr attr))
9623 (defun org-extract-attributes-from-string (tag)
9624 (let (key value attr)
9625 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9626 (setq key (match-string 1 tag) value (match-string 2 tag)
9627 tag (replace-match "" t t tag)
9628 attr (plist-put attr (intern key) value)))
9629 (cons tag attr)))
9631 (defun org-attributes-to-string (plist)
9632 "Format a property list into an HTML attribute list."
9633 (let ((s "") key value)
9634 (while plist
9635 (setq key (pop plist) value (pop plist))
9636 (and value
9637 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9640 ;;; Opening/following a link
9642 (defvar org-link-search-failed nil)
9644 (defvar org-open-link-functions nil
9645 "Hook for functions finding a plain text link.
9646 These functions must take a single argument, the link content.
9647 They will be called for links that look like [[link text][description]]
9648 when LINK TEXT does not have a protocol like \"http:\" and does not look
9649 like a filename (e.g. \"./blue.png\").
9651 These functions will be called *before* Org attempts to resolve the
9652 link by doing text searches in the current buffer - so if you want a
9653 link \"[[target]]\" to still find \"<<target>>\", your function should
9654 handle this as a special case.
9656 When the function does handle the link, it must return a non-nil value.
9657 If it decides that it is not responsible for this link, it must return
9658 nil to indicate that that Org-mode can continue with other options
9659 like exact and fuzzy text search.")
9661 (defun org-next-link ()
9662 "Move forward to the next link.
9663 If the link is in hidden text, expose it."
9664 (interactive)
9665 (when (and org-link-search-failed (eq this-command last-command))
9666 (goto-char (point-min))
9667 (message "Link search wrapped back to beginning of buffer"))
9668 (setq org-link-search-failed nil)
9669 (let* ((pos (point))
9670 (ct (org-context))
9671 (a (assoc :link ct)))
9672 (if a (goto-char (nth 2 a)))
9673 (if (re-search-forward org-any-link-re nil t)
9674 (progn
9675 (goto-char (match-beginning 0))
9676 (if (outline-invisible-p) (org-show-context)))
9677 (goto-char pos)
9678 (setq org-link-search-failed t)
9679 (error "No further link found"))))
9681 (defun org-previous-link ()
9682 "Move backward to the previous link.
9683 If the link is in hidden text, expose it."
9684 (interactive)
9685 (when (and org-link-search-failed (eq this-command last-command))
9686 (goto-char (point-max))
9687 (message "Link search wrapped back to end of buffer"))
9688 (setq org-link-search-failed nil)
9689 (let* ((pos (point))
9690 (ct (org-context))
9691 (a (assoc :link ct)))
9692 (if a (goto-char (nth 1 a)))
9693 (if (re-search-backward org-any-link-re nil t)
9694 (progn
9695 (goto-char (match-beginning 0))
9696 (if (outline-invisible-p) (org-show-context)))
9697 (goto-char pos)
9698 (setq org-link-search-failed t)
9699 (error "No further link found"))))
9701 (defun org-translate-link (s)
9702 "Translate a link string if a translation function has been defined."
9703 (if (and org-link-translation-function
9704 (fboundp org-link-translation-function)
9705 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9706 (progn
9707 (setq s (funcall org-link-translation-function
9708 (match-string 1 s) (match-string 2 s)))
9709 (concat (car s) ":" (cdr s)))
9712 (defun org-translate-link-from-planner (type path)
9713 "Translate a link from Emacs Planner syntax so that Org can follow it.
9714 This is still an experimental function, your mileage may vary."
9715 (cond
9716 ((member type '("http" "https" "news" "ftp"))
9717 ;; standard Internet links are the same.
9718 nil)
9719 ((and (equal type "irc") (string-match "^//" path))
9720 ;; Planner has two / at the beginning of an irc link, we have 1.
9721 ;; We should have zero, actually....
9722 (setq path (substring path 1)))
9723 ((and (equal type "lisp") (string-match "^/" path))
9724 ;; Planner has a slash, we do not.
9725 (setq type "elisp" path (substring path 1)))
9726 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9727 ;; A typical message link. Planner has the id after the final slash,
9728 ;; we separate it with a hash mark
9729 (setq path (concat (match-string 1 path) "#"
9730 (org-remove-angle-brackets (match-string 2 path)))))
9732 (cons type path))
9734 (defun org-find-file-at-mouse (ev)
9735 "Open file link or URL at mouse."
9736 (interactive "e")
9737 (mouse-set-point ev)
9738 (org-open-at-point 'in-emacs))
9740 (defun org-open-at-mouse (ev)
9741 "Open file link or URL at mouse.
9742 See the docstring of `org-open-file' for details."
9743 (interactive "e")
9744 (mouse-set-point ev)
9745 (if (eq major-mode 'org-agenda-mode)
9746 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9747 (org-open-at-point))
9749 (defvar org-window-config-before-follow-link nil
9750 "The window configuration before following a link.
9751 This is saved in case the need arises to restore it.")
9753 (defvar org-open-link-marker (make-marker)
9754 "Marker pointing to the location where `org-open-at-point; was called.")
9756 ;;;###autoload
9757 (defun org-open-at-point-global ()
9758 "Follow a link like Org-mode does.
9759 This command can be called in any mode to follow a link that has
9760 Org-mode syntax."
9761 (interactive)
9762 (org-run-like-in-org-mode 'org-open-at-point))
9764 ;;;###autoload
9765 (defun org-open-link-from-string (s &optional arg reference-buffer)
9766 "Open a link in the string S, as if it was in Org-mode."
9767 (interactive "sLink: \nP")
9768 (let ((reference-buffer (or reference-buffer (current-buffer))))
9769 (with-temp-buffer
9770 (let ((org-inhibit-startup (not reference-buffer)))
9771 (org-mode)
9772 (insert s)
9773 (goto-char (point-min))
9774 (when reference-buffer
9775 (setq org-link-abbrev-alist-local
9776 (with-current-buffer reference-buffer
9777 org-link-abbrev-alist-local)))
9778 (org-open-at-point arg reference-buffer)))))
9780 (defvar org-open-at-point-functions nil
9781 "Hook that is run when following a link at point.
9783 Functions in this hook must return t if they identify and follow
9784 a link at point. If they don't find anything interesting at point,
9785 they must return nil.")
9787 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9788 (defun org-open-at-point (&optional arg reference-buffer)
9789 "Open link at or after point.
9790 If there is no link at point, this function will search forward up to
9791 the end of the current line.
9792 Normally, files will be opened by an appropriate application. If the
9793 optional prefix argument ARG is non-nil, Emacs will visit the file.
9794 With a double prefix argument, try to open outside of Emacs, in the
9795 application the system uses for this file type."
9796 (interactive "P")
9797 ;; if in a code block, then open the block's results
9798 (unless (call-interactively #'org-babel-open-src-block-result)
9799 (org-load-modules-maybe)
9800 (move-marker org-open-link-marker (point))
9801 (setq org-window-config-before-follow-link (current-window-configuration))
9802 (org-remove-occur-highlights nil nil t)
9803 (cond
9804 ((and (org-at-heading-p)
9805 (not (org-at-timestamp-p t))
9806 (not (org-in-regexp
9807 (concat org-plain-link-re "\\|"
9808 org-bracket-link-regexp "\\|"
9809 org-angle-link-re "\\|"
9810 "[ \t]:[^ \t\n]+:[ \t]*$")))
9811 (not (get-text-property (point) 'org-linked-text)))
9812 (or (org-offer-links-in-entry arg)
9813 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9814 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9815 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9816 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9817 (not (org-in-regexp org-bracket-link-regexp)))
9818 (org-footnote-action))
9820 (let (type path link line search (pos (point)))
9821 (catch 'match
9822 (save-excursion
9823 (skip-chars-forward "^]\n\r")
9824 (when (org-in-regexp org-bracket-link-regexp 1)
9825 (setq link (org-extract-attributes
9826 (org-link-unescape (org-match-string-no-properties 1))))
9827 (while (string-match " *\n *" link)
9828 (setq link (replace-match " " t t link)))
9829 (setq link (org-link-expand-abbrev link))
9830 (cond
9831 ((or (file-name-absolute-p link)
9832 (string-match "^\\.\\.?/" link))
9833 (setq type "file" path link))
9834 ((string-match org-link-re-with-space3 link)
9835 (setq type (match-string 1 link) path (match-string 2 link)))
9836 ((string-match "^help:+\\(.+\\)" link)
9837 (setq type "help" path (match-string 1 link)))
9838 (t (setq type "thisfile" path link)))
9839 (throw 'match t)))
9841 (when (get-text-property (point) 'org-linked-text)
9842 (setq type "thisfile"
9843 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9844 (1+ (point)) (point))
9845 path (buffer-substring
9846 (or (previous-single-property-change pos 'org-linked-text)
9847 (point-min))
9848 (or (next-single-property-change pos 'org-linked-text)
9849 (point-max))))
9850 (throw 'match t))
9852 (save-excursion
9853 (when (or (org-in-regexp org-angle-link-re)
9854 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9855 (save-match-data (not (looking-back "\\[\\[")))))
9856 (setq type (match-string 1)
9857 path (org-link-unescape (match-string 2)))
9858 (throw 'match t)))
9859 (save-excursion
9860 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9861 (setq type "tags"
9862 path (match-string 1))
9863 (while (string-match ":" path)
9864 (setq path (replace-match "+" t t path)))
9865 (throw 'match t)))
9866 (when (org-in-regexp "<\\([^><\n]+\\)>")
9867 (setq type "tree-match"
9868 path (match-string 1))
9869 (throw 'match t)))
9870 (unless path
9871 (error "No link found"))
9873 ;; switch back to reference buffer
9874 ;; needed when if called in a temporary buffer through
9875 ;; org-open-link-from-string
9876 (with-current-buffer (or reference-buffer (current-buffer))
9878 ;; Remove any trailing spaces in path
9879 (if (string-match " +\\'" path)
9880 (setq path (replace-match "" t t path)))
9881 (if (and org-link-translation-function
9882 (fboundp org-link-translation-function))
9883 ;; Check if we need to translate the link
9884 (let ((tmp (funcall org-link-translation-function type path)))
9885 (setq type (car tmp) path (cdr tmp))))
9887 (cond
9889 ((assoc type org-link-protocols)
9890 (funcall (nth 1 (assoc type org-link-protocols)) path))
9892 ((equal type "help")
9893 (let ((f-or-v (intern path)))
9894 (cond ((fboundp f-or-v)
9895 (describe-function f-or-v))
9896 ((boundp f-or-v)
9897 (describe-variable f-or-v))
9898 (t (error "Not a known function or variable")))))
9900 ((equal type "mailto")
9901 (let ((cmd (car org-link-mailto-program))
9902 (args (cdr org-link-mailto-program)) args1
9903 (address path) (subject "") a)
9904 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9905 (setq address (match-string 1 path)
9906 subject (org-link-escape (match-string 2 path))))
9907 (while args
9908 (cond
9909 ((not (stringp (car args))) (push (pop args) args1))
9910 (t (setq a (pop args))
9911 (if (string-match "%a" a)
9912 (setq a (replace-match address t t a)))
9913 (if (string-match "%s" a)
9914 (setq a (replace-match subject t t a)))
9915 (push a args1))))
9916 (apply cmd (nreverse args1))))
9918 ((member type '("http" "https" "ftp" "news"))
9919 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9920 (org-link-escape
9921 path org-link-escape-chars-browser)
9922 path))))
9924 ((string= type "doi")
9925 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9926 (org-link-escape
9927 path org-link-escape-chars-browser)
9928 path))))
9930 ((member type '("message"))
9931 (browse-url (concat type ":" path)))
9933 ((string= type "tags")
9934 (org-tags-view arg path))
9936 ((string= type "tree-match")
9937 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9939 ((string= type "file")
9940 (if (string-match "::\\([0-9]+\\)\\'" path)
9941 (setq line (string-to-number (match-string 1 path))
9942 path (substring path 0 (match-beginning 0)))
9943 (if (string-match "::\\(.+\\)\\'" path)
9944 (setq search (match-string 1 path)
9945 path (substring path 0 (match-beginning 0)))))
9946 (if (string-match "[*?{]" (file-name-nondirectory path))
9947 (dired path)
9948 (org-open-file path arg line search)))
9950 ((string= type "shell")
9951 (let ((buf (generate-new-buffer "*Org Shell Output"))
9952 (cmd path))
9953 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9954 (string-match org-confirm-shell-link-not-regexp cmd))
9955 (not org-confirm-shell-link-function)
9956 (funcall org-confirm-shell-link-function
9957 (format "Execute \"%s\" in shell? "
9958 (org-add-props cmd nil
9959 'face 'org-warning))))
9960 (progn
9961 (message "Executing %s" cmd)
9962 (shell-command cmd buf)
9963 (if (featurep 'midnight)
9964 (setq clean-buffer-list-kill-buffer-names
9965 (cons buf clean-buffer-list-kill-buffer-names))))
9966 (error "Abort"))))
9968 ((string= type "elisp")
9969 (let ((cmd path))
9970 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9971 (string-match org-confirm-elisp-link-not-regexp cmd))
9972 (not org-confirm-elisp-link-function)
9973 (funcall org-confirm-elisp-link-function
9974 (format "Execute \"%s\" as elisp? "
9975 (org-add-props cmd nil
9976 'face 'org-warning))))
9977 (message "%s => %s" cmd
9978 (if (equal (string-to-char cmd) ?\()
9979 (eval (read cmd))
9980 (call-interactively (read cmd))))
9981 (error "Abort"))))
9983 ((and (string= type "thisfile")
9984 (run-hook-with-args-until-success
9985 'org-open-link-functions path)))
9987 ((string= type "thisfile")
9988 (if arg
9989 (switch-to-buffer-other-window
9990 (org-get-buffer-for-internal-link (current-buffer)))
9991 (org-mark-ring-push))
9992 (let ((cmd `(org-link-search
9993 ,path
9994 ,(cond ((equal arg '(4)) ''occur)
9995 ((equal arg '(16)) ''org-occur))
9996 ,pos)))
9997 (condition-case nil (let ((org-link-search-inhibit-query t))
9998 (eval cmd))
9999 (error (progn (widen) (eval cmd))))))
10001 (t (browse-url-at-point)))))))
10002 (move-marker org-open-link-marker nil)
10003 (run-hook-with-args 'org-follow-link-hook)))
10005 (defun org-offer-links-in-entry (&optional nth zero)
10006 "Offer links in the current entry and follow the selected link.
10007 If there is only one link, follow it immediately as well.
10008 If NTH is an integer, immediately pick the NTH link found.
10009 If ZERO is a string, check also this string for a link, and if
10010 there is one, offer it as link number zero."
10011 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10012 "\\(" org-angle-link-re "\\)\\|"
10013 "\\(" org-plain-link-re "\\)"))
10014 (cnt ?0)
10015 (in-emacs (if (integerp nth) nil nth))
10016 have-zero end links link c)
10017 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10018 (push (match-string 0 zero) links)
10019 (setq cnt (1- cnt) have-zero t))
10020 (save-excursion
10021 (org-back-to-heading t)
10022 (setq end (save-excursion (outline-next-heading) (point)))
10023 (while (re-search-forward re end t)
10024 (push (match-string 0) links))
10025 (setq links (org-uniquify (reverse links))))
10027 (cond
10028 ((null links)
10029 (message "No links"))
10030 ((equal (length links) 1)
10031 (setq link (list (car links))))
10032 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10033 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10034 (t ; we have to select a link
10035 (save-excursion
10036 (save-window-excursion
10037 (delete-other-windows)
10038 (with-output-to-temp-buffer "*Select Link*"
10039 (mapc (lambda (l)
10040 (if (not (string-match org-bracket-link-regexp l))
10041 (princ (format "[%c] %s\n" (incf cnt)
10042 (org-remove-angle-brackets l)))
10043 (if (match-end 3)
10044 (princ (format "[%c] %s (%s)\n" (incf cnt)
10045 (match-string 3 l) (match-string 1 l)))
10046 (princ (format "[%c] %s\n" (incf cnt)
10047 (match-string 1 l))))))
10048 links))
10049 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10050 (message "Select link to open, RET to open all:")
10051 (setq c (read-char-exclusive))
10052 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10053 (when (equal c ?q) (error "Abort"))
10054 (if (equal c ?\C-m)
10055 (setq link links)
10056 (setq nth (- c ?0))
10057 (if have-zero (setq nth (1+ nth)))
10058 (unless (and (integerp nth) (>= (length links) nth))
10059 (error "Invalid link selection"))
10060 (setq link (list (nth (1- nth) links))))))
10061 (if link
10062 (let ((buf (current-buffer)))
10063 (dolist (l link)
10064 (org-open-link-from-string l in-emacs buf))
10066 nil)))
10068 ;; Add special file links that specify the way of opening
10070 (org-add-link-type "file+sys" 'org-open-file-with-system)
10071 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10072 (defun org-open-file-with-system (path)
10073 "Open file at PATH using the system way of opening it."
10074 (org-open-file path 'system))
10075 (defun org-open-file-with-emacs (path)
10076 "Open file at PATH in Emacs."
10077 (org-open-file path 'emacs))
10078 (defun org-remove-file-link-modifiers ()
10079 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10080 (goto-char (point-min))
10081 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10082 (org-if-unprotected
10083 (replace-match "file:" t t))))
10084 (eval-after-load "org-exp"
10085 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10086 'org-remove-file-link-modifiers))
10088 ;;;; Time estimates
10090 (defun org-get-effort (&optional pom)
10091 "Get the effort estimate for the current entry."
10092 (org-entry-get pom org-effort-property))
10094 ;;; File search
10096 (defvar org-create-file-search-functions nil
10097 "List of functions to construct the right search string for a file link.
10098 These functions are called in turn with point at the location to
10099 which the link should point.
10101 A function in the hook should first test if it would like to
10102 handle this file type, for example by checking the `major-mode'
10103 or the file extension. If it decides not to handle this file, it
10104 should just return nil to give other functions a chance. If it
10105 does handle the file, it must return the search string to be used
10106 when following the link. The search string will be part of the
10107 file link, given after a double colon, and `org-open-at-point'
10108 will automatically search for it. If special measures must be
10109 taken to make the search successful, another function should be
10110 added to the companion hook `org-execute-file-search-functions',
10111 which see.
10113 A function in this hook may also use `setq' to set the variable
10114 `description' to provide a suggestion for the descriptive text to
10115 be used for this link when it gets inserted into an Org-mode
10116 buffer with \\[org-insert-link].")
10118 (defvar org-execute-file-search-functions nil
10119 "List of functions to execute a file search triggered by a link.
10121 Functions added to this hook must accept a single argument, the
10122 search string that was part of the file link, the part after the
10123 double colon. The function must first check if it would like to
10124 handle this search, for example by checking the `major-mode' or
10125 the file extension. If it decides not to handle this search, it
10126 should just return nil to give other functions a chance. If it
10127 does handle the search, it must return a non-nil value to keep
10128 other functions from trying.
10130 Each function can access the current prefix argument through the
10131 variable `current-prefix-argument'. Note that a single prefix is
10132 used to force opening a link in Emacs, so it may be good to only
10133 use a numeric or double prefix to guide the search function.
10135 In case this is needed, a function in this hook can also restore
10136 the window configuration before `org-open-at-point' was called using:
10138 (set-window-configuration org-window-config-before-follow-link)")
10140 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10141 (defun org-link-search (s &optional type avoid-pos stealth)
10142 "Search for a link search option.
10143 If S is surrounded by forward slashes, it is interpreted as a
10144 regular expression. In org-mode files, this will create an `org-occur'
10145 sparse tree. In ordinary files, `occur' will be used to list matches.
10146 If the current buffer is in `dired-mode', grep will be used to search
10147 in all files. If AVOID-POS is given, ignore matches near that position.
10149 When optional argument STEALTH is non-nil, do not modify
10150 visibility around point, thus ignoring
10151 `org-show-hierarchy-above', `org-show-following-heading' and
10152 `org-show-siblings' variables."
10153 (let ((case-fold-search t)
10154 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10155 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10156 (append '(("") (" ") ("\t") ("\n"))
10157 org-emphasis-alist)
10158 "\\|") "\\)"))
10159 (pos (point))
10160 (pre nil) (post nil)
10161 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10162 (cond
10163 ;; First check if there are any special search functions
10164 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10165 ;; Now try the builtin stuff
10166 ((and (equal (string-to-char s0) ?#)
10167 (> (length s0) 1)
10168 (save-excursion
10169 (goto-char (point-min))
10170 (and
10171 (re-search-forward
10172 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10173 (setq type 'dedicated
10174 pos (match-beginning 0))))
10175 ;; There is an exact target for this
10176 (goto-char pos)
10177 (org-back-to-heading t)))
10178 ((save-excursion
10179 (goto-char (point-min))
10180 (and
10181 (re-search-forward
10182 (concat "<<" (regexp-quote s0) ">>") nil t)
10183 (setq type 'dedicated
10184 pos (match-beginning 0))))
10185 ;; There is an exact target for this
10186 (goto-char pos))
10187 ((save-excursion
10188 (goto-char (point-min))
10189 (and
10190 (re-search-forward
10191 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10192 (setq type 'dedicated pos (match-beginning 0))))
10193 ;; Found an invisible target.
10194 (goto-char pos))
10195 ((save-excursion
10196 (goto-char (point-min))
10197 (and
10198 (re-search-forward
10199 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10200 (setq type 'dedicated pos (match-beginning 0))))
10201 ;; Found an element with a matching #+name affiliated keyword.
10202 (goto-char pos))
10203 ((and (string-match "^(\\(.*\\))$" s0)
10204 (save-excursion
10205 (goto-char (point-min))
10206 (and
10207 (re-search-forward
10208 (concat "[^[]" (regexp-quote
10209 (format org-coderef-label-format
10210 (match-string 1 s0))))
10211 nil t)
10212 (setq type 'dedicated
10213 pos (1+ (match-beginning 0))))))
10214 ;; There is a coderef target for this
10215 (goto-char pos))
10216 ((string-match "^/\\(.*\\)/$" s)
10217 ;; A regular expression
10218 (cond
10219 ((derived-mode-p 'org-mode)
10220 (org-occur (match-string 1 s)))
10221 ;;((eq major-mode 'dired-mode)
10222 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10223 (t (org-do-occur (match-string 1 s)))))
10224 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10225 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10226 (goto-char (point-min))
10227 (cond
10228 ((let (case-fold-search)
10229 (re-search-forward (format org-complex-heading-regexp-format
10230 (regexp-quote s))
10231 nil t))
10232 ;; OK, found a match
10233 (setq type 'dedicated)
10234 (goto-char (match-beginning 0)))
10235 ((and (not org-link-search-inhibit-query)
10236 (eq org-link-search-must-match-exact-headline 'query-to-create)
10237 (y-or-n-p "No match - create this as a new heading? "))
10238 (goto-char (point-max))
10239 (or (bolp) (newline))
10240 (insert "* " s "\n")
10241 (beginning-of-line 0))
10243 (goto-char pos)
10244 (error "No match"))))
10246 ;; A normal search string
10247 (when (equal (string-to-char s) ?*)
10248 ;; Anchor on headlines, post may include tags.
10249 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10250 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10251 s (substring s 1)))
10252 (remove-text-properties
10253 0 (length s)
10254 '(face nil mouse-face nil keymap nil fontified nil) s)
10255 ;; Make a series of regular expressions to find a match
10256 (setq words (org-split-string s "[ \n\r\t]+")
10258 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10259 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10260 "\\)" markers)
10261 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10262 re2a (concat "[ \t\r\n]" re2a_)
10263 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10264 re4 (concat "[^a-zA-Z_]" re4_)
10266 re1 (concat pre re2 post)
10267 re3 (concat pre (if pre re4_ re4) post)
10268 re5 (concat pre ".*" re4)
10269 re2 (concat pre re2)
10270 re2a (concat pre (if pre re2a_ re2a))
10271 re4 (concat pre (if pre re4_ re4))
10272 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10273 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10274 re5 "\\)"
10276 (cond
10277 ((eq type 'org-occur) (org-occur reall))
10278 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10279 (t (goto-char (point-min))
10280 (setq type 'fuzzy)
10281 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10282 (org-search-not-self 1 re1 nil t)
10283 (org-search-not-self 1 re2 nil t)
10284 (org-search-not-self 1 re2a nil t)
10285 (org-search-not-self 1 re3 nil t)
10286 (org-search-not-self 1 re4 nil t)
10287 (org-search-not-self 1 re5 nil t)
10289 (goto-char (match-beginning 1))
10290 (goto-char pos)
10291 (error "No match"))))))
10292 (and (derived-mode-p 'org-mode)
10293 (not stealth)
10294 (org-show-context 'link-search))
10295 type))
10297 (defun org-search-not-self (group &rest args)
10298 "Execute `re-search-forward', but only accept matches that do not
10299 enclose the position of `org-open-link-marker'."
10300 (let ((m org-open-link-marker))
10301 (catch 'exit
10302 (while (apply 're-search-forward args)
10303 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10304 (goto-char (match-end group))
10305 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10306 (> (match-beginning 0) (marker-position m))
10307 (< (match-end 0) (marker-position m)))
10308 (save-match-data
10309 (or (not (org-in-regexp
10310 org-bracket-link-analytic-regexp 1))
10311 (not (match-end 4)) ; no description
10312 (and (<= (match-beginning 4) (point))
10313 (>= (match-end 4) (point))))))
10314 (throw 'exit (point))))))))
10316 (defun org-get-buffer-for-internal-link (buffer)
10317 "Return a buffer to be used for displaying the link target of internal links."
10318 (cond
10319 ((not org-display-internal-link-with-indirect-buffer)
10320 buffer)
10321 ((string-match "(Clone)$" (buffer-name buffer))
10322 (message "Buffer is already a clone, not making another one")
10323 ;; we also do not modify visibility in this case
10324 buffer)
10325 (t ; make a new indirect buffer for displaying the link
10326 (let* ((bn (buffer-name buffer))
10327 (ibn (concat bn "(Clone)"))
10328 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10329 (with-current-buffer ib (org-overview))
10330 ib))))
10332 (defun org-do-occur (regexp &optional cleanup)
10333 "Call the Emacs command `occur'.
10334 If CLEANUP is non-nil, remove the printout of the regular expression
10335 in the *Occur* buffer. This is useful if the regex is long and not useful
10336 to read."
10337 (occur regexp)
10338 (when cleanup
10339 (let ((cwin (selected-window)) win beg end)
10340 (when (setq win (get-buffer-window "*Occur*"))
10341 (select-window win))
10342 (goto-char (point-min))
10343 (when (re-search-forward "match[a-z]+" nil t)
10344 (setq beg (match-end 0))
10345 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10346 (setq end (1- (match-beginning 0)))))
10347 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10348 (goto-char (point-min))
10349 (select-window cwin))))
10351 ;;; The mark ring for links jumps
10353 (defvar org-mark-ring nil
10354 "Mark ring for positions before jumps in Org-mode.")
10355 (defvar org-mark-ring-last-goto nil
10356 "Last position in the mark ring used to go back.")
10357 ;; Fill and close the ring
10358 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10359 (loop for i from 1 to org-mark-ring-length do
10360 (push (make-marker) org-mark-ring))
10361 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10362 org-mark-ring)
10364 (defun org-mark-ring-push (&optional pos buffer)
10365 "Put the current position or POS into the mark ring and rotate it."
10366 (interactive)
10367 (setq pos (or pos (point)))
10368 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10369 (move-marker (car org-mark-ring)
10370 (or pos (point))
10371 (or buffer (current-buffer)))
10372 (message "%s"
10373 (substitute-command-keys
10374 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10376 (defun org-mark-ring-goto (&optional n)
10377 "Jump to the previous position in the mark ring.
10378 With prefix arg N, jump back that many stored positions. When
10379 called several times in succession, walk through the entire ring.
10380 Org-mode commands jumping to a different position in the current file,
10381 or to another Org-mode file, automatically push the old position
10382 onto the ring."
10383 (interactive "p")
10384 (let (p m)
10385 (if (eq last-command this-command)
10386 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10387 (setq p org-mark-ring))
10388 (setq org-mark-ring-last-goto p)
10389 (setq m (car p))
10390 (org-pop-to-buffer-same-window (marker-buffer m))
10391 (goto-char m)
10392 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10394 (defun org-remove-angle-brackets (s)
10395 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10396 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10398 (defun org-add-angle-brackets (s)
10399 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10400 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10402 (defun org-remove-double-quotes (s)
10403 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10404 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10407 ;;; Following specific links
10409 (defun org-follow-timestamp-link ()
10410 (cond
10411 ((org-at-date-range-p t)
10412 (let ((org-agenda-start-on-weekday)
10413 (t1 (match-string 1))
10414 (t2 (match-string 2)))
10415 (setq t1 (time-to-days (org-time-string-to-time t1))
10416 t2 (time-to-days (org-time-string-to-time t2)))
10417 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10418 ((org-at-timestamp-p t)
10419 (org-agenda-list nil (time-to-days (org-time-string-to-time
10420 (substring (match-string 1) 0 10)))
10422 (t (error "This should not happen"))))
10425 ;;; Following file links
10426 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10427 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10428 (declare-function mailcap-mime-info
10429 "mailcap" (string &optional request no-decode))
10430 (defvar org-wait nil)
10431 (defun org-open-file (path &optional in-emacs line search)
10432 "Open the file at PATH.
10433 First, this expands any special file name abbreviations. Then the
10434 configuration variable `org-file-apps' is checked if it contains an
10435 entry for this file type, and if yes, the corresponding command is launched.
10437 If no application is found, Emacs simply visits the file.
10439 With optional prefix argument IN-EMACS, Emacs will visit the file.
10440 With a double \\[universal-argument] \\[universal-argument] \
10441 prefix arg, Org tries to avoid opening in Emacs
10442 and to use an external application to visit the file.
10444 Optional LINE specifies a line to go to, optional SEARCH a string
10445 to search for. If LINE or SEARCH is given, the file will be
10446 opened in Emacs, unless an entry from org-file-apps that makes
10447 use of groups in a regexp matches.
10449 If you want to change the way frames are used when following a
10450 link, please customize `org-link-frame-setup'.
10452 If the file does not exist, an error is thrown."
10453 (let* ((file (if (equal path "")
10454 buffer-file-name
10455 (substitute-in-file-name (expand-file-name path))))
10456 (file-apps (append org-file-apps (org-default-apps)))
10457 (apps (org-remove-if
10458 'org-file-apps-entry-match-against-dlink-p file-apps))
10459 (apps-dlink (org-remove-if-not
10460 'org-file-apps-entry-match-against-dlink-p file-apps))
10461 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10462 (dirp (if remp nil (file-directory-p file)))
10463 (file (if (and dirp org-open-directory-means-index-dot-org)
10464 (concat (file-name-as-directory file) "index.org")
10465 file))
10466 (a-m-a-p (assq 'auto-mode apps))
10467 (dfile (downcase file))
10468 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10469 (link (cond ((and (eq line nil)
10470 (eq search nil))
10471 file)
10472 (line
10473 (concat file "::" (number-to-string line)))
10474 (search
10475 (concat file "::" search))))
10476 (dlink (downcase link))
10477 (old-buffer (current-buffer))
10478 (old-pos (point))
10479 (old-mode major-mode)
10480 ext cmd link-match-data)
10481 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10482 (setq ext (match-string 1 dfile))
10483 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10484 (setq ext (match-string 1 dfile))))
10485 (cond
10486 ((member in-emacs '((16) system))
10487 (setq cmd (cdr (assoc 'system apps))))
10488 (in-emacs (setq cmd 'emacs))
10490 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10491 (and dirp (cdr (assoc 'directory apps)))
10492 ; first, try matching against apps-dlink
10493 ; if we get a match here, store the match data for later
10494 (let ((match (assoc-default dlink apps-dlink
10495 'string-match)))
10496 (if match
10497 (progn (setq link-match-data (match-data))
10498 match)
10499 (progn (setq in-emacs (or in-emacs line search))
10500 nil))) ; if we have no match in apps-dlink,
10501 ; always open the file in emacs if line or search
10502 ; is given (for backwards compatibility)
10503 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10504 'string-match)
10505 (cdr (assoc ext apps))
10506 (cdr (assoc t apps))))))
10507 (when (eq cmd 'system)
10508 (setq cmd (cdr (assoc 'system apps))))
10509 (when (eq cmd 'default)
10510 (setq cmd (cdr (assoc t apps))))
10511 (when (eq cmd 'mailcap)
10512 (require 'mailcap)
10513 (mailcap-parse-mailcaps)
10514 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10515 (command (mailcap-mime-info mime-type)))
10516 (if (stringp command)
10517 (setq cmd command)
10518 (setq cmd 'emacs))))
10519 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10520 (not (file-exists-p file))
10521 (not org-open-non-existing-files))
10522 (error "No such file: %s" file))
10523 (cond
10524 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10525 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10526 (while (string-match "['\"]%s['\"]" cmd)
10527 (setq cmd (replace-match "%s" t t cmd)))
10528 (while (string-match "%s" cmd)
10529 (setq cmd (replace-match
10530 (save-match-data
10531 (shell-quote-argument
10532 (convert-standard-filename file)))
10533 t t cmd)))
10535 ;; Replace "%1", "%2" etc. in command with group matches from regex
10536 (save-match-data
10537 (let ((match-index 1)
10538 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10539 (set-match-data link-match-data)
10540 (while (<= match-index number-of-groups)
10541 (let ((regex (concat "%" (number-to-string match-index)))
10542 (replace-with (match-string match-index dlink)))
10543 (while (string-match regex cmd)
10544 (setq cmd (replace-match replace-with t t cmd))))
10545 (setq match-index (+ match-index 1)))))
10547 (save-window-excursion
10548 (message "Running %s...done" cmd)
10549 (start-process-shell-command cmd nil cmd)
10550 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10551 ((or (stringp cmd)
10552 (eq cmd 'emacs))
10553 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10554 (widen)
10555 (if line (org-goto-line line)
10556 (if search (org-link-search search))))
10557 ((consp cmd)
10558 (let ((file (convert-standard-filename file)))
10559 (save-match-data
10560 (set-match-data link-match-data)
10561 (eval cmd))))
10562 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10563 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10564 (or (not (equal old-buffer (current-buffer)))
10565 (not (equal old-pos (point))))
10566 (org-mark-ring-push old-pos old-buffer))))
10568 (defun org-file-apps-entry-match-against-dlink-p (entry)
10569 "This function returns non-nil if `entry' uses a regular
10570 expression which should be matched against the whole link by
10571 org-open-file.
10573 It assumes that is the case when the entry uses a regular
10574 expression which has at least one grouping construct and the
10575 action is either a lisp form or a command string containing
10576 '%1', i.e. using at least one subexpression match as a
10577 parameter."
10578 (let ((selector (car entry))
10579 (action (cdr entry)))
10580 (if (stringp selector)
10581 (and (> (regexp-opt-depth selector) 0)
10582 (or (and (stringp action)
10583 (string-match "%[0-9]" action))
10584 (consp action)))
10585 nil)))
10587 (defun org-default-apps ()
10588 "Return the default applications for this operating system."
10589 (cond
10590 ((eq system-type 'darwin)
10591 org-file-apps-defaults-macosx)
10592 ((eq system-type 'windows-nt)
10593 org-file-apps-defaults-windowsnt)
10594 (t org-file-apps-defaults-gnu)))
10596 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10597 "Convert extensions to regular expressions in the cars of LIST.
10598 Also, weed out any non-string entries, because the return value is used
10599 only for regexp matching.
10600 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10601 point to the symbol `emacs', indicating that the file should
10602 be opened in Emacs."
10603 (append
10604 (delq nil
10605 (mapcar (lambda (x)
10606 (if (not (stringp (car x)))
10608 (if (string-match "\\W" (car x))
10610 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10611 list))
10612 (if add-auto-mode
10613 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10615 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10616 (defun org-file-remote-p (file)
10617 "Test whether FILE specifies a location on a remote system.
10618 Return non-nil if the location is indeed remote.
10620 For example, the filename \"/user@host:/foo\" specifies a location
10621 on the system \"/user@host:\"."
10622 (cond ((fboundp 'file-remote-p)
10623 (file-remote-p file))
10624 ((fboundp 'tramp-handle-file-remote-p)
10625 (tramp-handle-file-remote-p file))
10626 ((and (boundp 'ange-ftp-name-format)
10627 (string-match (car ange-ftp-name-format) file))
10628 t)))
10631 ;;;; Refiling
10633 (defun org-get-org-file ()
10634 "Read a filename, with default directory `org-directory'."
10635 (let ((default (or org-default-notes-file remember-data-file)))
10636 (read-file-name (format "File name [%s]: " default)
10637 (file-name-as-directory org-directory)
10638 default)))
10640 (defun org-notes-order-reversed-p ()
10641 "Check if the current file should receive notes in reversed order."
10642 (cond
10643 ((not org-reverse-note-order) nil)
10644 ((eq t org-reverse-note-order) t)
10645 ((not (listp org-reverse-note-order)) nil)
10646 (t (catch 'exit
10647 (let ((all org-reverse-note-order)
10648 entry)
10649 (while (setq entry (pop all))
10650 (if (string-match (car entry) buffer-file-name)
10651 (throw 'exit (cdr entry))))
10652 nil)))))
10654 (defvar org-refile-target-table nil
10655 "The list of refile targets, created by `org-refile'.")
10657 (defvar org-agenda-new-buffers nil
10658 "Buffers created to visit agenda files.")
10660 (defvar org-refile-cache nil
10661 "Cache for refile targets.")
10663 (defvar org-refile-markers nil
10664 "All the markers used for caching refile locations.")
10666 (defun org-refile-marker (pos)
10667 "Get a new refile marker, but only if caching is in use."
10668 (if (not org-refile-use-cache)
10670 (let ((m (make-marker)))
10671 (move-marker m pos)
10672 (push m org-refile-markers)
10673 m)))
10675 (defun org-refile-cache-clear ()
10676 "Clear the refile cache and disable all the markers."
10677 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10678 (setq org-refile-markers nil)
10679 (setq org-refile-cache nil)
10680 (message "Refile cache has been cleared"))
10682 (defun org-refile-cache-check-set (set)
10683 "Check if all the markers in the cache still have live buffers."
10684 (let (marker)
10685 (catch 'exit
10686 (while (and set (setq marker (nth 3 (pop set))))
10687 ;; if org-refile-use-outline-path is 'file, marker may be nil
10688 (when (and marker (null (marker-buffer marker)))
10689 (message "not found") (sit-for 3)
10690 (throw 'exit nil)))
10691 t)))
10693 (defun org-refile-cache-put (set &rest identifiers)
10694 "Push the refile targets SET into the cache, under IDENTIFIERS."
10695 (let* ((key (sha1 (prin1-to-string identifiers)))
10696 (entry (assoc key org-refile-cache)))
10697 (if entry
10698 (setcdr entry set)
10699 (push (cons key set) org-refile-cache))))
10701 (defun org-refile-cache-get (&rest identifiers)
10702 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10703 (cond
10704 ((not org-refile-cache) nil)
10705 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10707 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10708 org-refile-cache))))
10709 (and set (org-refile-cache-check-set set) set)))))
10711 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10712 "Produce a table with refile targets."
10713 (let ((case-fold-search nil)
10714 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10715 (entries (or org-refile-targets '((nil . (:level . 1)))))
10716 targets tgs txt re files f desc descre fast-path-p level pos0)
10717 (message "Getting targets...")
10718 (with-current-buffer (or default-buffer (current-buffer))
10719 (while (setq entry (pop entries))
10720 (setq files (car entry) desc (cdr entry))
10721 (setq fast-path-p nil)
10722 (cond
10723 ((null files) (setq files (list (current-buffer))))
10724 ((eq files 'org-agenda-files)
10725 (setq files (org-agenda-files 'unrestricted)))
10726 ((and (symbolp files) (fboundp files))
10727 (setq files (funcall files)))
10728 ((and (symbolp files) (boundp files))
10729 (setq files (symbol-value files))))
10730 (if (stringp files) (setq files (list files)))
10731 (cond
10732 ((eq (car desc) :tag)
10733 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10734 ((eq (car desc) :todo)
10735 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10736 ((eq (car desc) :regexp)
10737 (setq descre (cdr desc)))
10738 ((eq (car desc) :level)
10739 (setq descre (concat "^\\*\\{" (number-to-string
10740 (if org-odd-levels-only
10741 (1- (* 2 (cdr desc)))
10742 (cdr desc)))
10743 "\\}[ \t]")))
10744 ((eq (car desc) :maxlevel)
10745 (setq fast-path-p t)
10746 (setq descre (concat "^\\*\\{1," (number-to-string
10747 (if org-odd-levels-only
10748 (1- (* 2 (cdr desc)))
10749 (cdr desc)))
10750 "\\}[ \t]")))
10751 (t (error "Bad refiling target description %s" desc)))
10752 (while (setq f (pop files))
10753 (with-current-buffer
10754 (if (bufferp f) f (org-get-agenda-file-buffer f))
10756 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10757 (progn
10758 (if (bufferp f) (setq f (buffer-file-name
10759 (buffer-base-buffer f))))
10760 (setq f (and f (expand-file-name f)))
10761 (if (eq org-refile-use-outline-path 'file)
10762 (push (list (file-name-nondirectory f) f nil nil) tgs))
10763 (save-excursion
10764 (save-restriction
10765 (widen)
10766 (goto-char (point-min))
10767 (while (re-search-forward descre nil t)
10768 (goto-char (setq pos0 (point-at-bol)))
10769 (catch 'next
10770 (when org-refile-target-verify-function
10771 (save-match-data
10772 (or (funcall org-refile-target-verify-function)
10773 (throw 'next t))))
10774 (when (and (looking-at org-complex-heading-regexp)
10775 (not (member (match-string 4) excluded-entries))
10776 (match-string 4))
10777 (setq level (org-reduced-level
10778 (- (match-end 1) (match-beginning 1)))
10779 txt (org-link-display-format (match-string 4))
10780 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10781 re (format org-complex-heading-regexp-format
10782 (regexp-quote (match-string 4))))
10783 (when org-refile-use-outline-path
10784 (setq txt (mapconcat
10785 'org-protect-slash
10786 (append
10787 (if (eq org-refile-use-outline-path
10788 'file)
10789 (list (file-name-nondirectory
10790 (buffer-file-name
10791 (buffer-base-buffer))))
10792 (if (eq org-refile-use-outline-path
10793 'full-file-path)
10794 (list (buffer-file-name
10795 (buffer-base-buffer)))))
10796 (org-get-outline-path fast-path-p
10797 level txt)
10798 (list txt))
10799 "/")))
10800 (push (list txt f re (org-refile-marker (point)))
10801 tgs)))
10802 (when (= (point) pos0)
10803 ;; verification function has not moved point
10804 (goto-char (point-at-eol))))))))
10805 (when org-refile-use-cache
10806 (org-refile-cache-put tgs (buffer-file-name) descre))
10807 (setq targets (append tgs targets))
10808 ))))
10809 (message "Getting targets...done")
10810 (nreverse targets)))
10812 (defun org-protect-slash (s)
10813 (while (string-match "/" s)
10814 (setq s (replace-match "\\" t t s)))
10817 (defvar org-olpa (make-vector 20 nil))
10819 (defun org-get-outline-path (&optional fastp level heading)
10820 "Return the outline path to the current entry, as a list.
10822 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10823 routine which makes outline path derivations for an entire file,
10824 avoiding backtracing. Refile target collection makes use of that."
10825 (if fastp
10826 (progn
10827 (if (> level 19)
10828 (error "Outline path failure, more than 19 levels"))
10829 (loop for i from level upto 19 do
10830 (aset org-olpa i nil))
10831 (prog1
10832 (delq nil (append org-olpa nil))
10833 (aset org-olpa level heading)))
10834 (let (rtn case-fold-search)
10835 (save-excursion
10836 (save-restriction
10837 (widen)
10838 (while (org-up-heading-safe)
10839 (when (looking-at org-complex-heading-regexp)
10840 (push (org-match-string-no-properties 4) rtn)))
10841 rtn)))))
10843 (defun org-format-outline-path (path &optional width prefix)
10844 "Format the outline path PATH for display.
10845 Width is the maximum number of characters that is available.
10846 Prefix is a prefix to be included in the returned string,
10847 such as the file name."
10848 (setq width (or width 79))
10849 (if prefix (setq width (- width (length prefix))))
10850 (if (not path)
10851 (or prefix "")
10852 (let* ((nsteps (length path))
10853 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10854 (maxwidth (if (<= total-width width)
10855 10000 ;; everything fits
10856 ;; we need to shorten the level headings
10857 (/ (- width nsteps) nsteps)))
10858 (org-odd-levels-only nil)
10859 (n 0)
10860 (total (1+ (length prefix))))
10861 (setq maxwidth (max maxwidth 10))
10862 (concat prefix
10863 (mapconcat
10864 (lambda (h)
10865 (setq n (1+ n))
10866 (if (and (= n nsteps) (< maxwidth 10000))
10867 (setq maxwidth (- total-width total)))
10868 (if (< (length h) maxwidth)
10869 (progn (setq total (+ total (length h) 1)) h)
10870 (setq h (substring h 0 (- maxwidth 2))
10871 total (+ total maxwidth 1))
10872 (if (string-match "[ \t]+\\'" h)
10873 (setq h (substring h 0 (match-beginning 0))))
10874 (setq h (concat h "..")))
10875 (org-add-props h nil 'face
10876 (nth (% (1- n) org-n-level-faces)
10877 org-level-faces))
10879 path "/")))))
10881 (defun org-display-outline-path (&optional file current)
10882 "Display the current outline path in the echo area."
10883 (interactive "P")
10884 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10885 (case-fold-search nil)
10886 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10887 (if current (setq path (append path
10888 (save-excursion
10889 (org-back-to-heading t)
10890 (if (looking-at org-complex-heading-regexp)
10891 (list (match-string 4)))))))
10892 (message "%s"
10893 (org-format-outline-path
10894 path
10895 (1- (frame-width))
10896 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10898 (defvar org-refile-history nil
10899 "History for refiling operations.")
10901 (defvar org-after-refile-insert-hook nil
10902 "Hook run after `org-refile' has inserted its stuff at the new location.
10903 Note that this is still *before* the stuff will be removed from
10904 the *old* location.")
10906 (defvar org-capture-last-stored-marker)
10907 (defun org-refile (&optional goto default-buffer rfloc)
10908 "Move the entry or entries at point to another heading.
10909 The list of target headings is compiled using the information in
10910 `org-refile-targets', which see.
10912 At the target location, the entry is filed as a subitem of the target
10913 heading. Depending on `org-reverse-note-order', the new subitem will
10914 either be the first or the last subitem.
10916 If there is an active region, all entries in that region will be moved.
10917 However, the region must fulfill the requirement that the first heading
10918 is the first one sets the top-level of the moved text - at most siblings
10919 below it are allowed.
10921 With prefix arg GOTO, the command will only visit the target location
10922 and not actually move anything.
10924 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10925 go to the location where the last refiling operation has put the subtree.
10926 With a prefix argument of `2', refile to the running clock.
10928 RFLOC can be a refile location obtained in a different way.
10930 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10932 If you are using target caching (see `org-refile-use-cache'),
10933 you have to clear the target cache in order to find new targets.
10934 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10935 prefix argument (`C-u C-u C-u C-c C-w')."
10937 (interactive "P")
10938 (if (member goto '(0 (64)))
10939 (org-refile-cache-clear)
10940 (let* ((cbuf (current-buffer))
10941 (regionp (org-region-active-p))
10942 (region-start (and regionp (region-beginning)))
10943 (region-end (and regionp (region-end)))
10944 (region-length (and regionp (- region-end region-start)))
10945 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10946 pos it nbuf file re level reversed)
10947 (setq last-command nil)
10948 (when regionp
10949 (goto-char region-start)
10950 (or (bolp) (goto-char (point-at-bol)))
10951 (setq region-start (point))
10952 (unless (or (org-kill-is-subtree-p
10953 (buffer-substring region-start region-end))
10954 (prog1 org-refile-active-region-within-subtree
10955 (org-toggle-heading)))
10956 (error "The region is not a (sequence of) subtree(s)")))
10957 (if (equal goto '(16))
10958 (org-refile-goto-last-stored)
10959 (when (or
10960 (and (equal goto 2)
10961 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10962 (prog1
10963 (setq it (list (or org-clock-heading "running clock")
10964 (buffer-file-name
10965 (marker-buffer org-clock-hd-marker))
10967 (marker-position org-clock-hd-marker)))
10968 (setq goto nil)))
10969 (setq it (or rfloc
10970 (let (heading-text)
10971 (save-excursion
10972 (unless goto
10973 (org-back-to-heading t)
10974 (setq heading-text
10975 (nth 4 (org-heading-components))))
10976 (org-refile-get-location
10977 (cond (goto "Goto")
10978 (regionp "Refile region to")
10979 (t (concat "Refile subtree \""
10980 heading-text "\" to")))
10981 default-buffer
10982 (and (not (equal '(4) goto))
10983 org-refile-allow-creating-parent-nodes)
10984 goto))))))
10985 (setq file (nth 1 it)
10986 re (nth 2 it)
10987 pos (nth 3 it))
10988 (if (and (not goto)
10990 (equal (buffer-file-name) file)
10991 (if regionp
10992 (and (>= pos region-start)
10993 (<= pos region-end))
10994 (and (>= pos (point))
10995 (< pos (save-excursion
10996 (org-end-of-subtree t t))))))
10997 (error "Cannot refile to position inside the tree or region"))
10999 (setq nbuf (or (find-buffer-visiting file)
11000 (find-file-noselect file)))
11001 (if goto
11002 (progn
11003 (org-pop-to-buffer-same-window nbuf)
11004 (goto-char pos)
11005 (org-show-context 'org-goto))
11006 (if regionp
11007 (progn
11008 (org-kill-new (buffer-substring region-start region-end))
11009 (org-save-markers-in-region region-start region-end))
11010 (org-copy-subtree 1 nil t))
11011 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11012 (find-file-noselect file)))
11013 (setq reversed (org-notes-order-reversed-p))
11014 (save-excursion
11015 (save-restriction
11016 (widen)
11017 (if pos
11018 (progn
11019 (goto-char pos)
11020 (looking-at org-outline-regexp)
11021 (setq level (org-get-valid-level (funcall outline-level) 1))
11022 (goto-char
11023 (if reversed
11024 (or (outline-next-heading) (point-max))
11025 (or (save-excursion (org-get-next-sibling))
11026 (org-end-of-subtree t t)
11027 (point-max)))))
11028 (setq level 1)
11029 (if (not reversed)
11030 (goto-char (point-max))
11031 (goto-char (point-min))
11032 (or (outline-next-heading) (goto-char (point-max)))))
11033 (if (not (bolp)) (newline))
11034 (org-paste-subtree level)
11035 (when org-log-refile
11036 (org-add-log-setup 'refile nil nil 'findpos
11037 org-log-refile)
11038 (unless (eq org-log-refile 'note)
11039 (save-excursion (org-add-log-note))))
11040 (and org-auto-align-tags
11041 (let ((org-loop-over-headlines-in-active-region nil))
11042 (org-set-tags nil t)))
11043 (bookmark-set "org-refile-last-stored")
11044 ;; If we are refiling for capture, make sure that the
11045 ;; last-capture pointers point here
11046 (when (org-bound-and-true-p org-refile-for-capture)
11047 (bookmark-set "org-capture-last-stored-marker")
11048 (move-marker org-capture-last-stored-marker (point)))
11049 (if (fboundp 'deactivate-mark) (deactivate-mark))
11050 (run-hooks 'org-after-refile-insert-hook))))
11051 (if regionp
11052 (delete-region (point) (+ (point) region-length))
11053 (org-cut-subtree))
11054 (when (featurep 'org-inlinetask)
11055 (org-inlinetask-remove-END-maybe))
11056 (setq org-markers-to-move nil)
11057 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11059 (defun org-refile-goto-last-stored ()
11060 "Go to the location where the last refile was stored."
11061 (interactive)
11062 (bookmark-jump "org-refile-last-stored")
11063 (message "This is the location of the last refile"))
11065 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11066 no-exclude)
11067 "Prompt the user for a refile location, using PROMPT.
11068 PROMPT should not be suffixed with a colon and a space, because
11069 this function appends the default value from
11070 `org-refile-history' automatically, if that is not empty.
11071 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11072 this is used for the GOTO interface."
11073 (let ((org-refile-targets org-refile-targets)
11074 (org-refile-use-outline-path org-refile-use-outline-path)
11075 excluded-entries)
11076 (when (and (derived-mode-p 'org-mode)
11077 (not org-refile-use-cache)
11078 (not no-exclude))
11079 (org-map-tree
11080 (lambda()
11081 (setq excluded-entries
11082 (append excluded-entries (list (org-get-heading t t)))))))
11083 (setq org-refile-target-table
11084 (org-refile-get-targets default-buffer excluded-entries)))
11085 (unless org-refile-target-table
11086 (error "No refile targets"))
11087 (let* ((prompt (concat prompt
11088 (and (car org-refile-history)
11089 (concat " (default " (car org-refile-history) ")"))
11090 ": "))
11091 (cbuf (current-buffer))
11092 (partial-completion-mode nil)
11093 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11094 (cfunc (if (and org-refile-use-outline-path
11095 org-outline-path-complete-in-steps)
11096 'org-olpath-completing-read
11097 'org-icompleting-read))
11098 (extra (if org-refile-use-outline-path "/" ""))
11099 (filename (and cfn (expand-file-name cfn)))
11100 (tbl (mapcar
11101 (lambda (x)
11102 (if (and (not (member org-refile-use-outline-path
11103 '(file full-file-path)))
11104 (not (equal filename (nth 1 x))))
11105 (cons (concat (car x) extra " ("
11106 (file-name-nondirectory (nth 1 x)) ")")
11107 (cdr x))
11108 (cons (concat (car x) extra) (cdr x))))
11109 org-refile-target-table))
11110 (completion-ignore-case t)
11111 pa answ parent-target child parent old-hist)
11112 (setq old-hist org-refile-history)
11113 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11114 nil 'org-refile-history (car org-refile-history)))
11115 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11116 (org-refile-check-position pa)
11117 (if pa
11118 (progn
11119 (when (or (not org-refile-history)
11120 (not (eq old-hist org-refile-history))
11121 (not (equal (car pa) (car org-refile-history))))
11122 (setq org-refile-history
11123 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11124 org-refile-history
11125 (cdr org-refile-history))))
11126 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11127 (pop org-refile-history)))
11129 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11130 (progn
11131 (setq parent (match-string 1 answ)
11132 child (match-string 2 answ))
11133 (setq parent-target (or (assoc parent tbl)
11134 (assoc (concat parent "/") tbl)))
11135 (when (and parent-target
11136 (or (eq new-nodes t)
11137 (and (eq new-nodes 'confirm)
11138 (y-or-n-p (format "Create new node \"%s\"? "
11139 child)))))
11140 (org-refile-new-child parent-target child)))
11141 (error "Invalid target location")))))
11143 (declare-function org-string-nw-p "org-macs.el" (s))
11144 (defun org-refile-check-position (refile-pointer)
11145 "Check if the refile pointer matches the readline to which it points."
11146 (let* ((file (nth 1 refile-pointer))
11147 (re (nth 2 refile-pointer))
11148 (pos (nth 3 refile-pointer))
11149 buffer)
11150 (when (org-string-nw-p re)
11151 (setq buffer (if (markerp pos)
11152 (marker-buffer pos)
11153 (or (find-buffer-visiting file)
11154 (find-file-noselect file))))
11155 (with-current-buffer buffer
11156 (save-excursion
11157 (save-restriction
11158 (widen)
11159 (goto-char pos)
11160 (beginning-of-line 1)
11161 (unless (org-looking-at-p re)
11162 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11164 (defun org-refile-new-child (parent-target child)
11165 "Use refile target PARENT-TARGET to add new CHILD below it."
11166 (unless parent-target
11167 (error "Cannot find parent for new node"))
11168 (let ((file (nth 1 parent-target))
11169 (pos (nth 3 parent-target))
11170 level)
11171 (with-current-buffer (or (find-buffer-visiting file)
11172 (find-file-noselect file))
11173 (save-excursion
11174 (save-restriction
11175 (widen)
11176 (if pos
11177 (goto-char pos)
11178 (goto-char (point-max))
11179 (if (not (bolp)) (newline)))
11180 (when (looking-at org-outline-regexp)
11181 (setq level (funcall outline-level))
11182 (org-end-of-subtree t t))
11183 (org-back-over-empty-lines)
11184 (insert "\n" (make-string
11185 (if pos (org-get-valid-level level 1) 1) ?*)
11186 " " child "\n")
11187 (beginning-of-line 0)
11188 (list (concat (car parent-target) "/" child) file "" (point)))))))
11190 (defun org-olpath-completing-read (prompt collection &rest args)
11191 "Read an outline path like a file name."
11192 (let ((thetable collection)
11193 (org-completion-use-ido nil) ; does not work with ido.
11194 (org-completion-use-iswitchb nil)) ; or iswitchb
11195 (apply
11196 'org-icompleting-read prompt
11197 (lambda (string predicate &optional flag)
11198 (let (rtn r f (l (length string)))
11199 (cond
11200 ((eq flag nil)
11201 ;; try completion
11202 (try-completion string thetable))
11203 ((eq flag t)
11204 ;; all-completions
11205 (setq rtn (all-completions string thetable predicate))
11206 (mapcar
11207 (lambda (x)
11208 (setq r (substring x l))
11209 (if (string-match " ([^)]*)$" x)
11210 (setq f (match-string 0 x))
11211 (setq f ""))
11212 (if (string-match "/" r)
11213 (concat string (substring r 0 (match-end 0)) f)
11215 rtn))
11216 ((eq flag 'lambda)
11217 ;; exact match?
11218 (assoc string thetable)))))
11219 args)))
11221 ;;;; Dynamic blocks
11223 (defun org-find-dblock (name)
11224 "Find the first dynamic block with name NAME in the buffer.
11225 If not found, stay at current position and return nil."
11226 (let ((case-fold-search t) pos)
11227 (save-excursion
11228 (goto-char (point-min))
11229 (setq pos (and (re-search-forward
11230 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11231 (match-beginning 0))))
11232 (if pos (goto-char pos))
11233 pos))
11235 (defconst org-dblock-start-re
11236 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11237 "Matches the start line of a dynamic block, with parameters.")
11239 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11240 "Matches the end of a dynamic block.")
11242 (defun org-create-dblock (plist)
11243 "Create a dynamic block section, with parameters taken from PLIST.
11244 PLIST must contain a :name entry which is used as name of the block."
11245 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11246 (end-of-line 1)
11247 (newline))
11248 (let ((col (current-column))
11249 (name (plist-get plist :name)))
11250 (insert "#+BEGIN: " name)
11251 (while plist
11252 (if (eq (car plist) :name)
11253 (setq plist (cddr plist))
11254 (insert " " (prin1-to-string (pop plist)))))
11255 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11256 (beginning-of-line -2)))
11258 (defun org-prepare-dblock ()
11259 "Prepare dynamic block for refresh.
11260 This empties the block, puts the cursor at the insert position and returns
11261 the property list including an extra property :name with the block name."
11262 (unless (looking-at org-dblock-start-re)
11263 (error "Not at a dynamic block"))
11264 (let* ((begdel (1+ (match-end 0)))
11265 (name (org-no-properties (match-string 1)))
11266 (params (append (list :name name)
11267 (read (concat "(" (match-string 3) ")")))))
11268 (save-excursion
11269 (beginning-of-line 1)
11270 (skip-chars-forward " \t")
11271 (setq params (plist-put params :indentation-column (current-column))))
11272 (unless (re-search-forward org-dblock-end-re nil t)
11273 (error "Dynamic block not terminated"))
11274 (setq params
11275 (append params
11276 (list :content (buffer-substring
11277 begdel (match-beginning 0)))))
11278 (delete-region begdel (match-beginning 0))
11279 (goto-char begdel)
11280 (open-line 1)
11281 params))
11283 (defun org-map-dblocks (&optional command)
11284 "Apply COMMAND to all dynamic blocks in the current buffer.
11285 If COMMAND is not given, use `org-update-dblock'."
11286 (let ((cmd (or command 'org-update-dblock)))
11287 (save-excursion
11288 (goto-char (point-min))
11289 (while (re-search-forward org-dblock-start-re nil t)
11290 (goto-char (match-beginning 0))
11291 (save-excursion
11292 (condition-case nil
11293 (funcall cmd)
11294 (error (message "Error during update of dynamic block"))))
11295 (unless (re-search-forward org-dblock-end-re nil t)
11296 (error "Dynamic block not terminated"))))))
11298 (defun org-dblock-update (&optional arg)
11299 "User command for updating dynamic blocks.
11300 Update the dynamic block at point. With prefix ARG, update all dynamic
11301 blocks in the buffer."
11302 (interactive "P")
11303 (if arg
11304 (org-update-all-dblocks)
11305 (or (looking-at org-dblock-start-re)
11306 (org-beginning-of-dblock))
11307 (org-update-dblock)))
11309 (defun org-update-dblock ()
11310 "Update the dynamic block at point.
11311 This means to empty the block, parse for parameters and then call
11312 the correct writing function."
11313 (interactive)
11314 (save-window-excursion
11315 (let* ((pos (point))
11316 (line (org-current-line))
11317 (params (org-prepare-dblock))
11318 (name (plist-get params :name))
11319 (indent (plist-get params :indentation-column))
11320 (cmd (intern (concat "org-dblock-write:" name))))
11321 (message "Updating dynamic block `%s' at line %d..." name line)
11322 (funcall cmd params)
11323 (message "Updating dynamic block `%s' at line %d...done" name line)
11324 (goto-char pos)
11325 (when (and indent (> indent 0))
11326 (setq indent (make-string indent ?\ ))
11327 (save-excursion
11328 (org-beginning-of-dblock)
11329 (forward-line 1)
11330 (while (not (looking-at org-dblock-end-re))
11331 (insert indent)
11332 (beginning-of-line 2))
11333 (when (looking-at org-dblock-end-re)
11334 (and (looking-at "[ \t]+")
11335 (replace-match ""))
11336 (insert indent)))))))
11338 (defun org-beginning-of-dblock ()
11339 "Find the beginning of the dynamic block at point.
11340 Error if there is no such block at point."
11341 (let ((pos (point))
11342 beg)
11343 (end-of-line 1)
11344 (if (and (re-search-backward org-dblock-start-re nil t)
11345 (setq beg (match-beginning 0))
11346 (re-search-forward org-dblock-end-re nil t)
11347 (> (match-end 0) pos))
11348 (goto-char beg)
11349 (goto-char pos)
11350 (error "Not in a dynamic block"))))
11352 ;;;###autoload
11353 (defun org-update-all-dblocks ()
11354 "Update all dynamic blocks in the buffer.
11355 This function can be used in a hook."
11356 (interactive)
11357 (when (derived-mode-p 'org-mode)
11358 (org-map-dblocks 'org-update-dblock)))
11361 ;;;; Completion
11363 (defconst org-additional-option-like-keywords
11364 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11365 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11366 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11367 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11368 "BEGIN:" "END:"
11369 "ORGTBL" "TBLFM:" "TBLNAME:"
11370 "BEGIN_EXAMPLE" "END_EXAMPLE"
11371 "BEGIN_VERBATIM" "END_VERBATIM"
11372 "BEGIN_QUOTE" "END_QUOTE"
11373 "BEGIN_VERSE" "END_VERSE"
11374 "BEGIN_CENTER" "END_CENTER"
11375 "BEGIN_SRC" "END_SRC"
11376 "BEGIN_RESULT" "END_RESULT"
11377 "BEGIN_lstlisting" "END_lstlisting"
11378 "NAME:" "RESULTS:"
11379 "HEADER:" "HEADERS:"
11380 "COLUMNS:" "PROPERTY:"
11381 "CAPTION:" "LABEL:"
11382 "SETUPFILE:"
11383 "INCLUDE:"
11384 "BIND:"
11385 "MACRO:"))
11387 (defconst org-options-keywords
11388 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11389 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11390 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11391 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11392 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11393 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11394 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11396 (defconst org-additional-option-like-keywords-for-flyspell
11397 (delete-dups
11398 (split-string
11399 (mapconcat (lambda(k)
11400 (replace-regexp-in-string
11401 "_\\|:" " "
11402 (concat k " " (downcase k) " " (upcase k))))
11403 (append org-options-keywords org-additional-option-like-keywords)
11404 " ")
11405 " +" t)))
11407 (defcustom org-structure-template-alist
11409 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11410 "<src lang=\"?\">\n\n</src>")
11411 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11412 "<example>\n?\n</example>")
11413 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11414 "<quote>\n?\n</quote>")
11415 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11416 "<verse>\n?\n</verse>")
11417 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11418 "<center>\n?\n</center>")
11419 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11420 "<literal style=\"latex\">\n?\n</literal>")
11421 ("L" "#+LaTeX: "
11422 "<literal style=\"latex\">?</literal>")
11423 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11424 "<literal style=\"html\">\n?\n</literal>")
11425 ("H" "#+HTML: "
11426 "<literal style=\"html\">?</literal>")
11427 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11428 ("A" "#+ASCII: ")
11429 ("i" "#+INDEX: ?"
11430 "#+INDEX: ?")
11431 ("I" "#+INCLUDE: %file ?"
11432 "<include file=%file markup=\"?\">")
11434 "Structure completion elements.
11435 This is a list of abbreviation keys and values. The value gets inserted
11436 if you type `<' followed by the key and then press the completion key,
11437 usually `M-TAB'. %file will be replaced by a file name after prompting
11438 for the file using completion. The cursor will be placed at the position
11439 of the `?` in the template.
11440 There are two templates for each key, the first uses the original Org syntax,
11441 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11442 the default when the /org-mtags.el/ module has been loaded. See also the
11443 variable `org-mtags-prefer-muse-templates'."
11444 :group 'org-completion
11445 :type '(repeat
11446 (string :tag "Key")
11447 (string :tag "Template")
11448 (string :tag "Muse Template")))
11450 (defun org-try-structure-completion ()
11451 "Try to complete a structure template before point.
11452 This looks for strings like \"<e\" on an otherwise empty line and
11453 expands them."
11454 (let ((l (buffer-substring (point-at-bol) (point)))
11456 (when (and (looking-at "[ \t]*$")
11457 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11458 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11459 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11460 (match-beginning 1)) a)
11461 t)))
11463 (defun org-complete-expand-structure-template (start cell)
11464 "Expand a structure template."
11465 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11466 (rpl (nth (if musep 2 1) cell))
11467 (ind ""))
11468 (delete-region start (point))
11469 (when (string-match "\\`#\\+" rpl)
11470 (cond
11471 ((bolp))
11472 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11473 (setq ind (buffer-substring (point-at-bol) (point))))
11474 (t (newline))))
11475 (setq start (point))
11476 (if (string-match "%file" rpl)
11477 (setq rpl (replace-match
11478 (concat
11479 "\""
11480 (save-match-data
11481 (abbreviate-file-name (read-file-name "Include file: ")))
11482 "\"")
11483 t t rpl)))
11484 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11485 (concat "\n" ind)))
11486 (insert rpl)
11487 (if (re-search-backward "\\?" start t) (delete-char 1))))
11489 ;;;; TODO, DEADLINE, Comments
11491 (defun org-toggle-comment ()
11492 "Change the COMMENT state of an entry."
11493 (interactive)
11494 (save-excursion
11495 (org-back-to-heading)
11496 (let (case-fold-search)
11497 (cond
11498 ((looking-at (format org-heading-keyword-regexp-format
11499 org-comment-string))
11500 (goto-char (match-end 1))
11501 (looking-at (concat " +" org-comment-string))
11502 (replace-match "" t t)
11503 (when (eolp) (insert " ")))
11504 ((looking-at org-outline-regexp)
11505 (goto-char (match-end 0))
11506 (insert org-comment-string " "))))))
11508 (defvar org-last-todo-state-is-todo nil
11509 "This is non-nil when the last TODO state change led to a TODO state.
11510 If the last change removed the TODO tag or switched to DONE, then
11511 this is nil.")
11513 (defvar org-setting-tags nil) ; dynamically skipped
11515 (defvar org-todo-setup-filter-hook nil
11516 "Hook for functions that pre-filter todo specs.
11517 Each function takes a todo spec and returns either nil or the spec
11518 transformed into canonical form." )
11520 (defvar org-todo-get-default-hook nil
11521 "Hook for functions that get a default item for todo.
11522 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11523 nil or a string to be used for the todo mark." )
11525 (defvar org-agenda-headline-snapshot-before-repeat)
11527 (defun org-current-effective-time ()
11528 "Return current time adjusted for `org-extend-today-until' variable."
11529 (let* ((ct (org-current-time))
11530 (dct (decode-time ct))
11531 (ct1
11532 (if (and org-use-effective-time
11533 (< (nth 2 dct) org-extend-today-until))
11534 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11535 ct)))
11536 ct1))
11538 (defun org-todo-yesterday (&optional arg)
11539 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11540 (interactive "P")
11541 (if (eq major-mode 'org-agenda-mode)
11542 (apply 'org-agenda-todo-yesterday arg)
11543 (let* ((hour (third (decode-time
11544 (org-current-time))))
11545 (org-extend-today-until (1+ hour)))
11546 (org-todo arg))))
11548 (defun org-todo (&optional arg)
11549 "Change the TODO state of an item.
11550 The state of an item is given by a keyword at the start of the heading,
11551 like
11552 *** TODO Write paper
11553 *** DONE Call mom
11555 The different keywords are specified in the variable `org-todo-keywords'.
11556 By default the available states are \"TODO\" and \"DONE\".
11557 So for this example: when the item starts with TODO, it is changed to DONE.
11558 When it starts with DONE, the DONE is removed. And when neither TODO nor
11559 DONE are present, add TODO at the beginning of the heading.
11561 With \\[universal-argument] prefix arg, use completion to determine the new \
11562 state.
11563 With numeric prefix arg, switch to that state.
11564 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11565 keywords (nextset).
11566 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11567 With a numeric prefix arg of 0, inhibit note taking for the change.
11569 For calling through lisp, arg is also interpreted in the following way:
11570 'none -> empty state
11571 \"\"(empty string) -> switch to empty state
11572 'done -> switch to DONE
11573 'nextset -> switch to the next set of keywords
11574 'previousset -> switch to the previous set of keywords
11575 \"WAITING\" -> switch to the specified keyword, but only if it
11576 really is a member of `org-todo-keywords'."
11577 (interactive "P")
11578 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11579 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11580 'region-start-level 'region))
11581 org-loop-over-headlines-in-active-region)
11582 (org-map-entries
11583 `(org-todo ,arg)
11584 org-loop-over-headlines-in-active-region
11585 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11586 (if (equal arg '(16)) (setq arg 'nextset))
11587 (let ((org-blocker-hook org-blocker-hook)
11588 (case-fold-search nil))
11589 (when (equal arg '(64))
11590 (setq arg nil org-blocker-hook nil))
11591 (when (and org-blocker-hook
11592 (or org-inhibit-blocking
11593 (org-entry-get nil "NOBLOCKING")))
11594 (setq org-blocker-hook nil))
11595 (save-excursion
11596 (catch 'exit
11597 (org-back-to-heading t)
11598 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11599 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11600 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11601 (let* ((match-data (match-data))
11602 (startpos (point-at-bol))
11603 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11604 (org-log-done org-log-done)
11605 (org-log-repeat org-log-repeat)
11606 (org-todo-log-states org-todo-log-states)
11607 (org-inhibit-logging
11608 (if (equal arg 0)
11609 (progn (setq arg nil) 'note) org-inhibit-logging))
11610 (this (match-string 1))
11611 (hl-pos (match-beginning 0))
11612 (head (org-get-todo-sequence-head this))
11613 (ass (assoc head org-todo-kwd-alist))
11614 (interpret (nth 1 ass))
11615 (done-word (nth 3 ass))
11616 (final-done-word (nth 4 ass))
11617 (org-last-state (or this ""))
11618 (completion-ignore-case t)
11619 (member (member this org-todo-keywords-1))
11620 (tail (cdr member))
11621 (org-state (cond
11622 ((and org-todo-key-trigger
11623 (or (and (equal arg '(4))
11624 (eq org-use-fast-todo-selection 'prefix))
11625 (and (not arg) org-use-fast-todo-selection
11626 (not (eq org-use-fast-todo-selection
11627 'prefix)))))
11628 ;; Use fast selection
11629 (org-fast-todo-selection))
11630 ((and (equal arg '(4))
11631 (or (not org-use-fast-todo-selection)
11632 (not org-todo-key-trigger)))
11633 ;; Read a state with completion
11634 (org-icompleting-read
11635 "State: " (mapcar (lambda(x) (list x))
11636 org-todo-keywords-1)
11637 nil t))
11638 ((eq arg 'right)
11639 (if this
11640 (if tail (car tail) nil)
11641 (car org-todo-keywords-1)))
11642 ((eq arg 'left)
11643 (if (equal member org-todo-keywords-1)
11645 (if this
11646 (nth (- (length org-todo-keywords-1)
11647 (length tail) 2)
11648 org-todo-keywords-1)
11649 (org-last org-todo-keywords-1))))
11650 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11651 (setq arg nil))) ; hack to fall back to cycling
11652 (arg
11653 ;; user or caller requests a specific state
11654 (cond
11655 ((equal arg "") nil)
11656 ((eq arg 'none) nil)
11657 ((eq arg 'done) (or done-word (car org-done-keywords)))
11658 ((eq arg 'nextset)
11659 (or (car (cdr (member head org-todo-heads)))
11660 (car org-todo-heads)))
11661 ((eq arg 'previousset)
11662 (let ((org-todo-heads (reverse org-todo-heads)))
11663 (or (car (cdr (member head org-todo-heads)))
11664 (car org-todo-heads))))
11665 ((car (member arg org-todo-keywords-1)))
11666 ((stringp arg)
11667 (error "State `%s' not valid in this file" arg))
11668 ((nth (1- (prefix-numeric-value arg))
11669 org-todo-keywords-1))))
11670 ((null member) (or head (car org-todo-keywords-1)))
11671 ((equal this final-done-word) nil) ;; -> make empty
11672 ((null tail) nil) ;; -> first entry
11673 ((memq interpret '(type priority))
11674 (if (eq this-command last-command)
11675 (car tail)
11676 (if (> (length tail) 0)
11677 (or done-word (car org-done-keywords))
11678 nil)))
11680 (car tail))))
11681 (org-state (or
11682 (run-hook-with-args-until-success
11683 'org-todo-get-default-hook org-state org-last-state)
11684 org-state))
11685 (next (if org-state (concat " " org-state " ") " "))
11686 (change-plist (list :type 'todo-state-change :from this :to org-state
11687 :position startpos))
11688 dolog now-done-p)
11689 (when org-blocker-hook
11690 (setq org-last-todo-state-is-todo
11691 (not (member this org-done-keywords)))
11692 (unless (save-excursion
11693 (save-match-data
11694 (org-with-wide-buffer
11695 (run-hook-with-args-until-failure
11696 'org-blocker-hook change-plist))))
11697 (if (org-called-interactively-p 'interactive)
11698 (error "TODO state change from %s to %s blocked" this org-state)
11699 ;; fail silently
11700 (message "TODO state change from %s to %s blocked" this org-state)
11701 (throw 'exit nil))))
11702 (store-match-data match-data)
11703 (replace-match next t t)
11704 (unless (pos-visible-in-window-p hl-pos)
11705 (message "TODO state changed to %s" (org-trim next)))
11706 (unless head
11707 (setq head (org-get-todo-sequence-head org-state)
11708 ass (assoc head org-todo-kwd-alist)
11709 interpret (nth 1 ass)
11710 done-word (nth 3 ass)
11711 final-done-word (nth 4 ass)))
11712 (when (memq arg '(nextset previousset))
11713 (message "Keyword-Set %d/%d: %s"
11714 (- (length org-todo-sets) -1
11715 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11716 (length org-todo-sets)
11717 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11718 (setq org-last-todo-state-is-todo
11719 (not (member org-state org-done-keywords)))
11720 (setq now-done-p (and (member org-state org-done-keywords)
11721 (not (member this org-done-keywords))))
11722 (and logging (org-local-logging logging))
11723 (when (and (or org-todo-log-states org-log-done)
11724 (not (eq org-inhibit-logging t))
11725 (not (memq arg '(nextset previousset))))
11726 ;; we need to look at recording a time and note
11727 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11728 (nth 2 (assoc this org-todo-log-states))))
11729 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11730 (setq dolog 'time))
11731 (when (and org-state
11732 (member org-state org-not-done-keywords)
11733 (not (member this org-not-done-keywords)))
11734 ;; This is now a todo state and was not one before
11735 ;; If there was a CLOSED time stamp, get rid of it.
11736 (org-add-planning-info nil nil 'closed))
11737 (when (and now-done-p org-log-done)
11738 ;; It is now done, and it was not done before
11739 (org-add-planning-info 'closed (org-current-effective-time))
11740 (if (and (not dolog) (eq 'note org-log-done))
11741 (org-add-log-setup 'done org-state this 'findpos 'note)))
11742 (when (and org-state dolog)
11743 ;; This is a non-nil state, and we need to log it
11744 (org-add-log-setup 'state org-state this 'findpos dolog)))
11745 ;; Fixup tag positioning
11746 (org-todo-trigger-tag-changes org-state)
11747 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11748 (when org-provide-todo-statistics
11749 (org-update-parent-todo-statistics))
11750 (run-hooks 'org-after-todo-state-change-hook)
11751 (if (and arg (not (member org-state org-done-keywords)))
11752 (setq head (org-get-todo-sequence-head org-state)))
11753 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11754 ;; Do we need to trigger a repeat?
11755 (when now-done-p
11756 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11757 ;; This is for the agenda, take a snapshot of the headline.
11758 (save-match-data
11759 (setq org-agenda-headline-snapshot-before-repeat
11760 (org-get-heading))))
11761 (org-auto-repeat-maybe org-state))
11762 ;; Fixup cursor location if close to the keyword
11763 (if (and (outline-on-heading-p)
11764 (not (bolp))
11765 (save-excursion (beginning-of-line 1)
11766 (looking-at org-todo-line-regexp))
11767 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11768 (progn
11769 (goto-char (or (match-end 2) (match-end 1)))
11770 (and (looking-at " ") (just-one-space))))
11771 (when org-trigger-hook
11772 (save-excursion
11773 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11775 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11776 "Block turning an entry into a TODO, using the hierarchy.
11777 This checks whether the current task should be blocked from state
11778 changes. Such blocking occurs when:
11780 1. The task has children which are not all in a completed state.
11782 2. A task has a parent with the property :ORDERED:, and there
11783 are siblings prior to the current task with incomplete
11784 status.
11786 3. The parent of the task is blocked because it has siblings that should
11787 be done first, or is child of a block grandparent TODO entry."
11789 (if (not org-enforce-todo-dependencies)
11790 t ; if locally turned off don't block
11791 (catch 'dont-block
11792 ;; If this is not a todo state change, or if this entry is already DONE,
11793 ;; do not block
11794 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11795 (member (plist-get change-plist :from)
11796 (cons 'done org-done-keywords))
11797 (member (plist-get change-plist :to)
11798 (cons 'todo org-not-done-keywords))
11799 (not (plist-get change-plist :to)))
11800 (throw 'dont-block t))
11801 ;; If this task has children, and any are undone, it's blocked
11802 (save-excursion
11803 (org-back-to-heading t)
11804 (let ((this-level (funcall outline-level)))
11805 (outline-next-heading)
11806 (let ((child-level (funcall outline-level)))
11807 (while (and (not (eobp))
11808 (> child-level this-level))
11809 ;; this todo has children, check whether they are all
11810 ;; completed
11811 (if (and (not (org-entry-is-done-p))
11812 (org-entry-is-todo-p))
11813 (throw 'dont-block nil))
11814 (outline-next-heading)
11815 (setq child-level (funcall outline-level))))))
11816 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11817 ;; any previous siblings are undone, it's blocked
11818 (save-excursion
11819 (org-back-to-heading t)
11820 (let* ((pos (point))
11821 (parent-pos (and (org-up-heading-safe) (point))))
11822 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11823 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11824 (forward-line 1)
11825 (re-search-forward org-not-done-heading-regexp pos t))
11826 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11827 ;; Search further up the hierarchy, to see if an ancestor is blocked
11828 (while t
11829 (goto-char parent-pos)
11830 (if (not (looking-at org-not-done-heading-regexp))
11831 (throw 'dont-block t)) ; do not block, parent is not a TODO
11832 (setq pos (point))
11833 (setq parent-pos (and (org-up-heading-safe) (point)))
11834 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11835 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11836 (forward-line 1)
11837 (re-search-forward org-not-done-heading-regexp pos t))
11838 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11840 (defcustom org-track-ordered-property-with-tag nil
11841 "Should the ORDERED property also be shown as a tag?
11842 The ORDERED property decides if an entry should require subtasks to be
11843 completed in sequence. Since a property is not very visible, setting
11844 this option means that toggling the ORDERED property with the command
11845 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11846 not relevant for the behavior, but it makes things more visible.
11848 Note that toggling the tag with tags commands will not change the property
11849 and therefore not influence behavior!
11851 This can be t, meaning the tag ORDERED should be used, It can also be a
11852 string to select a different tag for this task."
11853 :group 'org-todo
11854 :type '(choice
11855 (const :tag "No tracking" nil)
11856 (const :tag "Track with ORDERED tag" t)
11857 (string :tag "Use other tag")))
11859 (defun org-toggle-ordered-property ()
11860 "Toggle the ORDERED property of the current entry.
11861 For better visibility, you can track the value of this property with a tag.
11862 See variable `org-track-ordered-property-with-tag'."
11863 (interactive)
11864 (let* ((t1 org-track-ordered-property-with-tag)
11865 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11866 (save-excursion
11867 (org-back-to-heading)
11868 (if (org-entry-get nil "ORDERED")
11869 (progn
11870 (org-delete-property "ORDERED")
11871 (and tag (org-toggle-tag tag 'off))
11872 (message "Subtasks can be completed in arbitrary order"))
11873 (org-entry-put nil "ORDERED" "t")
11874 (and tag (org-toggle-tag tag 'on))
11875 (message "Subtasks must be completed in sequence")))))
11877 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11878 (defun org-block-todo-from-checkboxes (change-plist)
11879 "Block turning an entry into a TODO, using checkboxes.
11880 This checks whether the current task should be blocked from state
11881 changes because there are unchecked boxes in this entry."
11882 (if (not org-enforce-todo-checkbox-dependencies)
11883 t ; if locally turned off don't block
11884 (catch 'dont-block
11885 ;; If this is not a todo state change, or if this entry is already DONE,
11886 ;; do not block
11887 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11888 (member (plist-get change-plist :from)
11889 (cons 'done org-done-keywords))
11890 (member (plist-get change-plist :to)
11891 (cons 'todo org-not-done-keywords))
11892 (not (plist-get change-plist :to)))
11893 (throw 'dont-block t))
11894 ;; If this task has checkboxes that are not checked, it's blocked
11895 (save-excursion
11896 (org-back-to-heading t)
11897 (let ((beg (point)) end)
11898 (outline-next-heading)
11899 (setq end (point))
11900 (goto-char beg)
11901 (if (org-list-search-forward
11902 (concat (org-item-beginning-re)
11903 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11904 "\\[[- ]\\]")
11905 end t)
11906 (progn
11907 (if (boundp 'org-blocked-by-checkboxes)
11908 (setq org-blocked-by-checkboxes t))
11909 (throw 'dont-block nil)))))
11910 t))) ; do not block
11912 (defun org-entry-blocked-p ()
11913 "Is the current entry blocked?"
11914 (if (org-entry-get nil "NOBLOCKING")
11915 nil ;; Never block this entry
11916 (not
11917 (run-hook-with-args-until-failure
11918 'org-blocker-hook
11919 (list :type 'todo-state-change
11920 :position (point)
11921 :from 'todo
11922 :to 'done)))))
11924 (defun org-update-statistics-cookies (all)
11925 "Update the statistics cookie, either from TODO or from checkboxes.
11926 This should be called with the cursor in a line with a statistics cookie."
11927 (interactive "P")
11928 (if all
11929 (progn
11930 (org-update-checkbox-count 'all)
11931 (org-map-entries 'org-update-parent-todo-statistics))
11932 (if (not (org-at-heading-p))
11933 (org-update-checkbox-count)
11934 (let ((pos (move-marker (make-marker) (point)))
11935 end l1 l2)
11936 (ignore-errors (org-back-to-heading t))
11937 (if (not (org-at-heading-p))
11938 (org-update-checkbox-count)
11939 (setq l1 (org-outline-level))
11940 (setq end (save-excursion
11941 (outline-next-heading)
11942 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11943 (point)))
11944 (if (and (save-excursion
11945 (re-search-forward
11946 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11947 (not (save-excursion (re-search-forward
11948 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11949 (org-update-checkbox-count)
11950 (if (and l2 (> l2 l1))
11951 (progn
11952 (goto-char end)
11953 (org-update-parent-todo-statistics))
11954 (goto-char pos)
11955 (beginning-of-line 1)
11956 (while (re-search-forward
11957 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11958 (point-at-eol) t)
11959 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11960 (goto-char pos)
11961 (move-marker pos nil)))))
11963 (defvar org-entry-property-inherited-from) ;; defined below
11964 (defun org-update-parent-todo-statistics ()
11965 "Update any statistics cookie in the parent of the current headline.
11966 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11967 the entire subtree and this will travel up the hierarchy and update
11968 statistics everywhere."
11969 (let* ((prop (save-excursion (org-up-heading-safe)
11970 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11971 (recursive (or (not org-hierarchical-todo-statistics)
11972 (and prop (string-match "\\<recursive\\>" prop))))
11973 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11975 (first t)
11976 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11977 level ltoggle l1 new ndel
11978 (cnt-all 0) (cnt-done 0) is-percent kwd
11979 checkbox-beg ov ovs ove cookie-present)
11980 (catch 'exit
11981 (save-excursion
11982 (beginning-of-line 1)
11983 (setq ltoggle (funcall outline-level))
11984 ;; Three situations are to consider:
11986 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11987 ;; to the top-level ancestor on the headline;
11989 ;; 2. If parent has "recursive" property, repeat up to the
11990 ;; headline setting that property, taking inheritance into
11991 ;; account;
11993 ;; 3. Else, move up to direct parent and proceed only once.
11994 (while (and (setq level (org-up-heading-safe))
11995 (or recursive first)
11996 (>= (point) lim))
11997 (setq first nil cookie-present nil)
11998 (unless (and level
11999 (not (string-match
12000 "\\<checkbox\\>"
12001 (downcase (or (org-entry-get nil "COOKIE_DATA")
12002 "")))))
12003 (throw 'exit nil))
12004 (while (re-search-forward box-re (point-at-eol) t)
12005 (setq cnt-all 0 cnt-done 0 cookie-present t)
12006 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12007 (save-match-data
12008 (unless (outline-next-heading) (throw 'exit nil))
12009 (while (and (looking-at org-complex-heading-regexp)
12010 (> (setq l1 (length (match-string 1))) level))
12011 (setq kwd (and (or recursive (= l1 ltoggle))
12012 (match-string 2)))
12013 (if (or (eq org-provide-todo-statistics 'all-headlines)
12014 (and (listp org-provide-todo-statistics)
12015 (or (member kwd org-provide-todo-statistics)
12016 (member kwd org-done-keywords))))
12017 (setq cnt-all (1+ cnt-all))
12018 (if (eq org-provide-todo-statistics t)
12019 (and kwd (setq cnt-all (1+ cnt-all)))))
12020 (and (member kwd org-done-keywords)
12021 (setq cnt-done (1+ cnt-done)))
12022 (outline-next-heading)))
12023 (setq new
12024 (if is-percent
12025 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12026 (format "[%d/%d]" cnt-done cnt-all))
12027 ndel (- (match-end 0) checkbox-beg))
12028 ;; handle overlays when updating cookie from column view
12029 (when (setq ov (car (overlays-at checkbox-beg)))
12030 (setq ovs (overlay-start ov) ove (overlay-end ov))
12031 (delete-overlay ov))
12032 (goto-char checkbox-beg)
12033 (insert new)
12034 (delete-region (point) (+ (point) ndel))
12035 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12036 (when ov (move-overlay ov ovs ove)))
12037 (when cookie-present
12038 (run-hook-with-args 'org-after-todo-statistics-hook
12039 cnt-done (- cnt-all cnt-done))))))
12040 (run-hooks 'org-todo-statistics-hook)))
12042 (defvar org-after-todo-statistics-hook nil
12043 "Hook that is called after a TODO statistics cookie has been updated.
12044 Each function is called with two arguments: the number of not-done entries
12045 and the number of done entries.
12047 For example, the following function, when added to this hook, will switch
12048 an entry to DONE when all children are done, and back to TODO when new
12049 entries are set to a TODO status. Note that this hook is only called
12050 when there is a statistics cookie in the headline!
12052 (defun org-summary-todo (n-done n-not-done)
12053 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12054 (let (org-log-done org-log-states) ; turn off logging
12055 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12058 (defvar org-todo-statistics-hook nil
12059 "Hook that is run whenever Org thinks TODO statistics should be updated.
12060 This hook runs even if there is no statistics cookie present, in which case
12061 `org-after-todo-statistics-hook' would not run.")
12063 (defun org-todo-trigger-tag-changes (state)
12064 "Apply the changes defined in `org-todo-state-tags-triggers'."
12065 (let ((l org-todo-state-tags-triggers)
12066 changes)
12067 (when (or (not state) (equal state ""))
12068 (setq changes (append changes (cdr (assoc "" l)))))
12069 (when (and (stringp state) (> (length state) 0))
12070 (setq changes (append changes (cdr (assoc state l)))))
12071 (when (member state org-not-done-keywords)
12072 (setq changes (append changes (cdr (assoc 'todo l)))))
12073 (when (member state org-done-keywords)
12074 (setq changes (append changes (cdr (assoc 'done l)))))
12075 (dolist (c changes)
12076 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12078 (defun org-local-logging (value)
12079 "Get logging settings from a property VALUE."
12080 (let* (words w a)
12081 ;; directly set the variables, they are already local.
12082 (setq org-log-done nil
12083 org-log-repeat nil
12084 org-todo-log-states nil)
12085 (setq words (org-split-string value))
12086 (while (setq w (pop words))
12087 (cond
12088 ((setq a (assoc w org-startup-options))
12089 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12090 (set (nth 1 a) (nth 2 a))))
12091 ((setq a (org-extract-log-state-settings w))
12092 (and (member (car a) org-todo-keywords-1)
12093 (push a org-todo-log-states)))))))
12095 (defun org-get-todo-sequence-head (kwd)
12096 "Return the head of the TODO sequence to which KWD belongs.
12097 If KWD is not set, check if there is a text property remembering the
12098 right sequence."
12099 (let (p)
12100 (cond
12101 ((not kwd)
12102 (or (get-text-property (point-at-bol) 'org-todo-head)
12103 (progn
12104 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12105 nil (point-at-eol)))
12106 (get-text-property p 'org-todo-head))))
12107 ((not (member kwd org-todo-keywords-1))
12108 (car org-todo-keywords-1))
12109 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12111 (defun org-fast-todo-selection ()
12112 "Fast TODO keyword selection with single keys.
12113 Returns the new TODO keyword, or nil if no state change should occur."
12114 (let* ((fulltable org-todo-key-alist)
12115 (done-keywords org-done-keywords) ;; needed for the faces.
12116 (maxlen (apply 'max (mapcar
12117 (lambda (x)
12118 (if (stringp (car x)) (string-width (car x)) 0))
12119 fulltable)))
12120 (expert nil)
12121 (fwidth (+ maxlen 3 1 3))
12122 (ncol (/ (- (window-width) 4) fwidth))
12123 tg cnt e c tbl
12124 groups ingroup)
12125 (save-excursion
12126 (save-window-excursion
12127 (if expert
12128 (set-buffer (get-buffer-create " *Org todo*"))
12129 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12130 (erase-buffer)
12131 (org-set-local 'org-done-keywords done-keywords)
12132 (setq tbl fulltable cnt 0)
12133 (while (setq e (pop tbl))
12134 (cond
12135 ((equal e '(:startgroup))
12136 (push '() groups) (setq ingroup t)
12137 (when (not (= cnt 0))
12138 (setq cnt 0)
12139 (insert "\n"))
12140 (insert "{ "))
12141 ((equal e '(:endgroup))
12142 (setq ingroup nil cnt 0)
12143 (insert "}\n"))
12144 ((equal e '(:newline))
12145 (when (not (= cnt 0))
12146 (setq cnt 0)
12147 (insert "\n")
12148 (setq e (car tbl))
12149 (while (equal (car tbl) '(:newline))
12150 (insert "\n")
12151 (setq tbl (cdr tbl)))))
12153 (setq tg (car e) c (cdr e))
12154 (if ingroup (push tg (car groups)))
12155 (setq tg (org-add-props tg nil 'face
12156 (org-get-todo-face tg)))
12157 (if (and (= cnt 0) (not ingroup)) (insert " "))
12158 (insert "[" c "] " tg (make-string
12159 (- fwidth 4 (length tg)) ?\ ))
12160 (when (= (setq cnt (1+ cnt)) ncol)
12161 (insert "\n")
12162 (if ingroup (insert " "))
12163 (setq cnt 0)))))
12164 (insert "\n")
12165 (goto-char (point-min))
12166 (if (not expert) (org-fit-window-to-buffer))
12167 (message "[a-z..]:Set [SPC]:clear")
12168 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12169 (cond
12170 ((or (= c ?\C-g)
12171 (and (= c ?q) (not (rassoc c fulltable))))
12172 (setq quit-flag t))
12173 ((= c ?\ ) nil)
12174 ((setq e (rassoc c fulltable) tg (car e))
12176 (t (setq quit-flag t)))))))
12178 (defun org-entry-is-todo-p ()
12179 (member (org-get-todo-state) org-not-done-keywords))
12181 (defun org-entry-is-done-p ()
12182 (member (org-get-todo-state) org-done-keywords))
12184 (defun org-get-todo-state ()
12185 (save-excursion
12186 (org-back-to-heading t)
12187 (and (looking-at org-todo-line-regexp)
12188 (match-end 2)
12189 (match-string 2))))
12191 (defun org-at-date-range-p (&optional inactive-ok)
12192 "Is the cursor inside a date range?"
12193 (interactive)
12194 (save-excursion
12195 (catch 'exit
12196 (let ((pos (point)))
12197 (skip-chars-backward "^[<\r\n")
12198 (skip-chars-backward "<[")
12199 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12200 (>= (match-end 0) pos)
12201 (throw 'exit t))
12202 (skip-chars-backward "^<[\r\n")
12203 (skip-chars-backward "<[")
12204 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12205 (>= (match-end 0) pos)
12206 (throw 'exit t)))
12207 nil)))
12209 (defun org-get-repeat (&optional tagline)
12210 "Check if there is a deadline/schedule with repeater in this entry."
12211 (save-match-data
12212 (save-excursion
12213 (org-back-to-heading t)
12214 (and (re-search-forward (if tagline
12215 (concat tagline "\\s-*" org-repeat-re)
12216 org-repeat-re)
12217 (org-entry-end-position) t)
12218 (match-string-no-properties 1)))))
12220 (defvar org-last-changed-timestamp)
12221 (defvar org-last-inserted-timestamp)
12222 (defvar org-log-post-message)
12223 (defvar org-log-note-purpose)
12224 (defvar org-log-note-how)
12225 (defvar org-log-note-extra)
12226 (defun org-auto-repeat-maybe (done-word)
12227 "Check if the current headline contains a repeated deadline/schedule.
12228 If yes, set TODO state back to what it was and change the base date
12229 of repeating deadline/scheduled time stamps to new date.
12230 This function is run automatically after each state change to a DONE state."
12231 ;; last-state is dynamically scoped into this function
12232 (let* ((repeat (org-get-repeat))
12233 (aa (assoc org-last-state org-todo-kwd-alist))
12234 (interpret (nth 1 aa))
12235 (head (nth 2 aa))
12236 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12237 (msg "Entry repeats: ")
12238 (org-log-done nil)
12239 (org-todo-log-states nil)
12240 re type n what ts time to-state)
12241 (when repeat
12242 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12243 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12244 org-todo-repeat-to-state))
12245 (unless (and to-state (member to-state org-todo-keywords-1))
12246 (setq to-state (if (eq interpret 'type) org-last-state head)))
12247 (org-todo to-state)
12248 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12249 (org-entry-put nil "LAST_REPEAT" (format-time-string
12250 (org-time-stamp-format t t))))
12251 (when org-log-repeat
12252 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12253 (memq 'org-add-log-note post-command-hook))
12254 ;; OK, we are already setup for some record
12255 (if (eq org-log-repeat 'note)
12256 ;; make sure we take a note, not only a time stamp
12257 (setq org-log-note-how 'note))
12258 ;; Set up for taking a record
12259 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12260 org-last-state
12261 'findpos org-log-repeat)))
12262 (org-back-to-heading t)
12263 (org-add-planning-info nil nil 'closed)
12264 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12265 org-deadline-time-regexp "\\)\\|\\("
12266 org-ts-regexp "\\)"))
12267 (while (re-search-forward
12268 re (save-excursion (outline-next-heading) (point)) t)
12269 (setq type (if (match-end 1) org-scheduled-string
12270 (if (match-end 3) org-deadline-string "Plain:"))
12271 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12272 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12273 (setq n (string-to-number (match-string 2 ts))
12274 what (match-string 3 ts))
12275 (if (equal what "w") (setq n (* n 7) what "d"))
12276 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12277 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12278 ;; Preparation, see if we need to modify the start date for the change
12279 (when (match-end 1)
12280 (setq time (save-match-data (org-time-string-to-time ts)))
12281 (cond
12282 ((equal (match-string 1 ts) ".")
12283 ;; Shift starting date to today
12284 (org-timestamp-change
12285 (- (org-today) (time-to-days time))
12286 'day))
12287 ((equal (match-string 1 ts) "+")
12288 (let ((nshiftmax 10) (nshift 0))
12289 (while (or (= nshift 0)
12290 (<= (time-to-days time)
12291 (time-to-days (current-time))))
12292 (when (= (incf nshift) nshiftmax)
12293 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12294 (error "Abort")))
12295 (org-timestamp-change n (cdr (assoc what whata)))
12296 (org-at-timestamp-p t)
12297 (setq ts (match-string 1))
12298 (setq time (save-match-data (org-time-string-to-time ts)))))
12299 (org-timestamp-change (- n) (cdr (assoc what whata)))
12300 ;; rematch, so that we have everything in place for the real shift
12301 (org-at-timestamp-p t)
12302 (setq ts (match-string 1))
12303 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12304 (org-timestamp-change n (cdr (assoc what whata)))
12305 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12306 (setq org-log-post-message msg)
12307 (message "%s" msg))))
12309 (defun org-show-todo-tree (arg)
12310 "Make a compact tree which shows all headlines marked with TODO.
12311 The tree will show the lines where the regexp matches, and all higher
12312 headlines above the match.
12313 With a \\[universal-argument] prefix, prompt for a regexp to match.
12314 With a numeric prefix N, construct a sparse tree for the Nth element
12315 of `org-todo-keywords-1'."
12316 (interactive "P")
12317 (let ((case-fold-search nil)
12318 (kwd-re
12319 (cond ((null arg) org-not-done-regexp)
12320 ((equal arg '(4))
12321 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12322 (mapcar 'list org-todo-keywords-1))))
12323 (concat "\\("
12324 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12325 "\\)\\>")))
12326 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12327 (regexp-quote (nth (1- (prefix-numeric-value arg))
12328 org-todo-keywords-1)))
12329 (t (error "Invalid prefix argument: %s" arg)))))
12330 (message "%d TODO entries found"
12331 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12333 (defun org-deadline (&optional remove time)
12334 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12335 With argument REMOVE, remove any deadline from the item.
12336 With argument TIME, set the deadline at the corresponding date. TIME
12337 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12338 (interactive "P")
12339 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12340 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12341 'region-start-level 'region))
12342 org-loop-over-headlines-in-active-region)
12343 (org-map-entries
12344 `(org-deadline ',remove ,time)
12345 org-loop-over-headlines-in-active-region
12346 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12347 (let* ((old-date (org-entry-get nil "DEADLINE"))
12348 (repeater (and old-date
12349 (string-match
12350 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12351 old-date)
12352 (match-string 1 old-date))))
12353 (if remove
12354 (progn
12355 (when (and old-date org-log-redeadline)
12356 (org-add-log-setup 'deldeadline nil old-date 'findpos
12357 org-log-redeadline))
12358 (org-remove-timestamp-with-keyword org-deadline-string)
12359 (message "Item no longer has a deadline."))
12360 (org-add-planning-info 'deadline time 'closed)
12361 (when (and old-date org-log-redeadline
12362 (not (equal old-date
12363 (substring org-last-inserted-timestamp 1 -1))))
12364 (org-add-log-setup 'redeadline nil old-date 'findpos
12365 org-log-redeadline))
12366 (when repeater
12367 (save-excursion
12368 (org-back-to-heading t)
12369 (when (re-search-forward (concat org-deadline-string " "
12370 org-last-inserted-timestamp)
12371 (save-excursion
12372 (outline-next-heading) (point)) t)
12373 (goto-char (1- (match-end 0)))
12374 (insert " " repeater)
12375 (setq org-last-inserted-timestamp
12376 (concat (substring org-last-inserted-timestamp 0 -1)
12377 " " repeater
12378 (substring org-last-inserted-timestamp -1))))))
12379 (message "Deadline on %s" org-last-inserted-timestamp)))))
12381 (defun org-schedule (&optional remove time)
12382 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12383 With argument REMOVE, remove any scheduling date from the item.
12384 With argument TIME, scheduled at the corresponding date. TIME can
12385 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12386 (interactive "P")
12387 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12388 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12389 'region-start-level 'region))
12390 org-loop-over-headlines-in-active-region)
12391 (org-map-entries
12392 `(org-schedule ',remove ,time)
12393 org-loop-over-headlines-in-active-region
12394 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12395 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12396 (repeater (and old-date
12397 (string-match
12398 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12399 old-date)
12400 (match-string 1 old-date))))
12401 (if remove
12402 (progn
12403 (when (and old-date org-log-reschedule)
12404 (org-add-log-setup 'delschedule nil old-date 'findpos
12405 org-log-reschedule))
12406 (org-remove-timestamp-with-keyword org-scheduled-string)
12407 (message "Item is no longer scheduled."))
12408 (org-add-planning-info 'scheduled time 'closed)
12409 (when (and old-date org-log-reschedule
12410 (not (equal old-date
12411 (substring org-last-inserted-timestamp 1 -1))))
12412 (org-add-log-setup 'reschedule nil old-date 'findpos
12413 org-log-reschedule))
12414 (when repeater
12415 (save-excursion
12416 (org-back-to-heading t)
12417 (when (re-search-forward (concat org-scheduled-string " "
12418 org-last-inserted-timestamp)
12419 (save-excursion
12420 (outline-next-heading) (point)) t)
12421 (goto-char (1- (match-end 0)))
12422 (insert " " repeater)
12423 (setq org-last-inserted-timestamp
12424 (concat (substring org-last-inserted-timestamp 0 -1)
12425 " " repeater
12426 (substring org-last-inserted-timestamp -1))))))
12427 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12429 (defun org-get-scheduled-time (pom &optional inherit)
12430 "Get the scheduled time as a time tuple, of a format suitable
12431 for calling org-schedule with, or if there is no scheduling,
12432 returns nil."
12433 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12434 (when time
12435 (apply 'encode-time (org-parse-time-string time)))))
12437 (defun org-get-deadline-time (pom &optional inherit)
12438 "Get the deadline as a time tuple, of a format suitable for
12439 calling org-deadline with, or if there is no scheduling, returns
12440 nil."
12441 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12442 (when time
12443 (apply 'encode-time (org-parse-time-string time)))))
12445 (defun org-remove-timestamp-with-keyword (keyword)
12446 "Remove all time stamps with KEYWORD in the current entry."
12447 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12448 beg)
12449 (save-excursion
12450 (org-back-to-heading t)
12451 (setq beg (point))
12452 (outline-next-heading)
12453 (while (re-search-backward re beg t)
12454 (replace-match "")
12455 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12456 (equal (char-before) ?\ ))
12457 (backward-delete-char 1)
12458 (if (string-match "^[ \t]*$" (buffer-substring
12459 (point-at-bol) (point-at-eol)))
12460 (delete-region (point-at-bol)
12461 (min (point-max) (1+ (point-at-eol))))))))))
12463 (defun org-add-planning-info (what &optional time &rest remove)
12464 "Insert new timestamp with keyword in the line directly after the headline.
12465 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12466 If non is given, the user is prompted for a date.
12467 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12468 be removed."
12469 (interactive)
12470 (let (org-time-was-given org-end-time-was-given ts
12471 end default-time default-input)
12473 (catch 'exit
12474 (when (and (memq what '(scheduled deadline))
12475 (or (not time)
12476 (and (stringp time)
12477 (string-match "^[-+]+[0-9]" time))))
12478 ;; Try to get a default date/time from existing timestamp
12479 (save-excursion
12480 (org-back-to-heading t)
12481 (setq end (save-excursion (outline-next-heading) (point)))
12482 (when (re-search-forward (if (eq what 'scheduled)
12483 org-scheduled-time-regexp
12484 org-deadline-time-regexp)
12485 end t)
12486 (setq ts (match-string 1)
12487 default-time
12488 (apply 'encode-time (org-parse-time-string ts))
12489 default-input (and ts (org-get-compact-tod ts))))))
12490 (when what
12491 (setq time
12492 (if (stringp time)
12493 ;; This is a string (relative or absolute), set proper date
12494 (apply 'encode-time
12495 (org-read-date-analyze
12496 time default-time (decode-time default-time)))
12497 ;; If necessary, get the time from the user
12498 (or time (org-read-date nil 'to-time nil nil
12499 default-time default-input)))))
12501 (when (and org-insert-labeled-timestamps-at-point
12502 (member what '(scheduled deadline)))
12503 (insert
12504 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12505 (org-insert-time-stamp time org-time-was-given
12506 nil nil nil (list org-end-time-was-given))
12507 (setq what nil))
12508 (save-excursion
12509 (save-restriction
12510 (let (col list elt ts buffer-invisibility-spec)
12511 (org-back-to-heading t)
12512 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12513 (goto-char (match-end 1))
12514 (setq col (current-column))
12515 (goto-char (match-end 0))
12516 (if (eobp) (insert "\n") (forward-char 1))
12517 (when (and (not what)
12518 (not (looking-at
12519 (concat "[ \t]*"
12520 org-keyword-time-not-clock-regexp))))
12521 ;; Nothing to add, nothing to remove...... :-)
12522 (throw 'exit nil))
12523 (if (and (not (looking-at org-outline-regexp))
12524 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12525 "[^\r\n]*"))
12526 (not (equal (match-string 1) org-clock-string)))
12527 (narrow-to-region (match-beginning 0) (match-end 0))
12528 (insert-before-markers "\n")
12529 (backward-char 1)
12530 (narrow-to-region (point) (point))
12531 (and org-adapt-indentation (org-indent-to-column col)))
12532 ;; Check if we have to remove something.
12533 (setq list (cons what remove))
12534 (while list
12535 (setq elt (pop list))
12536 (when (or (and (eq elt 'scheduled)
12537 (re-search-forward org-scheduled-time-regexp nil t))
12538 (and (eq elt 'deadline)
12539 (re-search-forward org-deadline-time-regexp nil t))
12540 (and (eq elt 'closed)
12541 (re-search-forward org-closed-time-regexp nil t)))
12542 (replace-match "")
12543 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12544 (and (looking-at "[ \t]+") (replace-match ""))
12545 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12546 (when what
12547 (insert
12548 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12549 (cond ((eq what 'scheduled) org-scheduled-string)
12550 ((eq what 'deadline) org-deadline-string)
12551 ((eq what 'closed) org-closed-string))
12552 " ")
12553 (setq ts (org-insert-time-stamp
12554 time
12555 (or org-time-was-given
12556 (and (eq what 'closed) org-log-done-with-time))
12557 (eq what 'closed)
12558 nil nil (list org-end-time-was-given)))
12559 (insert
12560 (if (not (or (bolp) (eq (char-before) ?\ )
12561 (memq (char-after) '(32 10))
12562 (eobp))) " " ""))
12563 (end-of-line 1))
12564 (goto-char (point-min))
12565 (widen)
12566 (if (and (looking-at "[ \t]*\n")
12567 (equal (char-before) ?\n))
12568 (delete-region (1- (point)) (point-at-eol)))
12569 ts))))))
12571 (defvar org-log-note-marker (make-marker))
12572 (defvar org-log-note-purpose nil)
12573 (defvar org-log-note-state nil)
12574 (defvar org-log-note-previous-state nil)
12575 (defvar org-log-note-how nil)
12576 (defvar org-log-note-extra nil)
12577 (defvar org-log-note-window-configuration nil)
12578 (defvar org-log-note-return-to (make-marker))
12579 (defvar org-log-note-effective-time nil
12580 "Remembered current time so that dynamically scoped
12581 `org-extend-today-until' affects tha timestamps in state change
12582 log")
12584 (defvar org-log-post-message nil
12585 "Message to be displayed after a log note has been stored.
12586 The auto-repeater uses this.")
12588 (defun org-add-note ()
12589 "Add a note to the current entry.
12590 This is done in the same way as adding a state change note."
12591 (interactive)
12592 (org-add-log-setup 'note nil nil 'findpos nil))
12594 (defvar org-property-end-re)
12595 (defun org-add-log-setup (&optional purpose state prev-state
12596 findpos how extra)
12597 "Set up the post command hook to take a note.
12598 If this is about to TODO state change, the new state is expected in STATE.
12599 When FINDPOS is non-nil, find the correct position for the note in
12600 the current entry. If not, assume that it can be inserted at point.
12601 HOW is an indicator what kind of note should be created.
12602 EXTRA is additional text that will be inserted into the notes buffer."
12603 (let* ((org-log-into-drawer (org-log-into-drawer))
12604 (drawer (cond ((stringp org-log-into-drawer)
12605 org-log-into-drawer)
12606 (org-log-into-drawer "LOGBOOK"))))
12607 (save-restriction
12608 (save-excursion
12609 (when findpos
12610 (org-back-to-heading t)
12611 (narrow-to-region (point) (save-excursion
12612 (outline-next-heading) (point)))
12613 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12614 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12615 "[^\r\n]*\\)?"))
12616 (goto-char (match-end 0))
12617 (cond
12618 (drawer
12619 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12620 nil t)
12621 (progn
12622 (goto-char (match-end 0))
12623 (or org-log-states-order-reversed
12624 (and (re-search-forward org-property-end-re nil t)
12625 (goto-char (1- (match-beginning 0))))))
12626 (insert "\n:" drawer ":\n:END:")
12627 (beginning-of-line 0)
12628 (org-indent-line)
12629 (beginning-of-line 2)
12630 (org-indent-line)
12631 (end-of-line 0)))
12632 ((and org-log-state-notes-insert-after-drawers
12633 (save-excursion
12634 (forward-line) (looking-at org-drawer-regexp)))
12635 (forward-line)
12636 (while (looking-at org-drawer-regexp)
12637 (goto-char (match-end 0))
12638 (re-search-forward org-property-end-re (point-max) t)
12639 (forward-line))
12640 (forward-line -1)))
12641 (unless org-log-states-order-reversed
12642 (and (= (char-after) ?\n) (forward-char 1))
12643 (org-skip-over-state-notes)
12644 (skip-chars-backward " \t\n\r")))
12645 (move-marker org-log-note-marker (point))
12646 (setq org-log-note-purpose purpose
12647 org-log-note-state state
12648 org-log-note-previous-state prev-state
12649 org-log-note-how how
12650 org-log-note-extra extra
12651 org-log-note-effective-time (org-current-effective-time))
12652 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12654 (defun org-skip-over-state-notes ()
12655 "Skip past the list of State notes in an entry."
12656 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12657 (when (ignore-errors (goto-char (org-in-item-p)))
12658 (let* ((struct (org-list-struct))
12659 (prevs (org-list-prevs-alist struct)))
12660 (while (looking-at "[ \t]*- State")
12661 (goto-char (or (org-list-get-next-item (point) struct prevs)
12662 (org-list-get-item-end (point) struct)))))))
12664 (defun org-add-log-note (&optional purpose)
12665 "Pop up a window for taking a note, and add this note later at point."
12666 (remove-hook 'post-command-hook 'org-add-log-note)
12667 (setq org-log-note-window-configuration (current-window-configuration))
12668 (delete-other-windows)
12669 (move-marker org-log-note-return-to (point))
12670 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12671 (goto-char org-log-note-marker)
12672 (org-switch-to-buffer-other-window "*Org Note*")
12673 (erase-buffer)
12674 (if (memq org-log-note-how '(time state))
12675 (let (current-prefix-arg) (org-store-log-note))
12676 (let ((org-inhibit-startup t)) (org-mode))
12677 (insert (format "# Insert note for %s.
12678 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12679 (cond
12680 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12681 ((eq org-log-note-purpose 'done) "closed todo item")
12682 ((eq org-log-note-purpose 'state)
12683 (format "state change from \"%s\" to \"%s\""
12684 (or org-log-note-previous-state "")
12685 (or org-log-note-state "")))
12686 ((eq org-log-note-purpose 'reschedule)
12687 "rescheduling")
12688 ((eq org-log-note-purpose 'delschedule)
12689 "no longer scheduled")
12690 ((eq org-log-note-purpose 'redeadline)
12691 "changing deadline")
12692 ((eq org-log-note-purpose 'deldeadline)
12693 "removing deadline")
12694 ((eq org-log-note-purpose 'refile)
12695 "refiling")
12696 ((eq org-log-note-purpose 'note)
12697 "this entry")
12698 (t (error "This should not happen")))))
12699 (if org-log-note-extra (insert org-log-note-extra))
12700 (org-set-local 'org-finish-function 'org-store-log-note)
12701 (run-hooks 'org-log-buffer-setup-hook)))
12703 (defvar org-note-abort nil) ; dynamically scoped
12704 (defun org-store-log-note ()
12705 "Finish taking a log note, and insert it to where it belongs."
12706 (let ((txt (buffer-string))
12707 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12708 lines ind bul)
12709 (kill-buffer (current-buffer))
12710 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12711 (setq txt (replace-match "" t t txt)))
12712 (if (string-match "\\s-+\\'" txt)
12713 (setq txt (replace-match "" t t txt)))
12714 (setq lines (org-split-string txt "\n"))
12715 (when (and note (string-match "\\S-" note))
12716 (setq note
12717 (org-replace-escapes
12718 note
12719 (list (cons "%u" (user-login-name))
12720 (cons "%U" user-full-name)
12721 (cons "%t" (format-time-string
12722 (org-time-stamp-format 'long 'inactive)
12723 org-log-note-effective-time))
12724 (cons "%T" (format-time-string
12725 (org-time-stamp-format 'long nil)
12726 org-log-note-effective-time))
12727 (cons "%d" (format-time-string
12728 (org-time-stamp-format nil 'inactive)
12729 org-log-note-effective-time))
12730 (cons "%D" (format-time-string
12731 (org-time-stamp-format nil nil)
12732 org-log-note-effective-time))
12733 (cons "%s" (if org-log-note-state
12734 (concat "\"" org-log-note-state "\"")
12735 ""))
12736 (cons "%S" (if org-log-note-previous-state
12737 (concat "\"" org-log-note-previous-state "\"")
12738 "\"\"")))))
12739 (if lines (setq note (concat note " \\\\")))
12740 (push note lines))
12741 (when (or current-prefix-arg org-note-abort)
12742 (when org-log-into-drawer
12743 (org-remove-empty-drawer-at
12744 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12745 org-log-note-marker))
12746 (setq lines nil))
12747 (when lines
12748 (with-current-buffer (marker-buffer org-log-note-marker)
12749 (save-excursion
12750 (goto-char org-log-note-marker)
12751 (move-marker org-log-note-marker nil)
12752 (end-of-line 1)
12753 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12754 (setq ind (save-excursion
12755 (if (ignore-errors (goto-char (org-in-item-p)))
12756 (let ((struct (org-list-struct)))
12757 (org-list-get-ind
12758 (org-list-get-top-point struct) struct))
12759 (skip-chars-backward " \r\t\n")
12760 (cond
12761 ((and (org-at-heading-p)
12762 org-adapt-indentation)
12763 (1+ (org-current-level)))
12764 ((org-at-heading-p) 0)
12765 (t (org-get-indentation))))))
12766 (setq bul (org-list-bullet-string "-"))
12767 (org-indent-line-to ind)
12768 (insert bul (pop lines))
12769 (let ((ind-body (+ (length bul) ind)))
12770 (while lines
12771 (insert "\n")
12772 (org-indent-line-to ind-body)
12773 (insert (pop lines))))
12774 (message "Note stored")
12775 (org-back-to-heading t)
12776 (org-cycle-hide-drawers 'children)))))
12777 (set-window-configuration org-log-note-window-configuration)
12778 (with-current-buffer (marker-buffer org-log-note-return-to)
12779 (goto-char org-log-note-return-to))
12780 (move-marker org-log-note-return-to nil)
12781 (and org-log-post-message (message "%s" org-log-post-message)))
12783 (defun org-remove-empty-drawer-at (drawer pos)
12784 "Remove an empty drawer DRAWER at position POS.
12785 POS may also be a marker."
12786 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12787 (save-excursion
12788 (save-restriction
12789 (widen)
12790 (goto-char pos)
12791 (if (org-in-regexp
12792 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12793 (replace-match ""))))))
12795 (defvar org-ts-type nil)
12796 (defun org-sparse-tree (&optional arg type)
12797 "Create a sparse tree, prompt for the details.
12798 This command can create sparse trees. You first need to select the type
12799 of match used to create the tree:
12801 t Show all TODO entries.
12802 T Show entries with a specific TODO keyword.
12803 m Show entries selected by a tags/property match.
12804 p Enter a property name and its value (both with completion on existing
12805 names/values) and show entries with that property.
12806 r Show entries matching a regular expression (`/' can be used as well).
12807 b Show deadlines and scheduled items before a date.
12808 a Show deadlines and scheduled items after a date.
12809 d Show deadlines due within `org-deadline-warning-days'.
12810 D Show deadlines and scheduled items between a date range."
12811 (interactive "P")
12812 (let (ans kwd value ts-type)
12813 (setq type (or type org-sparse-tree-default-date-type))
12814 (setq org-ts-type type)
12815 (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"
12816 (cond ((eq type 'all) "all timestamps")
12817 ((eq type 'scheduled) "only scheduled")
12818 ((eq type 'deadline) "only deadline")
12819 ((eq type 'active) "only active timestamps")
12820 ((eq type 'inactive) "only inactive timestamps")
12821 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12822 (t "scheduled/deadline")))
12823 (setq ans (read-char-exclusive))
12824 (cond
12825 ((equal ans ?c)
12826 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12827 ((equal ans ?d)
12828 (call-interactively 'org-check-deadlines))
12829 ((equal ans ?b)
12830 (call-interactively 'org-check-before-date))
12831 ((equal ans ?a)
12832 (call-interactively 'org-check-after-date))
12833 ((equal ans ?D)
12834 (call-interactively 'org-check-dates-range))
12835 ((equal ans ?t)
12836 (org-show-todo-tree nil))
12837 ((equal ans ?T)
12838 (org-show-todo-tree '(4)))
12839 ((member ans '(?T ?m))
12840 (call-interactively 'org-match-sparse-tree))
12841 ((member ans '(?p ?P))
12842 (setq kwd (org-icompleting-read "Property: "
12843 (mapcar 'list (org-buffer-property-keys))))
12844 (setq value (org-icompleting-read "Value: "
12845 (mapcar 'list (org-property-values kwd))))
12846 (unless (string-match "\\`{.*}\\'" value)
12847 (setq value (concat "\"" value "\"")))
12848 (org-match-sparse-tree arg (concat kwd "=" value)))
12849 ((member ans '(?r ?R ?/))
12850 (call-interactively 'org-occur))
12851 (t (error "No such sparse tree command \"%c\"" ans)))))
12853 (defvar org-occur-highlights nil
12854 "List of overlays used for occur matches.")
12855 (make-variable-buffer-local 'org-occur-highlights)
12856 (defvar org-occur-parameters nil
12857 "Parameters of the active org-occur calls.
12858 This is a list, each call to org-occur pushes as cons cell,
12859 containing the regular expression and the callback, onto the list.
12860 The list can contain several entries if `org-occur' has been called
12861 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12862 will only contain one set of parameters. When the highlights are
12863 removed (for example with `C-c C-c', or with the next edit (depending
12864 on `org-remove-highlights-with-change'), this variable is emptied
12865 as well.")
12866 (make-variable-buffer-local 'org-occur-parameters)
12868 (defun org-occur (regexp &optional keep-previous callback)
12869 "Make a compact tree which shows all matches of REGEXP.
12870 The tree will show the lines where the regexp matches, and all higher
12871 headlines above the match. It will also show the heading after the match,
12872 to make sure editing the matching entry is easy.
12873 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12874 call to `org-occur' will be kept, to allow stacking of calls to this
12875 command.
12876 If CALLBACK is non-nil, it is a function which is called to confirm
12877 that the match should indeed be shown."
12878 (interactive "sRegexp: \nP")
12879 (when (equal regexp "")
12880 (error "Regexp cannot be empty"))
12881 (unless keep-previous
12882 (org-remove-occur-highlights nil nil t))
12883 (push (cons regexp callback) org-occur-parameters)
12884 (let ((cnt 0))
12885 (save-excursion
12886 (goto-char (point-min))
12887 (if (or (not keep-previous) ; do not want to keep
12888 (not org-occur-highlights)) ; no previous matches
12889 ;; hide everything
12890 (org-overview))
12891 (while (re-search-forward regexp nil t)
12892 (when (or (not callback)
12893 (save-match-data (funcall callback)))
12894 (setq cnt (1+ cnt))
12895 (when org-highlight-sparse-tree-matches
12896 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12897 (org-show-context 'occur-tree))))
12898 (when org-remove-highlights-with-change
12899 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12900 nil 'local))
12901 (unless org-sparse-tree-open-archived-trees
12902 (org-hide-archived-subtrees (point-min) (point-max)))
12903 (run-hooks 'org-occur-hook)
12904 (if (org-called-interactively-p 'interactive)
12905 (message "%d match(es) for regexp %s" cnt regexp))
12906 cnt))
12908 (defun org-occur-next-match (&optional n reset)
12909 "Function for `next-error-function' to find sparse tree matches.
12910 N is the number of matches to move, when negative move backwards.
12911 RESET is entirely ignored - this function always goes back to the
12912 starting point when no match is found."
12913 (let* ((limit (if (< n 0) (point-min) (point-max)))
12914 (search-func (if (< n 0)
12915 'previous-single-char-property-change
12916 'next-single-char-property-change))
12917 (n (abs n))
12918 (pos (point))
12920 (catch 'exit
12921 (while (setq p1 (funcall search-func (point) 'org-type))
12922 (when (equal p1 limit)
12923 (goto-char pos)
12924 (error "No more matches"))
12925 (when (equal (get-char-property p1 'org-type) 'org-occur)
12926 (setq n (1- n))
12927 (when (= n 0)
12928 (goto-char p1)
12929 (throw 'exit (point))))
12930 (goto-char p1))
12931 (goto-char p1)
12932 (error "No more matches"))))
12934 (defun org-show-context (&optional key)
12935 "Make sure point and context are visible.
12936 How much context is shown depends upon the variables
12937 `org-show-hierarchy-above', `org-show-following-heading',
12938 `org-show-entry-below' and `org-show-siblings'."
12939 (let ((heading-p (org-at-heading-p t))
12940 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12941 (following-p (org-get-alist-option org-show-following-heading key))
12942 (entry-p (org-get-alist-option org-show-entry-below key))
12943 (siblings-p (org-get-alist-option org-show-siblings key)))
12944 (catch 'exit
12945 ;; Show heading or entry text
12946 (if (and heading-p (not entry-p))
12947 (org-flag-heading nil) ; only show the heading
12948 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12949 (org-show-hidden-entry))) ; show entire entry
12950 (when following-p
12951 ;; Show next sibling, or heading below text
12952 (save-excursion
12953 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12954 (org-flag-heading nil))))
12955 (when siblings-p (org-show-siblings))
12956 (when hierarchy-p
12957 ;; show all higher headings, possibly with siblings
12958 (save-excursion
12959 (while (and (condition-case nil
12960 (progn (org-up-heading-all 1) t)
12961 (error nil))
12962 (not (bobp)))
12963 (org-flag-heading nil)
12964 (when siblings-p (org-show-siblings))))))))
12966 (defvar org-reveal-start-hook nil
12967 "Hook run before revealing a location.")
12969 (defun org-reveal (&optional siblings)
12970 "Show current entry, hierarchy above it, and the following headline.
12971 This can be used to show a consistent set of context around locations
12972 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12973 not t for the search context.
12975 With optional argument SIBLINGS, on each level of the hierarchy all
12976 siblings are shown. This repairs the tree structure to what it would
12977 look like when opened with hierarchical calls to `org-cycle'.
12978 With double optional argument \\[universal-argument] \\[universal-argument], \
12979 go to the parent and show the
12980 entire tree."
12981 (interactive "P")
12982 (run-hooks 'org-reveal-start-hook)
12983 (let ((org-show-hierarchy-above t)
12984 (org-show-following-heading t)
12985 (org-show-siblings (if siblings t org-show-siblings)))
12986 (org-show-context nil))
12987 (when (equal siblings '(16))
12988 (save-excursion
12989 (when (org-up-heading-safe)
12990 (org-show-subtree)
12991 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12993 (defun org-highlight-new-match (beg end)
12994 "Highlight from BEG to END and mark the highlight is an occur headline."
12995 (let ((ov (make-overlay beg end)))
12996 (overlay-put ov 'face 'secondary-selection)
12997 (overlay-put ov 'org-type 'org-occur)
12998 (push ov org-occur-highlights)))
13000 (defun org-remove-occur-highlights (&optional beg end noremove)
13001 "Remove the occur highlights from the buffer.
13002 BEG and END are ignored. If NOREMOVE is nil, remove this function
13003 from the `before-change-functions' in the current buffer."
13004 (interactive)
13005 (unless org-inhibit-highlight-removal
13006 (mapc 'delete-overlay org-occur-highlights)
13007 (setq org-occur-highlights nil)
13008 (setq org-occur-parameters nil)
13009 (unless noremove
13010 (remove-hook 'before-change-functions
13011 'org-remove-occur-highlights 'local))))
13013 ;;;; Priorities
13015 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13016 "Regular expression matching the priority indicator.")
13018 (defvar org-remove-priority-next-time nil)
13020 (defun org-priority-up ()
13021 "Increase the priority of the current item."
13022 (interactive)
13023 (org-priority 'up))
13025 (defun org-priority-down ()
13026 "Decrease the priority of the current item."
13027 (interactive)
13028 (org-priority 'down))
13030 (defun org-priority (&optional action)
13031 "Change the priority of an item.
13032 ACTION can be `set', `up', `down', or a character."
13033 (interactive)
13034 (unless org-enable-priority-commands
13035 (error "Priority commands are disabled"))
13036 (setq action (or action 'set))
13037 (let (current new news have remove)
13038 (save-excursion
13039 (org-back-to-heading t)
13040 (if (looking-at org-priority-regexp)
13041 (setq current (string-to-char (match-string 2))
13042 have t))
13043 (cond
13044 ((eq action 'remove)
13045 (setq remove t new ?\ ))
13046 ((or (eq action 'set)
13047 (if (featurep 'xemacs) (characterp action) (integerp action)))
13048 (if (not (eq action 'set))
13049 (setq new action)
13050 (message "Priority %c-%c, SPC to remove: "
13051 org-highest-priority org-lowest-priority)
13052 (save-match-data
13053 (setq new (read-char-exclusive))))
13054 (if (and (= (upcase org-highest-priority) org-highest-priority)
13055 (= (upcase org-lowest-priority) org-lowest-priority))
13056 (setq new (upcase new)))
13057 (cond ((equal new ?\ ) (setq remove t))
13058 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13059 (error "Priority must be between `%c' and `%c'"
13060 org-highest-priority org-lowest-priority))))
13061 ((eq action 'up)
13062 (setq new (if have
13063 (1- current) ; normal cycling
13064 ;; last priority was empty
13065 (if (eq last-command this-command)
13066 org-lowest-priority ; wrap around empty to lowest
13067 ;; default
13068 (if org-priority-start-cycle-with-default
13069 org-default-priority
13070 (1- org-default-priority))))))
13071 ((eq action 'down)
13072 (setq new (if have
13073 (1+ current) ; normal cycling
13074 ;; last priority was empty
13075 (if (eq last-command this-command)
13076 org-highest-priority ; wrap around empty to highest
13077 ;; default
13078 (if org-priority-start-cycle-with-default
13079 org-default-priority
13080 (1+ org-default-priority))))))
13081 (t (error "Invalid action")))
13082 (if (or (< (upcase new) org-highest-priority)
13083 (> (upcase new) org-lowest-priority))
13084 (if (and (memq action '(up down))
13085 (not have) (not (eq last-command this-command)))
13086 ;; `new' is from default priority
13087 (error
13088 "The default can not be set, see `org-default-priority' why")
13089 ;; normal cycling: `new' is beyond highest/lowest priority
13090 ;; and is wrapped around to the empty priority
13091 (setq remove t)))
13092 (setq news (format "%c" new))
13093 (if have
13094 (if remove
13095 (replace-match "" t t nil 1)
13096 (replace-match news t t nil 2))
13097 (if remove
13098 (error "No priority cookie found in line")
13099 (let ((case-fold-search nil))
13100 (looking-at org-todo-line-regexp))
13101 (if (match-end 2)
13102 (progn
13103 (goto-char (match-end 2))
13104 (insert " [#" news "]"))
13105 (goto-char (match-beginning 3))
13106 (insert "[#" news "] "))))
13107 (org-preserve-lc (org-set-tags nil 'align)))
13108 (if remove
13109 (message "Priority removed")
13110 (message "Priority of current item set to %s" news))))
13112 (defun org-get-priority (s)
13113 "Find priority cookie and return priority."
13114 (if (functionp org-get-priority-function)
13115 (funcall org-get-priority-function)
13116 (save-match-data
13117 (if (not (string-match org-priority-regexp s))
13118 (* 1000 (- org-lowest-priority org-default-priority))
13119 (* 1000 (- org-lowest-priority
13120 (string-to-char (match-string 2 s))))))))
13122 ;;;; Tags
13124 (defvar org-agenda-archives-mode)
13125 (defvar org-map-continue-from nil
13126 "Position from where mapping should continue.
13127 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13129 (defvar org-scanner-tags nil
13130 "The current tag list while the tags scanner is running.")
13131 (defvar org-trust-scanner-tags nil
13132 "Should `org-get-tags-at' use the tags for the scanner.
13133 This is for internal dynamical scoping only.
13134 When this is non-nil, the function `org-get-tags-at' will return the value
13135 of `org-scanner-tags' instead of building the list by itself. This
13136 can lead to large speed-ups when the tags scanner is used in a file with
13137 many entries, and when the list of tags is retrieved, for example to
13138 obtain a list of properties. Building the tags list for each entry in such
13139 a file becomes an N^2 operation - but with this variable set, it scales
13140 as N.")
13142 (defun org-scan-tags (action matcher todo-only &optional start-level)
13143 "Scan headline tags with inheritance and produce output ACTION.
13145 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13146 or `agenda' to produce an entry list for an agenda view. It can also be
13147 a Lisp form or a function that should be called at each matched headline, in
13148 this case the return value is a list of all return values from these calls.
13150 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13151 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13152 only lines with a not-done TODO keyword are included in the output.
13153 This should be the same variable that was scoped into
13154 and set by `org-make-tags-matcher' when it constructed MATCHER.
13156 START-LEVEL can be a string with asterisks, reducing the scope to
13157 headlines matching this string."
13158 (require 'org-agenda)
13159 (let* ((re (concat "^"
13160 (if start-level
13161 ;; Get the correct level to match
13162 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13163 org-outline-regexp)
13164 " *\\(\\<\\("
13165 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13166 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13167 (props (list 'face 'default
13168 'done-face 'org-agenda-done
13169 'undone-face 'default
13170 'mouse-face 'highlight
13171 'org-not-done-regexp org-not-done-regexp
13172 'org-todo-regexp org-todo-regexp
13173 'org-complex-heading-regexp org-complex-heading-regexp
13174 'help-echo
13175 (format "mouse-2 or RET jump to org file %s"
13176 (abbreviate-file-name
13177 (or (buffer-file-name (buffer-base-buffer))
13178 (buffer-name (buffer-base-buffer)))))))
13179 (case-fold-search nil)
13180 (org-map-continue-from nil)
13181 lspos tags tags-list
13182 (tags-alist (list (cons 0 org-file-tags)))
13183 (llast 0) rtn rtn1 level category i txt
13184 todo marker entry priority)
13185 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13186 (setq action (list 'lambda nil action)))
13187 (save-excursion
13188 (goto-char (point-min))
13189 (when (eq action 'sparse-tree)
13190 (org-overview)
13191 (org-remove-occur-highlights))
13192 (while (re-search-forward re nil t)
13193 (setq org-map-continue-from nil)
13194 (catch :skip
13195 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13196 tags (if (match-end 4) (org-match-string-no-properties 4)))
13197 (goto-char (setq lspos (match-beginning 0)))
13198 (setq level (org-reduced-level (funcall outline-level))
13199 category (org-get-category))
13200 (setq i llast llast level)
13201 ;; remove tag lists from same and sublevels
13202 (while (>= i level)
13203 (when (setq entry (assoc i tags-alist))
13204 (setq tags-alist (delete entry tags-alist)))
13205 (setq i (1- i)))
13206 ;; add the next tags
13207 (when tags
13208 (setq tags (org-split-string tags ":")
13209 tags-alist
13210 (cons (cons level tags) tags-alist)))
13211 ;; compile tags for current headline
13212 (setq tags-list
13213 (if org-use-tag-inheritance
13214 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13215 tags)
13216 org-scanner-tags tags-list)
13217 (when org-use-tag-inheritance
13218 (setcdr (car tags-alist)
13219 (mapcar (lambda (x)
13220 (setq x (copy-sequence x))
13221 (org-add-prop-inherited x))
13222 (cdar tags-alist))))
13223 (when (and tags org-use-tag-inheritance
13224 (or (not (eq t org-use-tag-inheritance))
13225 org-tags-exclude-from-inheritance))
13226 ;; selective inheritance, remove uninherited ones
13227 (setcdr (car tags-alist)
13228 (org-remove-uninherited-tags (cdar tags-alist))))
13229 (when (and
13231 ;; eval matcher only when the todo condition is OK
13232 (and (or (not todo-only) (member todo org-not-done-keywords))
13233 (let ((case-fold-search t) (org-trust-scanner-tags t))
13234 (eval matcher)))
13236 ;; Call the skipper, but return t if it does not skip,
13237 ;; so that the `and' form continues evaluating
13238 (progn
13239 (unless (eq action 'sparse-tree) (org-agenda-skip))
13242 ;; Check if timestamps are deselecting this entry
13243 (or (not todo-only)
13244 (and (member todo org-not-done-keywords)
13245 (or (not org-agenda-tags-todo-honor-ignore-options)
13246 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13248 ;; Extra check for the archive tag
13249 ;; FIXME: Does the skipper already do this????
13251 (not (member org-archive-tag tags-list))
13252 ;; we have an archive tag, should we use this anyway?
13253 (or (not org-agenda-skip-archived-trees)
13254 (and (eq action 'agenda) org-agenda-archives-mode))))
13256 ;; select this headline
13258 (cond
13259 ((eq action 'sparse-tree)
13260 (and org-highlight-sparse-tree-matches
13261 (org-get-heading) (match-end 0)
13262 (org-highlight-new-match
13263 (match-beginning 1) (match-end 1)))
13264 (org-show-context 'tags-tree))
13265 ((eq action 'agenda)
13266 (setq txt (org-agenda-format-item
13268 (concat
13269 (if (eq org-tags-match-list-sublevels 'indented)
13270 (make-string (1- level) ?.) "")
13271 (org-get-heading))
13272 category
13273 tags-list)
13274 priority (org-get-priority txt))
13275 (goto-char lspos)
13276 (setq marker (org-agenda-new-marker))
13277 (org-add-props txt props
13278 'org-marker marker 'org-hd-marker marker 'org-category category
13279 'todo-state todo
13280 'priority priority 'type "tagsmatch")
13281 (push txt rtn))
13282 ((functionp action)
13283 (setq org-map-continue-from nil)
13284 (save-excursion
13285 (setq rtn1 (funcall action))
13286 (push rtn1 rtn)))
13287 (t (error "Invalid action")))
13289 ;; if we are to skip sublevels, jump to end of subtree
13290 (unless org-tags-match-list-sublevels
13291 (org-end-of-subtree t)
13292 (backward-char 1))))
13293 ;; Get the correct position from where to continue
13294 (if org-map-continue-from
13295 (goto-char org-map-continue-from)
13296 (and (= (point) lspos) (end-of-line 1)))))
13297 (when (and (eq action 'sparse-tree)
13298 (not org-sparse-tree-open-archived-trees))
13299 (org-hide-archived-subtrees (point-min) (point-max)))
13300 (nreverse rtn)))
13302 (defun org-remove-uninherited-tags (tags)
13303 "Remove all tags that are not inherited from the list TAGS."
13304 (cond
13305 ((eq org-use-tag-inheritance t)
13306 (if org-tags-exclude-from-inheritance
13307 (org-delete-all org-tags-exclude-from-inheritance tags)
13308 tags))
13309 ((not org-use-tag-inheritance) nil)
13310 ((stringp org-use-tag-inheritance)
13311 (delq nil (mapcar
13312 (lambda (x)
13313 (if (and (string-match org-use-tag-inheritance x)
13314 (not (member x org-tags-exclude-from-inheritance)))
13315 x nil))
13316 tags)))
13317 ((listp org-use-tag-inheritance)
13318 (delq nil (mapcar
13319 (lambda (x)
13320 (if (member x org-use-tag-inheritance) x nil))
13321 tags)))))
13323 (defun org-match-sparse-tree (&optional todo-only match)
13324 "Create a sparse tree according to tags string MATCH.
13325 MATCH can contain positive and negative selection of tags, like
13326 \"+WORK+URGENT-WITHBOSS\".
13327 If optional argument TODO-ONLY is non-nil, only select lines that are
13328 also TODO lines."
13329 (interactive "P")
13330 (org-agenda-prepare-buffers (list (current-buffer)))
13331 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13333 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13335 (defvar org-cached-props nil)
13336 (defun org-cached-entry-get (pom property)
13337 (if (or (eq t org-use-property-inheritance)
13338 (and (stringp org-use-property-inheritance)
13339 (string-match org-use-property-inheritance property))
13340 (and (listp org-use-property-inheritance)
13341 (member property org-use-property-inheritance)))
13342 ;; Caching is not possible, check it directly
13343 (org-entry-get pom property 'inherit)
13344 ;; Get all properties, so that we can do complicated checks easily
13345 (cdr (assoc property (or org-cached-props
13346 (setq org-cached-props
13347 (org-entry-properties pom)))))))
13349 (defun org-global-tags-completion-table (&optional files)
13350 "Return the list of all tags in all agenda buffer/files.
13351 Optional FILES argument is a list of files which can be used
13352 instead of the agenda files."
13353 (save-excursion
13354 (org-uniquify
13355 (delq nil
13356 (apply 'append
13357 (mapcar
13358 (lambda (file)
13359 (set-buffer (find-file-noselect file))
13360 (append (org-get-buffer-tags)
13361 (mapcar (lambda (x) (if (stringp (car-safe x))
13362 (list (car-safe x)) nil))
13363 org-tag-alist)))
13364 (if (and files (car files))
13365 files
13366 (org-agenda-files))))))))
13368 (defun org-make-tags-matcher (match)
13369 "Create the TAGS/TODO matcher form for the selection string MATCH.
13371 The variable `todo-only' is scoped dynamically into this function.
13372 It will be set to t if the matcher restricts matching to TODO entries,
13373 otherwise will not be touched.
13375 Returns a cons of the selection string MATCH and the constructed
13376 lisp form implementing the matcher. The matcher is to be evaluated
13377 at an Org entry, with point on the headline, and returns t if the
13378 entry matches the selection string MATCH. The returned lisp form
13379 references two variables with information about the entry, which
13380 must be bound around the form's evaluation: todo, the TODO keyword
13381 at the entry (or nil of none); and tags-list, the list of all tags
13382 at the entry including inherited ones. Additionally, the category
13383 of the entry (if any) must be specified as the text property
13384 'org-category on the headline.
13386 See also `org-scan-tags'.
13388 (declare (special todo-only))
13389 (unless (boundp 'todo-only)
13390 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13391 (unless match
13392 ;; Get a new match request, with completion
13393 (let ((org-last-tags-completion-table
13394 (org-global-tags-completion-table)))
13395 (setq match (org-completing-read-no-i
13396 "Match: " 'org-tags-completion-function nil nil nil
13397 'org-tags-history))))
13399 ;; Parse the string and create a lisp form
13400 (let ((match0 match)
13401 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13402 minus tag mm
13403 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13404 orterms term orlist re-p str-p level-p level-op time-p
13405 prop-p pn pv po gv rest)
13406 (if (string-match "/+" match)
13407 ;; match contains also a todo-matching request
13408 (progn
13409 (setq tagsmatch (substring match 0 (match-beginning 0))
13410 todomatch (substring match (match-end 0)))
13411 (if (string-match "^!" todomatch)
13412 (setq todo-only t todomatch (substring todomatch 1)))
13413 (if (string-match "^\\s-*$" todomatch)
13414 (setq todomatch nil)))
13415 ;; only matching tags
13416 (setq tagsmatch match todomatch nil))
13418 ;; Make the tags matcher
13419 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13420 (setq tagsmatcher t)
13421 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13422 (while (setq term (pop orterms))
13423 (while (and (equal (substring term -1) "\\") orterms)
13424 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13425 (while (string-match re term)
13426 (setq rest (substring term (match-end 0))
13427 minus (and (match-end 1)
13428 (equal (match-string 1 term) "-"))
13429 tag (save-match-data (replace-regexp-in-string
13430 "\\\\-" "-"
13431 (match-string 2 term)))
13432 re-p (equal (string-to-char tag) ?{)
13433 level-p (match-end 4)
13434 prop-p (match-end 5)
13435 mm (cond
13436 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13437 (level-p
13438 (setq level-op (org-op-to-function (match-string 3 term)))
13439 `(,level-op level ,(string-to-number
13440 (match-string 4 term))))
13441 (prop-p
13442 (setq pn (match-string 5 term)
13443 po (match-string 6 term)
13444 pv (match-string 7 term)
13445 re-p (equal (string-to-char pv) ?{)
13446 str-p (equal (string-to-char pv) ?\")
13447 time-p (save-match-data
13448 (string-match "^\"[[<].*[]>]\"$" pv))
13449 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13450 (if time-p (setq pv (org-matcher-time pv)))
13451 (setq po (org-op-to-function po (if time-p 'time str-p)))
13452 (cond
13453 ((equal pn "CATEGORY")
13454 (setq gv '(get-text-property (point) 'org-category)))
13455 ((equal pn "TODO")
13456 (setq gv 'todo))
13458 (setq gv `(org-cached-entry-get nil ,pn))))
13459 (if re-p
13460 (if (eq po 'org<>)
13461 `(not (string-match ,pv (or ,gv "")))
13462 `(string-match ,pv (or ,gv "")))
13463 (if str-p
13464 `(,po (or ,gv "") ,pv)
13465 `(,po (string-to-number (or ,gv ""))
13466 ,(string-to-number pv) ))))
13467 (t `(member ,tag tags-list)))
13468 mm (if minus (list 'not mm) mm)
13469 term rest)
13470 (push mm tagsmatcher))
13471 (push (if (> (length tagsmatcher) 1)
13472 (cons 'and tagsmatcher)
13473 (car tagsmatcher))
13474 orlist)
13475 (setq tagsmatcher nil))
13476 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13477 (setq tagsmatcher
13478 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13479 ;; Make the todo matcher
13480 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13481 (setq todomatcher t)
13482 (setq orterms (org-split-string todomatch "|") orlist nil)
13483 (while (setq term (pop orterms))
13484 (while (string-match re term)
13485 (setq minus (and (match-end 1)
13486 (equal (match-string 1 term) "-"))
13487 kwd (match-string 2 term)
13488 re-p (equal (string-to-char kwd) ?{)
13489 term (substring term (match-end 0))
13490 mm (if re-p
13491 `(string-match ,(substring kwd 1 -1) todo)
13492 (list 'equal 'todo kwd))
13493 mm (if minus (list 'not mm) mm))
13494 (push mm todomatcher))
13495 (push (if (> (length todomatcher) 1)
13496 (cons 'and todomatcher)
13497 (car todomatcher))
13498 orlist)
13499 (setq todomatcher nil))
13500 (setq todomatcher (if (> (length orlist) 1)
13501 (cons 'or orlist) (car orlist))))
13503 ;; Return the string and lisp forms of the matcher
13504 (setq matcher (if todomatcher
13505 (list 'and tagsmatcher todomatcher)
13506 tagsmatcher))
13507 (when todo-only
13508 (setq matcher (list 'and '(member todo org-not-done-keywords)
13509 matcher)))
13510 (cons match0 matcher)))
13512 (defun org-op-to-function (op &optional stringp)
13513 "Turn an operator into the appropriate function."
13514 (setq op
13515 (cond
13516 ((equal op "<" ) '(< string< org-time<))
13517 ((equal op ">" ) '(> org-string> org-time>))
13518 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13519 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13520 ((member op '("=" "==")) '(= string= org-time=))
13521 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13522 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13524 (defun org<> (a b) (not (= a b)))
13525 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13526 (defun org-string>= (a b) (not (string< a b)))
13527 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13528 (defun org-string<> (a b) (not (string= a b)))
13529 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13530 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13531 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13532 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13533 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13534 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13535 (defun org-2ft (s)
13536 "Convert S to a floating point time.
13537 If S is already a number, just return it. If it is a string, parse
13538 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13539 (cond
13540 ((numberp s) s)
13541 ((stringp s)
13542 (condition-case nil
13543 (float-time (apply 'encode-time (org-parse-time-string s)))
13544 (error 0.)))
13545 (t 0.)))
13547 (defun org-time-today ()
13548 "Time in seconds today at 0:00.
13549 Returns the float number of seconds since the beginning of the
13550 epoch to the beginning of today (00:00)."
13551 (float-time (apply 'encode-time
13552 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13554 (defun org-matcher-time (s)
13555 "Interpret a time comparison value."
13556 (save-match-data
13557 (cond
13558 ((string= s "<now>") (float-time))
13559 ((string= s "<today>") (org-time-today))
13560 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13561 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13562 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13563 (+ (org-time-today)
13564 (* (string-to-number (match-string 1 s))
13565 (cdr (assoc (match-string 2 s)
13566 '(("d" . 86400.0) ("w" . 604800.0)
13567 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13568 (t (org-2ft s)))))
13570 (defun org-match-any-p (re list)
13571 "Does re match any element of list?"
13572 (setq list (mapcar (lambda (x) (string-match re x)) list))
13573 (delq nil list))
13575 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13576 (defvar org-tags-overlay (make-overlay 1 1))
13577 (org-detach-overlay org-tags-overlay)
13579 (defun org-get-local-tags-at (&optional pos)
13580 "Get a list of tags defined in the current headline."
13581 (org-get-tags-at pos 'local))
13583 (defun org-get-local-tags ()
13584 "Get a list of tags defined in the current headline."
13585 (org-get-tags-at nil 'local))
13587 (defun org-get-tags-at (&optional pos local)
13588 "Get a list of all headline tags applicable at POS.
13589 POS defaults to point. If tags are inherited, the list contains
13590 the targets in the same sequence as the headlines appear, i.e.
13591 the tags of the current headline come last.
13592 When LOCAL is non-nil, only return tags from the current headline,
13593 ignore inherited ones."
13594 (interactive)
13595 (if (and org-trust-scanner-tags
13596 (or (not pos) (equal pos (point)))
13597 (not local))
13598 org-scanner-tags
13599 (let (tags ltags lastpos parent)
13600 (save-excursion
13601 (save-restriction
13602 (widen)
13603 (goto-char (or pos (point)))
13604 (save-match-data
13605 (catch 'done
13606 (condition-case nil
13607 (progn
13608 (org-back-to-heading t)
13609 (while (not (equal lastpos (point)))
13610 (setq lastpos (point))
13611 (when (looking-at
13612 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13613 (setq ltags (org-split-string
13614 (org-match-string-no-properties 1) ":"))
13615 (when parent
13616 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13617 (setq tags (append
13618 (if parent
13619 (org-remove-uninherited-tags ltags)
13620 ltags)
13621 tags)))
13622 (or org-use-tag-inheritance (throw 'done t))
13623 (if local (throw 'done t))
13624 (or (org-up-heading-safe) (error nil))
13625 (setq parent t)))
13626 (error nil)))))
13627 (if local
13628 tags
13629 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13631 (defun org-add-prop-inherited (s)
13632 (add-text-properties 0 (length s) '(inherited t) s)
13635 (defun org-toggle-tag (tag &optional onoff)
13636 "Toggle the tag TAG for the current line.
13637 If ONOFF is `on' or `off', don't toggle but set to this state."
13638 (let (res current)
13639 (save-excursion
13640 (org-back-to-heading t)
13641 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13642 (point-at-eol) t)
13643 (progn
13644 (setq current (match-string 1))
13645 (replace-match ""))
13646 (setq current ""))
13647 (setq current (nreverse (org-split-string current ":")))
13648 (cond
13649 ((eq onoff 'on)
13650 (setq res t)
13651 (or (member tag current) (push tag current)))
13652 ((eq onoff 'off)
13653 (or (not (member tag current)) (setq current (delete tag current))))
13654 (t (if (member tag current)
13655 (setq current (delete tag current))
13656 (setq res t)
13657 (push tag current))))
13658 (end-of-line 1)
13659 (if current
13660 (progn
13661 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13662 (org-set-tags nil t))
13663 (delete-horizontal-space))
13664 (run-hooks 'org-after-tags-change-hook))
13665 res))
13667 (defun org-align-tags-here (to-col)
13668 ;; Assumes that this is a headline
13669 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13670 (beginning-of-line 1)
13671 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13672 (< pos (match-beginning 2)))
13673 (progn
13674 (setq tags-l (- (match-end 2) (match-beginning 2)))
13675 (goto-char (match-beginning 1))
13676 (insert " ")
13677 (delete-region (point) (1+ (match-beginning 2)))
13678 (setq ncol (max (current-column)
13679 (1+ col)
13680 (if (> to-col 0)
13681 to-col
13682 (- (abs to-col) tags-l))))
13683 (setq p (point))
13684 (insert (make-string (- ncol (current-column)) ?\ ))
13685 (setq ncol (current-column))
13686 (when indent-tabs-mode (tabify p (point-at-eol)))
13687 (org-move-to-column (min ncol col) t))
13688 (goto-char pos))))
13690 (defun org-set-tags-command (&optional arg just-align)
13691 "Call the set-tags command for the current entry."
13692 (interactive "P")
13693 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13694 (org-set-tags arg just-align)
13695 (save-excursion
13696 (org-back-to-heading t)
13697 (org-set-tags arg just-align))))
13699 (defun org-set-tags-to (data)
13700 "Set the tags of the current entry to DATA, replacing the current tags.
13701 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13702 If DATA is nil or the empty string, any tags will be removed."
13703 (interactive "sTags: ")
13704 (setq data
13705 (cond
13706 ((eq data nil) "")
13707 ((equal data "") "")
13708 ((stringp data)
13709 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13710 ":"))
13711 ((listp data)
13712 (concat ":" (mapconcat 'identity data ":") ":"))))
13713 (when data
13714 (save-excursion
13715 (org-back-to-heading t)
13716 (when (looking-at org-complex-heading-regexp)
13717 (if (match-end 5)
13718 (progn
13719 (goto-char (match-beginning 5))
13720 (insert data)
13721 (delete-region (point) (point-at-eol))
13722 (org-set-tags nil 'align))
13723 (goto-char (point-at-eol))
13724 (insert " " data)
13725 (org-set-tags nil 'align)))
13726 (beginning-of-line 1)
13727 (if (looking-at ".*?\\([ \t]+\\)$")
13728 (delete-region (match-beginning 1) (match-end 1))))))
13730 (defun org-align-all-tags ()
13731 "Align the tags i all headings."
13732 (interactive)
13733 (save-excursion
13734 (or (ignore-errors (org-back-to-heading t))
13735 (outline-next-heading))
13736 (if (org-at-heading-p)
13737 (org-set-tags t)
13738 (message "No headings"))))
13740 (defvar org-indent-indentation-per-level)
13741 (defun org-set-tags (&optional arg just-align)
13742 "Set the tags for the current headline.
13743 With prefix ARG, realign all tags in headings in the current buffer."
13744 (interactive "P")
13745 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13746 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13747 'region-start-level 'region))
13748 org-loop-over-headlines-in-active-region)
13749 (org-map-entries
13750 ;; We don't use ARG and JUST-ALIGN here these args are not
13751 ;; useful when looping over headlines
13752 `(org-set-tags)
13753 org-loop-over-headlines-in-active-region
13754 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13755 (let* ((re org-outline-regexp-bol)
13756 (current (unless arg (org-get-tags-string)))
13757 (col (current-column))
13758 (org-setting-tags t)
13759 table current-tags inherited-tags ; computed below when needed
13760 tags p0 c0 c1 rpl di tc level)
13761 (if arg
13762 (save-excursion
13763 (goto-char (point-min))
13764 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13765 (while (re-search-forward re nil t)
13766 (org-set-tags nil t)
13767 (end-of-line 1)))
13768 (message "All tags realigned to column %d" org-tags-column))
13769 (if just-align
13770 (setq tags current)
13771 ;; Get a new set of tags from the user
13772 (save-excursion
13773 (setq table (append org-tag-persistent-alist
13774 (or org-tag-alist (org-get-buffer-tags))
13775 (and
13776 org-complete-tags-always-offer-all-agenda-tags
13777 (org-global-tags-completion-table
13778 (org-agenda-files))))
13779 org-last-tags-completion-table table
13780 current-tags (org-split-string current ":")
13781 inherited-tags (nreverse
13782 (nthcdr (length current-tags)
13783 (nreverse (org-get-tags-at))))
13784 tags
13785 (if (or (eq t org-use-fast-tag-selection)
13786 (and org-use-fast-tag-selection
13787 (delq nil (mapcar 'cdr table))))
13788 (org-fast-tag-selection
13789 current-tags inherited-tags table
13790 (if org-fast-tag-selection-include-todo
13791 org-todo-key-alist))
13792 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13793 (org-trim
13794 (org-icompleting-read "Tags: "
13795 'org-tags-completion-function
13796 nil nil current 'org-tags-history))))))
13797 (while (string-match "[-+&]+" tags)
13798 ;; No boolean logic, just a list
13799 (setq tags (replace-match ":" t t tags))))
13801 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13803 (if org-tags-sort-function
13804 (setq tags (mapconcat 'identity
13805 (sort (org-split-string
13806 tags (org-re "[^[:alnum:]_@#%]+"))
13807 org-tags-sort-function) ":")))
13809 (if (string-match "\\`[\t ]*\\'" tags)
13810 (setq tags "")
13811 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13812 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13814 ;; Insert new tags at the correct column
13815 (beginning-of-line 1)
13816 (setq level (or (and (looking-at org-outline-regexp)
13817 (- (match-end 0) (point) 1))
13819 (cond
13820 ((and (equal current "") (equal tags "")))
13821 ((re-search-forward
13822 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13823 (point-at-eol) t)
13824 (if (equal tags "")
13825 (setq rpl "")
13826 (goto-char (match-beginning 0))
13827 (setq c0 (current-column)
13828 ;; compute offset for the case of org-indent-mode active
13829 di (if org-indent-mode
13830 (* (1- org-indent-indentation-per-level) (1- level))
13832 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13833 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13834 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13835 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13836 (replace-match rpl t t)
13837 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13838 tags)
13839 (t (error "Tags alignment failed")))
13840 (org-move-to-column col)
13841 (unless just-align
13842 (run-hooks 'org-after-tags-change-hook))))))
13844 (defun org-change-tag-in-region (beg end tag off)
13845 "Add or remove TAG for each entry in the region.
13846 This works in the agenda, and also in an org-mode buffer."
13847 (interactive
13848 (list (region-beginning) (region-end)
13849 (let ((org-last-tags-completion-table
13850 (if (derived-mode-p 'org-mode)
13851 (org-get-buffer-tags)
13852 (org-global-tags-completion-table))))
13853 (org-icompleting-read
13854 "Tag: " 'org-tags-completion-function nil nil nil
13855 'org-tags-history))
13856 (progn
13857 (message "[s]et or [r]emove? ")
13858 (equal (read-char-exclusive) ?r))))
13859 (if (fboundp 'deactivate-mark) (deactivate-mark))
13860 (let ((agendap (equal major-mode 'org-agenda-mode))
13861 l1 l2 m buf pos newhead (cnt 0))
13862 (goto-char end)
13863 (setq l2 (1- (org-current-line)))
13864 (goto-char beg)
13865 (setq l1 (org-current-line))
13866 (loop for l from l1 to l2 do
13867 (org-goto-line l)
13868 (setq m (get-text-property (point) 'org-hd-marker))
13869 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13870 (and agendap m))
13871 (setq buf (if agendap (marker-buffer m) (current-buffer))
13872 pos (if agendap m (point)))
13873 (with-current-buffer buf
13874 (save-excursion
13875 (save-restriction
13876 (goto-char pos)
13877 (setq cnt (1+ cnt))
13878 (org-toggle-tag tag (if off 'off 'on))
13879 (setq newhead (org-get-heading)))))
13880 (and agendap (org-agenda-change-all-lines newhead m))))
13881 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13883 (defun org-tags-completion-function (string predicate &optional flag)
13884 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13885 (confirm (lambda (x) (stringp (car x)))))
13886 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13887 (setq s1 (match-string 1 string)
13888 s2 (match-string 2 string))
13889 (setq s1 "" s2 string))
13890 (cond
13891 ((eq flag nil)
13892 ;; try completion
13893 (setq rtn (try-completion s2 ctable confirm))
13894 (if (stringp rtn)
13895 (setq rtn
13896 (concat s1 s2 (substring rtn (length s2))
13897 (if (and org-add-colon-after-tag-completion
13898 (assoc rtn ctable))
13899 ":" ""))))
13900 rtn)
13901 ((eq flag t)
13902 ;; all-completions
13903 (all-completions s2 ctable confirm)
13905 ((eq flag 'lambda)
13906 ;; exact match?
13907 (assoc s2 ctable)))
13910 (defun org-fast-tag-insert (kwd tags face &optional end)
13911 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13912 (insert (format "%-12s" (concat kwd ":"))
13913 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13914 (or end "")))
13916 (defun org-fast-tag-show-exit (flag)
13917 (save-excursion
13918 (org-goto-line 3)
13919 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13920 (replace-match ""))
13921 (when flag
13922 (end-of-line 1)
13923 (org-move-to-column (- (window-width) 19) t)
13924 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13926 (defun org-set-current-tags-overlay (current prefix)
13927 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13928 (if (featurep 'xemacs)
13929 (org-overlay-display org-tags-overlay (concat prefix s)
13930 'secondary-selection)
13931 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13932 (org-overlay-display org-tags-overlay (concat prefix s)))))
13934 (defvar org-last-tag-selection-key nil)
13935 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13936 "Fast tag selection with single keys.
13937 CURRENT is the current list of tags in the headline, INHERITED is the
13938 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13939 possibly with grouping information. TODO-TABLE is a similar table with
13940 TODO keywords, should these have keys assigned to them.
13941 If the keys are nil, a-z are automatically assigned.
13942 Returns the new tags string, or nil to not change the current settings."
13943 (let* ((fulltable (append table todo-table))
13944 (maxlen (apply 'max (mapcar
13945 (lambda (x)
13946 (if (stringp (car x)) (string-width (car x)) 0))
13947 fulltable)))
13948 (buf (current-buffer))
13949 (expert (eq org-fast-tag-selection-single-key 'expert))
13950 (buffer-tags nil)
13951 (fwidth (+ maxlen 3 1 3))
13952 (ncol (/ (- (window-width) 4) fwidth))
13953 (i-face 'org-done)
13954 (c-face 'org-todo)
13955 tg cnt e c char c1 c2 ntable tbl rtn
13956 ov-start ov-end ov-prefix
13957 (exit-after-next org-fast-tag-selection-single-key)
13958 (done-keywords org-done-keywords)
13959 groups ingroup)
13960 (save-excursion
13961 (beginning-of-line 1)
13962 (if (looking-at
13963 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13964 (setq ov-start (match-beginning 1)
13965 ov-end (match-end 1)
13966 ov-prefix "")
13967 (setq ov-start (1- (point-at-eol))
13968 ov-end (1+ ov-start))
13969 (skip-chars-forward "^\n\r")
13970 (setq ov-prefix
13971 (concat
13972 (buffer-substring (1- (point)) (point))
13973 (if (> (current-column) org-tags-column)
13975 (make-string (- org-tags-column (current-column)) ?\ ))))))
13976 (move-overlay org-tags-overlay ov-start ov-end)
13977 (save-window-excursion
13978 (if expert
13979 (set-buffer (get-buffer-create " *Org tags*"))
13980 (delete-other-windows)
13981 (split-window-vertically)
13982 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13983 (erase-buffer)
13984 (org-set-local 'org-done-keywords done-keywords)
13985 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13986 (org-fast-tag-insert "Current" current c-face "\n\n")
13987 (org-fast-tag-show-exit exit-after-next)
13988 (org-set-current-tags-overlay current ov-prefix)
13989 (setq tbl fulltable char ?a cnt 0)
13990 (while (setq e (pop tbl))
13991 (cond
13992 ((equal (car e) :startgroup)
13993 (push '() groups) (setq ingroup t)
13994 (when (not (= cnt 0))
13995 (setq cnt 0)
13996 (insert "\n"))
13997 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13998 ((equal (car e) :endgroup)
13999 (setq ingroup nil cnt 0)
14000 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14001 ((equal e '(:newline))
14002 (when (not (= cnt 0))
14003 (setq cnt 0)
14004 (insert "\n")
14005 (setq e (car tbl))
14006 (while (equal (car tbl) '(:newline))
14007 (insert "\n")
14008 (setq tbl (cdr tbl)))))
14010 (setq tg (copy-sequence (car e)) c2 nil)
14011 (if (cdr e)
14012 (setq c (cdr e))
14013 ;; automatically assign a character.
14014 (setq c1 (string-to-char
14015 (downcase (substring
14016 tg (if (= (string-to-char tg) ?@) 1 0)))))
14017 (if (or (rassoc c1 ntable) (rassoc c1 table))
14018 (while (or (rassoc char ntable) (rassoc char table))
14019 (setq char (1+ char)))
14020 (setq c2 c1))
14021 (setq c (or c2 char)))
14022 (if ingroup (push tg (car groups)))
14023 (setq tg (org-add-props tg nil 'face
14024 (cond
14025 ((not (assoc tg table))
14026 (org-get-todo-face tg))
14027 ((member tg current) c-face)
14028 ((member tg inherited) i-face))))
14029 (if (and (= cnt 0) (not ingroup)) (insert " "))
14030 (insert "[" c "] " tg (make-string
14031 (- fwidth 4 (length tg)) ?\ ))
14032 (push (cons tg c) ntable)
14033 (when (= (setq cnt (1+ cnt)) ncol)
14034 (insert "\n")
14035 (if ingroup (insert " "))
14036 (setq cnt 0)))))
14037 (setq ntable (nreverse ntable))
14038 (insert "\n")
14039 (goto-char (point-min))
14040 (if (not expert) (org-fit-window-to-buffer))
14041 (setq rtn
14042 (catch 'exit
14043 (while t
14044 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14045 (if (not groups) "no " "")
14046 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14047 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14048 (setq org-last-tag-selection-key c)
14049 (cond
14050 ((= c ?\r) (throw 'exit t))
14051 ((= c ?!)
14052 (setq groups (not groups))
14053 (goto-char (point-min))
14054 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14055 ((= c ?\C-c)
14056 (if (not expert)
14057 (org-fast-tag-show-exit
14058 (setq exit-after-next (not exit-after-next)))
14059 (setq expert nil)
14060 (delete-other-windows)
14061 (set-window-buffer (split-window-vertically) " *Org tags*")
14062 (org-switch-to-buffer-other-window " *Org tags*")
14063 (org-fit-window-to-buffer)))
14064 ((or (= c ?\C-g)
14065 (and (= c ?q) (not (rassoc c ntable))))
14066 (org-detach-overlay org-tags-overlay)
14067 (setq quit-flag t))
14068 ((= c ?\ )
14069 (setq current nil)
14070 (if exit-after-next (setq exit-after-next 'now)))
14071 ((= c ?\t)
14072 (condition-case nil
14073 (setq tg (org-icompleting-read
14074 "Tag: "
14075 (or buffer-tags
14076 (with-current-buffer buf
14077 (org-get-buffer-tags)))))
14078 (quit (setq tg "")))
14079 (when (string-match "\\S-" tg)
14080 (add-to-list 'buffer-tags (list tg))
14081 (if (member tg current)
14082 (setq current (delete tg current))
14083 (push tg current)))
14084 (if exit-after-next (setq exit-after-next 'now)))
14085 ((setq e (rassoc c todo-table) tg (car e))
14086 (with-current-buffer buf
14087 (save-excursion (org-todo tg)))
14088 (if exit-after-next (setq exit-after-next 'now)))
14089 ((setq e (rassoc c ntable) tg (car e))
14090 (if (member tg current)
14091 (setq current (delete tg current))
14092 (loop for g in groups do
14093 (if (member tg g)
14094 (mapc (lambda (x)
14095 (setq current (delete x current)))
14096 g)))
14097 (push tg current))
14098 (if exit-after-next (setq exit-after-next 'now))))
14100 ;; Create a sorted list
14101 (setq current
14102 (sort current
14103 (lambda (a b)
14104 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14105 (if (eq exit-after-next 'now) (throw 'exit t))
14106 (goto-char (point-min))
14107 (beginning-of-line 2)
14108 (delete-region (point) (point-at-eol))
14109 (org-fast-tag-insert "Current" current c-face)
14110 (org-set-current-tags-overlay current ov-prefix)
14111 (while (re-search-forward
14112 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14113 (setq tg (match-string 1))
14114 (add-text-properties
14115 (match-beginning 1) (match-end 1)
14116 (list 'face
14117 (cond
14118 ((member tg current) c-face)
14119 ((member tg inherited) i-face)
14120 (t (get-text-property (match-beginning 1) 'face))))))
14121 (goto-char (point-min)))))
14122 (org-detach-overlay org-tags-overlay)
14123 (if rtn
14124 (mapconcat 'identity current ":")
14125 nil))))
14127 (defun org-get-tags-string ()
14128 "Get the TAGS string in the current headline."
14129 (unless (org-at-heading-p t)
14130 (error "Not on a heading"))
14131 (save-excursion
14132 (beginning-of-line 1)
14133 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14134 (org-match-string-no-properties 1)
14135 "")))
14137 (defun org-get-tags ()
14138 "Get the list of tags specified in the current headline."
14139 (org-split-string (org-get-tags-string) ":"))
14141 (defun org-get-buffer-tags ()
14142 "Get a table of all tags used in the buffer, for completion."
14143 (let (tags)
14144 (save-excursion
14145 (goto-char (point-min))
14146 (while (re-search-forward
14147 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14148 (when (equal (char-after (point-at-bol 0)) ?*)
14149 (mapc (lambda (x) (add-to-list 'tags x))
14150 (org-split-string (org-match-string-no-properties 1) ":")))))
14151 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14152 (mapcar 'list tags)))
14154 ;;;; The mapping API
14156 ;;;###autoload
14157 (defun org-map-entries (func &optional match scope &rest skip)
14158 "Call FUNC at each headline selected by MATCH in SCOPE.
14160 FUNC is a function or a lisp form. The function will be called without
14161 arguments, with the cursor positioned at the beginning of the headline.
14162 The return values of all calls to the function will be collected and
14163 returned as a list.
14165 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14166 does not need to preserve point. After evaluation, the cursor will be
14167 moved to the end of the line (presumably of the headline of the
14168 processed entry) and search continues from there. Under some
14169 circumstances, this may not produce the wanted results. For example,
14170 if you have removed (e.g. archived) the current (sub)tree it could
14171 mean that the next entry will be skipped entirely. In such cases, you
14172 can specify the position from where search should continue by making
14173 FUNC set the variable `org-map-continue-from' to the desired buffer
14174 position.
14176 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14177 Only headlines that are matched by this query will be considered during
14178 the iteration. When MATCH is nil or t, all headlines will be
14179 visited by the iteration.
14181 SCOPE determines the scope of this command. It can be any of:
14183 nil The current buffer, respecting the restriction if any
14184 tree The subtree started with the entry at point
14185 region The entries within the active region, if any
14186 region-start-level
14187 The entries within the active region, but only those at
14188 the same level than the first one.
14189 file The current buffer, without restriction
14190 file-with-archives
14191 The current buffer, and any archives associated with it
14192 agenda All agenda files
14193 agenda-with-archives
14194 All agenda files with any archive files associated with them
14195 \(file1 file2 ...)
14196 If this is a list, all files in the list will be scanned
14198 The remaining args are treated as settings for the skipping facilities of
14199 the scanner. The following items can be given here:
14201 archive skip trees with the archive tag.
14202 comment skip trees with the COMMENT keyword
14203 function or Emacs Lisp form:
14204 will be used as value for `org-agenda-skip-function', so whenever
14205 the function returns t, FUNC will not be called for that
14206 entry and search will continue from the point where the
14207 function leaves it.
14209 If your function needs to retrieve the tags including inherited tags
14210 at the *current* entry, you can use the value of the variable
14211 `org-scanner-tags' which will be much faster than getting the value
14212 with `org-get-tags-at'. If your function gets properties with
14213 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14214 to t around the call to `org-entry-properties' to get the same speedup.
14215 Note that if your function moves around to retrieve tags and properties at
14216 a *different* entry, you cannot use these techniques."
14217 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14218 (not (org-region-active-p)))
14219 (let* ((org-agenda-archives-mode nil) ; just to make sure
14220 (org-agenda-skip-archived-trees (memq 'archive skip))
14221 (org-agenda-skip-comment-trees (memq 'comment skip))
14222 (org-agenda-skip-function
14223 (car (org-delete-all '(comment archive) skip)))
14224 (org-tags-match-list-sublevels t)
14225 (start-level (eq scope 'region-start-level))
14226 matcher file res
14227 org-todo-keywords-for-agenda
14228 org-done-keywords-for-agenda
14229 org-todo-keyword-alist-for-agenda
14230 org-drawers-for-agenda
14231 org-tag-alist-for-agenda
14232 todo-only)
14234 (cond
14235 ((eq match t) (setq matcher t))
14236 ((eq match nil) (setq matcher t))
14237 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14239 (save-excursion
14240 (save-restriction
14241 (cond ((eq scope 'tree)
14242 (org-back-to-heading t)
14243 (org-narrow-to-subtree)
14244 (setq scope nil))
14245 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14246 (org-region-active-p))
14247 ;; If needed, set start-level to a string like "2"
14248 (when start-level
14249 (save-excursion
14250 (goto-char (region-beginning))
14251 (unless (org-at-heading-p) (outline-next-heading))
14252 (setq start-level (org-current-level))))
14253 (narrow-to-region (region-beginning)
14254 (save-excursion
14255 (goto-char (region-end))
14256 (unless (and (bolp) (org-at-heading-p))
14257 (outline-next-heading))
14258 (point)))
14259 (setq scope nil)))
14261 (if (not scope)
14262 (progn
14263 (org-agenda-prepare-buffers
14264 (list (buffer-file-name (current-buffer))))
14265 (setq res (org-scan-tags func matcher todo-only start-level)))
14266 ;; Get the right scope
14267 (cond
14268 ((and scope (listp scope) (symbolp (car scope)))
14269 (setq scope (eval scope)))
14270 ((eq scope 'agenda)
14271 (setq scope (org-agenda-files t)))
14272 ((eq scope 'agenda-with-archives)
14273 (setq scope (org-agenda-files t))
14274 (setq scope (org-add-archive-files scope)))
14275 ((eq scope 'file)
14276 (setq scope (list (buffer-file-name))))
14277 ((eq scope 'file-with-archives)
14278 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14279 (org-agenda-prepare-buffers scope)
14280 (while (setq file (pop scope))
14281 (with-current-buffer (org-find-base-buffer-visiting file)
14282 (save-excursion
14283 (save-restriction
14284 (widen)
14285 (goto-char (point-min))
14286 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14287 res)))
14289 ;;;; Properties
14291 ;;; Setting and retrieving properties
14293 (defconst org-special-properties
14294 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14295 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14296 "The special properties valid in Org-mode.
14298 These are properties that are not defined in the property drawer,
14299 but in some other way.")
14301 (defconst org-default-properties
14302 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14303 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14304 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14305 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14306 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14307 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14308 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14309 "Some properties that are used by Org-mode for various purposes.
14310 Being in this list makes sure that they are offered for completion.")
14312 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14313 "Regular expression matching the first line of a property drawer.")
14315 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14316 "Regular expression matching the last line of a property drawer.")
14318 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14319 "Regular expression matching the first line of a property drawer.")
14321 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14322 "Regular expression matching the first line of a property drawer.")
14324 (defconst org-property-drawer-re
14325 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14326 org-property-end-re "\\)\n?")
14327 "Matches an entire property drawer.")
14329 (defconst org-clock-drawer-re
14330 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14331 org-property-end-re "\\)\n?")
14332 "Matches an entire clock drawer.")
14334 (defsubst org-re-property (property)
14335 "Return a regexp matching a PROPERTY line.
14336 Match group 1 will be set to the value."
14337 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14339 (defsubst org-re-property-keyword (property)
14340 "Return a regexp matching a PROPERTY line, possibly with no
14341 value for the property."
14342 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14344 (defun org-property-action ()
14345 "Do an action on properties."
14346 (interactive)
14347 (let (c)
14348 (org-at-property-p)
14349 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14350 (setq c (read-char-exclusive))
14351 (cond
14352 ((equal c ?s)
14353 (call-interactively 'org-set-property))
14354 ((equal c ?d)
14355 (call-interactively 'org-delete-property))
14356 ((equal c ?D)
14357 (call-interactively 'org-delete-property-globally))
14358 ((equal c ?c)
14359 (call-interactively 'org-compute-property-at-point))
14360 (t (error "No such property action %c" c)))))
14362 (defun org-inc-effort ()
14363 "Increment the value of the effort property in the current entry."
14364 (interactive)
14365 (org-set-effort nil t))
14367 (defun org-set-effort (&optional value increment)
14368 "Set the effort property of the current entry.
14369 With numerical prefix arg, use the nth allowed value, 0 stands for the
14370 10th allowed value.
14372 When INCREMENT is non-nil, set the property to the next allowed value."
14373 (interactive "P")
14374 (if (equal value 0) (setq value 10))
14375 (let* ((completion-ignore-case t)
14376 (prop org-effort-property)
14377 (cur (org-entry-get nil prop))
14378 (allowed (org-property-get-allowed-values nil prop 'table))
14379 (existing (mapcar 'list (org-property-values prop)))
14381 (val (cond
14382 ((stringp value) value)
14383 ((and allowed (integerp value))
14384 (or (car (nth (1- value) allowed))
14385 (car (org-last allowed))))
14386 ((and allowed increment)
14387 (or (caadr (member (list cur) allowed))
14388 (error "Allowed effort values are not set")))
14389 (allowed
14390 (message "Select 1-9,0, [RET%s]: %s"
14391 (if cur (concat "=" cur) "")
14392 (mapconcat 'car allowed " "))
14393 (setq rpl (read-char-exclusive))
14394 (if (equal rpl ?\r)
14396 (setq rpl (- rpl ?0))
14397 (if (equal rpl 0) (setq rpl 10))
14398 (if (and (> rpl 0) (<= rpl (length allowed)))
14399 (car (nth (1- rpl) allowed))
14400 (org-completing-read "Effort: " allowed nil))))
14402 (let (org-completion-use-ido org-completion-use-iswitchb)
14403 (org-completing-read
14404 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14405 (concat "[" cur "]") "")
14406 ": ")
14407 existing nil nil "" nil cur))))))
14408 (unless (equal (org-entry-get nil prop) val)
14409 (org-entry-put nil prop val))
14410 (message "%s is now %s" prop val)))
14412 (defun org-at-property-p ()
14413 "Is cursor inside a property drawer?"
14414 (save-excursion
14415 (beginning-of-line 1)
14416 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14417 (save-match-data ;; Used by calling procedures
14418 (let ((p (point))
14419 (range (unless (org-before-first-heading-p)
14420 (org-get-property-block))))
14421 (and range (<= (car range) p) (< p (cdr range))))))))
14423 (defun org-get-property-block (&optional beg end force)
14424 "Return the (beg . end) range of the body of the property drawer.
14425 BEG and END are the beginning and end of the current subtree, or of
14426 the part before the first headline. If they are not given, they will
14427 be found. If the drawer does not exist and FORCE is non-nil, create
14428 the drawer."
14429 (catch 'exit
14430 (save-excursion
14431 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14432 (progn (org-back-to-heading t) (point))))
14433 (end (or end (and (not (outline-next-heading)) (point-max))
14434 (point))))
14435 (goto-char beg)
14436 (if (re-search-forward org-property-start-re end t)
14437 (setq beg (1+ (match-end 0)))
14438 (if force
14439 (save-excursion
14440 (org-insert-property-drawer)
14441 (setq end (progn (outline-next-heading) (point))))
14442 (throw 'exit nil))
14443 (goto-char beg)
14444 (if (re-search-forward org-property-start-re end t)
14445 (setq beg (1+ (match-end 0)))))
14446 (if (re-search-forward org-property-end-re end t)
14447 (setq end (match-beginning 0))
14448 (or force (throw 'exit nil))
14449 (goto-char beg)
14450 (setq end beg)
14451 (org-indent-line)
14452 (insert ":END:\n"))
14453 (cons beg end)))))
14455 (defun org-entry-properties (&optional pom which specific)
14456 "Get all properties of the entry at point-or-marker POM.
14457 This includes the TODO keyword, the tags, time strings for deadline,
14458 scheduled, and clocking, and any additional properties defined in the
14459 entry. The return value is an alist, keys may occur multiple times
14460 if the property key was used several times.
14461 POM may also be nil, in which case the current entry is used.
14462 If WHICH is nil or `all', get all properties. If WHICH is
14463 `special' or `standard', only get that subclass. If WHICH
14464 is a string only get exactly this property. SPECIFIC can be a string, the
14465 specific property we are interested in. Specifying it can speed
14466 things up because then unnecessary parsing is avoided."
14467 (setq which (or which 'all))
14468 (org-with-point-at pom
14469 (let ((clockstr (substring org-clock-string 0 -1))
14470 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14471 (case-fold-search nil)
14472 beg end range props sum-props key key1 value string clocksum clocksumt)
14473 (save-excursion
14474 (when (condition-case nil
14475 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14476 (error nil))
14477 (setq beg (point))
14478 (setq sum-props (get-text-property (point) 'org-summaries))
14479 (setq clocksum (get-text-property (point) :org-clock-minutes)
14480 clocksumt (get-text-property (point) :org-clock-minutes-today))
14481 (outline-next-heading)
14482 (setq end (point))
14483 (when (memq which '(all special))
14484 ;; Get the special properties, like TODO and tags
14485 (goto-char beg)
14486 (when (and (or (not specific) (string= specific "TODO"))
14487 (looking-at org-todo-line-regexp) (match-end 2))
14488 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14489 (when (and (or (not specific) (string= specific "PRIORITY"))
14490 (looking-at org-priority-regexp))
14491 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14492 (when (or (not specific) (string= specific "FILE"))
14493 (push (cons "FILE" buffer-file-name) props))
14494 (when (and (or (not specific) (string= specific "TAGS"))
14495 (setq value (org-get-tags-string))
14496 (string-match "\\S-" value))
14497 (push (cons "TAGS" value) props))
14498 (when (and (or (not specific) (string= specific "ALLTAGS"))
14499 (setq value (org-get-tags-at)))
14500 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14501 ":"))
14502 props))
14503 (when (or (not specific) (string= specific "BLOCKED"))
14504 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14505 (when (or (not specific)
14506 (member specific
14507 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14508 "TIMESTAMP" "TIMESTAMP_IA")))
14509 (catch 'match
14510 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14511 (setq key (if (match-end 1)
14512 (substring (org-match-string-no-properties 1)
14513 0 -1))
14514 string (if (equal key clockstr)
14515 (org-trim
14516 (buffer-substring-no-properties
14517 (match-beginning 3) (goto-char
14518 (point-at-eol))))
14519 (substring (org-match-string-no-properties 3)
14520 1 -1)))
14521 ;; Get the correct property name from the key. This is
14522 ;; necessary if the user has configured time keywords.
14523 (setq key1 (concat key ":"))
14524 (cond
14525 ((not key)
14526 (setq key
14527 (if (= (char-after (match-beginning 3)) ?\[)
14528 "TIMESTAMP_IA" "TIMESTAMP")))
14529 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14530 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14531 ((equal key1 org-closed-string) (setq key "CLOSED"))
14532 ((equal key1 org-clock-string) (setq key "CLOCK")))
14533 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14534 (progn
14535 (push (cons key string) props)
14536 ;; no need to search further if match is found
14537 (throw 'match t))
14538 (when (or (equal key "CLOCK") (not (assoc key props)))
14539 (push (cons key string) props)))))))
14541 (when (memq which '(all standard))
14542 ;; Get the standard properties, like :PROP: ...
14543 (setq range (org-get-property-block beg end))
14544 (when range
14545 (goto-char (car range))
14546 (while (re-search-forward
14547 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14548 (cdr range) t)
14549 (setq key (org-match-string-no-properties 1)
14550 value (org-trim (or (org-match-string-no-properties 2) "")))
14551 (unless (member key excluded)
14552 (push (cons key (or value "")) props)))))
14553 (if clocksum
14554 (push (cons "CLOCKSUM"
14555 (org-columns-number-to-string (/ (float clocksum) 60.)
14556 'add_times))
14557 props))
14558 (if clocksumt
14559 (push (cons "CLOCKSUM_T"
14560 (org-columns-number-to-string (/ (float clocksumt) 60.)
14561 'add_times))
14562 props))
14563 (unless (assoc "CATEGORY" props)
14564 (push (cons "CATEGORY" (org-get-category)) props))
14565 (append sum-props (nreverse props)))))))
14567 (defun org-entry-get (pom property &optional inherit literal-nil)
14568 "Get value of PROPERTY for entry or content at point-or-marker POM.
14569 If INHERIT is non-nil and the entry does not have the property,
14570 then also check higher levels of the hierarchy.
14571 If INHERIT is the symbol `selective', use inheritance only if the setting
14572 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14573 If the property is present but empty, the return value is the empty string.
14574 If the property is not present at all, nil is returned.
14576 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14577 do not interpret it as the list atom nil. This is used for inheritance
14578 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14579 (org-with-point-at pom
14580 (if (and inherit (if (eq inherit 'selective)
14581 (org-property-inherit-p property)
14583 (org-entry-get-with-inheritance property literal-nil)
14584 (if (member property org-special-properties)
14585 ;; We need a special property. Use `org-entry-properties' to
14586 ;; retrieve it, but specify the wanted property
14587 (cdr (assoc property (org-entry-properties nil 'special property)))
14588 (let* ((range (org-get-property-block))
14589 (props (list (or (assoc property org-file-properties)
14590 (assoc property org-global-properties)
14591 (assoc property org-global-properties-fixed))))
14592 (ap (lambda (key)
14593 (when (re-search-forward
14594 (org-re-property key) (cdr range) t)
14595 (setq props
14596 (org-update-property-plist
14598 (if (match-end 1)
14599 (org-match-string-no-properties 1) "")
14600 props)))))
14601 val)
14602 (when (and range (goto-char (car range)))
14603 (funcall ap property)
14604 (goto-char (car range))
14605 (while (funcall ap (concat property "+")))
14606 (setq val (cdr (assoc property props)))
14607 (when val (if literal-nil val (org-not-nil val)))))))))
14609 (defun org-property-or-variable-value (var &optional inherit)
14610 "Check if there is a property fixing the value of VAR.
14611 If yes, return this value. If not, return the current value of the variable."
14612 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14613 (if (and prop (stringp prop) (string-match "\\S-" prop))
14614 (read prop)
14615 (symbol-value var))))
14617 (defun org-entry-delete (pom property)
14618 "Delete the property PROPERTY from entry at point-or-marker POM."
14619 (org-with-point-at pom
14620 (if (member property org-special-properties)
14621 nil ; cannot delete these properties.
14622 (let ((range (org-get-property-block)))
14623 (if (and range
14624 (goto-char (car range))
14625 (re-search-forward
14626 (org-re-property property)
14627 (cdr range) t))
14628 (progn
14629 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14631 nil)))))
14633 ;; Multi-values properties are properties that contain multiple values
14634 ;; These values are assumed to be single words, separated by whitespace.
14635 (defun org-entry-add-to-multivalued-property (pom property value)
14636 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14637 (let* ((old (org-entry-get pom property))
14638 (values (and old (org-split-string old "[ \t]"))))
14639 (setq value (org-entry-protect-space value))
14640 (unless (member value values)
14641 (setq values (cons value values))
14642 (org-entry-put pom property
14643 (mapconcat 'identity values " ")))))
14645 (defun org-entry-remove-from-multivalued-property (pom property value)
14646 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14647 (let* ((old (org-entry-get pom property))
14648 (values (and old (org-split-string old "[ \t]"))))
14649 (setq value (org-entry-protect-space value))
14650 (when (member value values)
14651 (setq values (delete value values))
14652 (org-entry-put pom property
14653 (mapconcat 'identity values " ")))))
14655 (defun org-entry-member-in-multivalued-property (pom property value)
14656 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14657 (let* ((old (org-entry-get pom property))
14658 (values (and old (org-split-string old "[ \t]"))))
14659 (setq value (org-entry-protect-space value))
14660 (member value values)))
14662 (defun org-entry-get-multivalued-property (pom property)
14663 "Return a list of values in a multivalued property."
14664 (let* ((value (org-entry-get pom property))
14665 (values (and value (org-split-string value "[ \t]"))))
14666 (mapcar 'org-entry-restore-space values)))
14668 (defun org-entry-put-multivalued-property (pom property &rest values)
14669 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14670 VALUES should be a list of strings. Spaces will be protected."
14671 (org-entry-put pom property
14672 (mapconcat 'org-entry-protect-space values " "))
14673 (let* ((value (org-entry-get pom property))
14674 (values (and value (org-split-string value "[ \t]"))))
14675 (mapcar 'org-entry-restore-space values)))
14677 (defun org-entry-protect-space (s)
14678 "Protect spaces and newline in string S."
14679 (while (string-match " " s)
14680 (setq s (replace-match "%20" t t s)))
14681 (while (string-match "\n" s)
14682 (setq s (replace-match "%0A" t t s)))
14685 (defun org-entry-restore-space (s)
14686 "Restore spaces and newline in string S."
14687 (while (string-match "%20" s)
14688 (setq s (replace-match " " t t s)))
14689 (while (string-match "%0A" s)
14690 (setq s (replace-match "\n" t t s)))
14693 (defvar org-entry-property-inherited-from (make-marker)
14694 "Marker pointing to the entry from where a property was inherited.
14695 Each call to `org-entry-get-with-inheritance' will set this marker to the
14696 location of the entry where the inheritance search matched. If there was
14697 no match, the marker will point nowhere.
14698 Note that also `org-entry-get' calls this function, if the INHERIT flag
14699 is set.")
14701 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14702 "Get PROPERTY of entry or content at point, search higher levels if needed.
14703 The search will stop at the first ancestor which has the property defined.
14704 If the value found is \"nil\", return nil to show that the property
14705 should be considered as undefined (this is the meaning of nil here).
14706 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14707 (move-marker org-entry-property-inherited-from nil)
14708 (let (tmp)
14709 (save-excursion
14710 (save-restriction
14711 (widen)
14712 (catch 'ex
14713 (while t
14714 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14715 (or (ignore-errors (org-back-to-heading t))
14716 (goto-char (point-min)))
14717 (move-marker org-entry-property-inherited-from (point))
14718 (throw 'ex tmp))
14719 (or (ignore-errors (org-up-heading-safe))
14720 (throw 'ex nil))))))
14721 (setq tmp (or tmp
14722 (cdr (assoc property org-file-properties))
14723 (cdr (assoc property org-global-properties))
14724 (cdr (assoc property org-global-properties-fixed))))
14725 (if literal-nil tmp (org-not-nil tmp))))
14727 (defvar org-property-changed-functions nil
14728 "Hook called when the value of a property has changed.
14729 Each hook function should accept two arguments, the name of the property
14730 and the new value.")
14732 (defun org-entry-put (pom property value)
14733 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14734 (org-with-point-at pom
14735 (org-back-to-heading t)
14736 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14737 range)
14738 (cond
14739 ((equal property "TODO")
14740 (when (and (stringp value) (string-match "\\S-" value)
14741 (not (member value org-todo-keywords-1)))
14742 (error "\"%s\" is not a valid TODO state" value))
14743 (if (or (not value)
14744 (not (string-match "\\S-" value)))
14745 (setq value 'none))
14746 (org-todo value)
14747 (org-set-tags nil 'align))
14748 ((equal property "PRIORITY")
14749 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14750 (string-to-char value) ?\ ))
14751 (org-set-tags nil 'align))
14752 ((equal property "CLOCKSUM")
14753 (if (not (re-search-forward
14754 (concat org-clock-string "\\]--\\(\\[[^]]+\\]\\)") nil t))
14755 (error "Cannot find a clock log")
14756 (goto-char (- (match-end 1) 2))
14757 (cond
14758 ((eq value 'earlier) (org-timestamp-down))
14759 ((eq value 'later) (org-timestamp-up)))
14760 (org-clock-sum-current-item)))
14761 ((equal property "SCHEDULED")
14762 (if (re-search-forward org-scheduled-time-regexp end t)
14763 (cond
14764 ((eq value 'earlier) (org-timestamp-change -1 'day))
14765 ((eq value 'later) (org-timestamp-change 1 'day))
14766 (t (call-interactively 'org-schedule)))
14767 (call-interactively 'org-schedule)))
14768 ((equal property "DEADLINE")
14769 (if (re-search-forward org-deadline-time-regexp end t)
14770 (cond
14771 ((eq value 'earlier) (org-timestamp-change -1 'day))
14772 ((eq value 'later) (org-timestamp-change 1 'day))
14773 (t (call-interactively 'org-deadline)))
14774 (call-interactively 'org-deadline)))
14775 ((member property org-special-properties)
14776 (error "The %s property can not yet be set with `org-entry-put'"
14777 property))
14778 (t ; a non-special property
14779 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14780 (setq range (org-get-property-block beg end 'force))
14781 (goto-char (car range))
14782 (if (re-search-forward
14783 (org-re-property-keyword property) (cdr range) t)
14784 (progn
14785 (delete-region (match-beginning 0) (match-end 0))
14786 (goto-char (match-beginning 0)))
14787 (goto-char (cdr range))
14788 (insert "\n")
14789 (backward-char 1)
14790 (org-indent-line))
14791 (insert ":" property ":")
14792 (and value (insert " " value))
14793 (org-indent-line)))))
14794 (run-hook-with-args 'org-property-changed-functions property value)))
14796 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14797 "Get all property keys in the current buffer.
14798 With INCLUDE-SPECIALS, also list the special properties that reflect things
14799 like tags and TODO state.
14800 With INCLUDE-DEFAULTS, also include properties that has special meaning
14801 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14802 and others.
14803 With INCLUDE-COLUMNS, also include property names given in COLUMN
14804 formats in the current buffer."
14805 (let (rtn range cfmt s p)
14806 (save-excursion
14807 (save-restriction
14808 (widen)
14809 (goto-char (point-min))
14810 (while (re-search-forward org-property-start-re nil t)
14811 (setq range (org-get-property-block))
14812 (goto-char (car range))
14813 (while (re-search-forward
14814 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14815 (cdr range) t)
14816 (add-to-list 'rtn (org-match-string-no-properties 1)))
14817 (outline-next-heading))))
14819 (when include-specials
14820 (setq rtn (append org-special-properties rtn)))
14822 (when include-defaults
14823 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14824 (add-to-list 'rtn org-effort-property))
14826 (when include-columns
14827 (save-excursion
14828 (save-restriction
14829 (widen)
14830 (goto-char (point-min))
14831 (while (re-search-forward
14832 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14833 nil t)
14834 (setq cfmt (match-string 2) s 0)
14835 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14836 cfmt s)
14837 (setq s (match-end 0)
14838 p (match-string 1 cfmt))
14839 (unless (or (equal p "ITEM")
14840 (member p org-special-properties))
14841 (add-to-list 'rtn (match-string 1 cfmt))))))))
14843 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14845 (defun org-property-values (key)
14846 "Return a list of all values of property KEY in the current buffer."
14847 (save-excursion
14848 (save-restriction
14849 (widen)
14850 (goto-char (point-min))
14851 (let ((re (org-re-property key))
14852 values)
14853 (while (re-search-forward re nil t)
14854 (add-to-list 'values (org-trim (match-string 1))))
14855 (delete "" values)))))
14857 (defun org-insert-property-drawer ()
14858 "Insert a property drawer into the current entry."
14859 (org-back-to-heading t)
14860 (looking-at org-outline-regexp)
14861 (let ((indent (if org-adapt-indentation
14862 (- (match-end 0) (match-beginning 0))
14864 (beg (point))
14865 (re (concat "^[ \t]*" org-keyword-time-regexp))
14866 end hiddenp)
14867 (outline-next-heading)
14868 (setq end (point))
14869 (goto-char beg)
14870 (while (re-search-forward re end t))
14871 (setq hiddenp (outline-invisible-p))
14872 (end-of-line 1)
14873 (and (equal (char-after) ?\n) (forward-char 1))
14874 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14875 (if (member (match-string 1) '("CLOCK:" ":END:"))
14876 ;; just skip this line
14877 (beginning-of-line 2)
14878 ;; Drawer start, find the end
14879 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14880 (beginning-of-line 1)))
14881 (org-skip-over-state-notes)
14882 (skip-chars-backward " \t\n\r")
14883 (if (eq (char-before) ?*) (forward-char 1))
14884 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14885 (beginning-of-line 0)
14886 (org-indent-to-column indent)
14887 (beginning-of-line 2)
14888 (org-indent-to-column indent)
14889 (beginning-of-line 0)
14890 (if hiddenp
14891 (save-excursion
14892 (org-back-to-heading t)
14893 (hide-entry))
14894 (org-flag-drawer t))))
14896 (defun org-insert-drawer (&optional arg drawer)
14897 "Insert a drawer at point.
14899 Optional argument DRAWER, when non-nil, is a string representing
14900 drawer's name. Otherwise, the user is prompted for a name.
14902 If a region is active, insert the drawer around that region
14903 instead.
14905 Point is left between drawer's boundaries."
14906 (interactive "P")
14907 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14908 "LOGBOOK"))
14909 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14910 ;; internally by Org. They are meant to be inserted
14911 ;; automatically.
14912 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14913 ;; Remove system drawers from list. Note: For some reason,
14914 ;; `org-completing-read' ignores the predicate while
14915 ;; `completing-read' handles it fine.
14916 (drawer (if arg "PROPERTIES"
14917 (or drawer
14918 (completing-read
14919 "Drawer: " org-drawers
14920 (lambda (d) (not (member d system-drawers))))))))
14921 (cond
14922 ;; With C-u, fall back on `org-insert-property-drawer'
14923 (arg (org-insert-property-drawer))
14924 ;; With an active region, insert a drawer at point.
14925 ((not (org-region-active-p))
14926 (progn
14927 (unless (bolp) (insert "\n"))
14928 (insert (format ":%s:\n\n:END:\n" drawer))
14929 (forward-line -2)))
14930 ;; Otherwise, insert the drawer at point
14932 (let ((rbeg (region-beginning))
14933 (rend (copy-marker (region-end))))
14934 (unwind-protect
14935 (progn
14936 (goto-char rbeg)
14937 (beginning-of-line)
14938 (when (save-excursion
14939 (re-search-forward org-outline-regexp-bol rend t))
14940 (error "Drawers cannot contain headlines"))
14941 ;; Position point at the beginning of the first
14942 ;; non-blank line in region. Insert drawer's opening
14943 ;; there, then indent it.
14944 (org-skip-whitespace)
14945 (beginning-of-line)
14946 (insert ":" drawer ":\n")
14947 (forward-line -1)
14948 (indent-for-tab-command)
14949 ;; Move point to the beginning of the first blank line
14950 ;; after the last non-blank line in region. Insert
14951 ;; drawer's closing, then indent it.
14952 (goto-char rend)
14953 (skip-chars-backward " \r\t\n")
14954 (insert "\n:END:")
14955 (indent-for-tab-command)
14956 (unless (eolp) (insert "\n")))
14957 ;; Clear marker, whatever the outcome of insertion is.
14958 (set-marker rend nil)))))))
14960 (defvar org-property-set-functions-alist nil
14961 "Property set function alist.
14962 Each entry should have the following format:
14964 (PROPERTY . READ-FUNCTION)
14966 The read function will be called with the same argument as
14967 `org-completing-read'.")
14969 (defun org-set-property-function (property)
14970 "Get the function that should be used to set PROPERTY.
14971 This is computed according to `org-property-set-functions-alist'."
14972 (or (cdr (assoc property org-property-set-functions-alist))
14973 'org-completing-read))
14975 (defun org-read-property-value (property)
14976 "Read PROPERTY value from user."
14977 (let* ((completion-ignore-case t)
14978 (allowed (org-property-get-allowed-values nil property 'table))
14979 (cur (org-entry-get nil property))
14980 (prompt (concat property " value"
14981 (if (and cur (string-match "\\S-" cur))
14982 (concat " [" cur "]") "") ": "))
14983 (set-function (org-set-property-function property))
14984 (val (if allowed
14985 (funcall set-function prompt allowed nil
14986 (not (get-text-property 0 'org-unrestricted
14987 (caar allowed))))
14988 (let (org-completion-use-ido org-completion-use-iswitchb)
14989 (funcall set-function prompt
14990 (mapcar 'list (org-property-values property))
14991 nil nil "" nil cur)))))
14992 (if (equal val "")
14994 val)))
14996 (defvar org-last-set-property nil)
14997 (defun org-read-property-name ()
14998 "Read a property name."
14999 (let* ((completion-ignore-case t)
15000 (keys (org-buffer-property-keys nil t t))
15001 (default-prop (or (save-excursion
15002 (save-match-data
15003 (beginning-of-line)
15004 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15005 (null (string= (match-string 1) "END"))
15006 (match-string 1))))
15007 org-last-set-property))
15008 (property (org-icompleting-read
15009 (concat "Property"
15010 (if default-prop (concat " [" default-prop "]") "")
15011 ": ")
15012 (mapcar 'list keys)
15013 nil nil nil nil
15014 default-prop
15016 (if (member property keys)
15017 property
15018 (or (cdr (assoc (downcase property)
15019 (mapcar (lambda (x) (cons (downcase x) x))
15020 keys)))
15021 property))))
15023 (defun org-set-property (property value)
15024 "In the current entry, set PROPERTY to VALUE.
15025 When called interactively, this will prompt for a property name, offering
15026 completion on existing and default properties. And then it will prompt
15027 for a value, offering completion either on allowed values (via an inherited
15028 xxx_ALL property) or on existing values in other instances of this property
15029 in the current file."
15030 (interactive (list nil nil))
15031 (let* ((property (or property (org-read-property-name)))
15032 (value (or value (org-read-property-value property)))
15033 (fn (cdr (assoc property org-properties-postprocess-alist))))
15034 (setq org-last-set-property property)
15035 ;; Possibly postprocess the inserted value:
15036 (when fn (setq value (funcall fn value)))
15037 (unless (equal (org-entry-get nil property) value)
15038 (org-entry-put nil property value))))
15040 (defun org-delete-property (property)
15041 "In the current entry, delete PROPERTY."
15042 (interactive
15043 (let* ((completion-ignore-case t)
15044 (prop (org-icompleting-read "Property: "
15045 (org-entry-properties nil 'standard))))
15046 (list prop)))
15047 (message "Property %s %s" property
15048 (if (org-entry-delete nil property)
15049 "deleted"
15050 "was not present in the entry")))
15052 (defun org-delete-property-globally (property)
15053 "Remove PROPERTY globally, from all entries."
15054 (interactive
15055 (let* ((completion-ignore-case t)
15056 (prop (org-icompleting-read
15057 "Globally remove property: "
15058 (mapcar 'list (org-buffer-property-keys)))))
15059 (list prop)))
15060 (save-excursion
15061 (save-restriction
15062 (widen)
15063 (goto-char (point-min))
15064 (let ((cnt 0))
15065 (while (re-search-forward
15066 (org-re-property property)
15067 nil t)
15068 (setq cnt (1+ cnt))
15069 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15070 (message "Property \"%s\" removed from %d entries" property cnt)))))
15072 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15074 (defun org-compute-property-at-point ()
15075 "Compute the property at point.
15076 This looks for an enclosing column format, extracts the operator and
15077 then applies it to the property in the column format's scope."
15078 (interactive)
15079 (unless (org-at-property-p)
15080 (error "Not at a property"))
15081 (let ((prop (org-match-string-no-properties 2)))
15082 (org-columns-get-format-and-top-level)
15083 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15084 (error "No operator defined for property %s" prop))
15085 (org-columns-compute prop)))
15087 (defvar org-property-allowed-value-functions nil
15088 "Hook for functions supplying allowed values for a specific property.
15089 The functions must take a single argument, the name of the property, and
15090 return a flat list of allowed values. If \":ETC\" is one of
15091 the values, this means that these values are intended as defaults for
15092 completion, but that other values should be allowed too.
15093 The functions must return nil if they are not responsible for this
15094 property.")
15096 (defun org-property-get-allowed-values (pom property &optional table)
15097 "Get allowed values for the property PROPERTY.
15098 When TABLE is non-nil, return an alist that can directly be used for
15099 completion."
15100 (let (vals)
15101 (cond
15102 ((equal property "TODO")
15103 (setq vals (org-with-point-at pom
15104 (append org-todo-keywords-1 '("")))))
15105 ((equal property "PRIORITY")
15106 (let ((n org-lowest-priority))
15107 (while (>= n org-highest-priority)
15108 (push (char-to-string n) vals)
15109 (setq n (1- n)))))
15110 ((member property org-special-properties))
15111 ((setq vals (run-hook-with-args-until-success
15112 'org-property-allowed-value-functions property)))
15114 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15115 (when (and vals (string-match "\\S-" vals))
15116 (setq vals (car (read-from-string (concat "(" vals ")"))))
15117 (setq vals (mapcar (lambda (x)
15118 (cond ((stringp x) x)
15119 ((numberp x) (number-to-string x))
15120 ((symbolp x) (symbol-name x))
15121 (t "???")))
15122 vals)))))
15123 (when (member ":ETC" vals)
15124 (setq vals (remove ":ETC" vals))
15125 (org-add-props (car vals) '(org-unrestricted t)))
15126 (if table (mapcar 'list vals) vals)))
15128 (defun org-property-previous-allowed-value (&optional previous)
15129 "Switch to the next allowed value for this property."
15130 (interactive)
15131 (org-property-next-allowed-value t))
15133 (defun org-property-next-allowed-value (&optional previous)
15134 "Switch to the next allowed value for this property."
15135 (interactive)
15136 (unless (org-at-property-p)
15137 (error "Not at a property"))
15138 (let* ((key (match-string 2))
15139 (value (match-string 3))
15140 (allowed (or (org-property-get-allowed-values (point) key)
15141 (and (member value '("[ ]" "[-]" "[X]"))
15142 '("[ ]" "[X]"))))
15143 nval)
15144 (unless allowed
15145 (error "Allowed values for this property have not been defined"))
15146 (if previous (setq allowed (reverse allowed)))
15147 (if (member value allowed)
15148 (setq nval (car (cdr (member value allowed)))))
15149 (setq nval (or nval (car allowed)))
15150 (if (equal nval value)
15151 (error "Only one allowed value for this property"))
15152 (org-at-property-p)
15153 (replace-match (concat " :" key ": " nval) t t)
15154 (org-indent-line)
15155 (beginning-of-line 1)
15156 (skip-chars-forward " \t")
15157 (run-hook-with-args 'org-property-changed-functions key nval)))
15159 (defun org-find-olp (path &optional this-buffer)
15160 "Return a marker pointing to the entry at outline path OLP.
15161 If anything goes wrong, throw an error.
15162 You can wrap this call to catch the error like this:
15164 (condition-case msg
15165 (org-mobile-locate-entry (match-string 4))
15166 (error (nth 1 msg)))
15168 The return value will then be either a string with the error message,
15169 or a marker if everything is OK.
15171 If THIS-BUFFER is set, the outline path does not contain a file,
15172 only headings."
15173 (let* ((file (if this-buffer buffer-file-name (pop path)))
15174 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15175 (level 1)
15176 (lmin 1)
15177 (lmax 1)
15178 limit re end found pos heading cnt flevel)
15179 (unless buffer (error "File not found :%s" file))
15180 (with-current-buffer buffer
15181 (save-excursion
15182 (save-restriction
15183 (widen)
15184 (setq limit (point-max))
15185 (goto-char (point-min))
15186 (while (setq heading (pop path))
15187 (setq re (format org-complex-heading-regexp-format
15188 (regexp-quote heading)))
15189 (setq cnt 0 pos (point))
15190 (while (re-search-forward re end t)
15191 (setq level (- (match-end 1) (match-beginning 1)))
15192 (if (and (>= level lmin) (<= level lmax))
15193 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15194 (when (= cnt 0) (error "Heading not found on level %d: %s"
15195 lmax heading))
15196 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15197 lmax heading))
15198 (goto-char found)
15199 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15200 (setq end (save-excursion (org-end-of-subtree t t))))
15201 (when (org-at-heading-p)
15202 (move-marker (make-marker) (point))))))))
15204 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15205 "Find node HEADING in BUFFER.
15206 Return a marker to the heading if it was found, or nil if not.
15207 If POS-ONLY is set, return just the position instead of a marker.
15209 The heading text must match exact, but it may have a TODO keyword,
15210 a priority cookie and tags in the standard locations."
15211 (with-current-buffer (or buffer (current-buffer))
15212 (save-excursion
15213 (save-restriction
15214 (widen)
15215 (goto-char (point-min))
15216 (let (case-fold-search)
15217 (if (re-search-forward
15218 (format org-complex-heading-regexp-format
15219 (regexp-quote heading)) nil t)
15220 (if pos-only
15221 (match-beginning 0)
15222 (move-marker (make-marker) (match-beginning 0)))))))))
15224 (defun org-find-exact-heading-in-directory (heading &optional dir)
15225 "Find Org node headline HEADING in all .org files in directory DIR.
15226 When the target headline is found, return a marker to this location."
15227 (let ((files (directory-files (or dir default-directory)
15228 nil "\\`[^.#].*\\.org\\'"))
15229 file visiting m buffer)
15230 (catch 'found
15231 (while (setq file (pop files))
15232 (message "trying %s" file)
15233 (setq visiting (org-find-base-buffer-visiting file))
15234 (setq buffer (or visiting (find-file-noselect file)))
15235 (setq m (org-find-exact-headline-in-buffer
15236 heading buffer))
15237 (when (and (not m) (not visiting)) (kill-buffer buffer))
15238 (and m (throw 'found m))))))
15240 (defun org-find-entry-with-id (ident)
15241 "Locate the entry that contains the ID property with exact value IDENT.
15242 IDENT can be a string, a symbol or a number, this function will search for
15243 the string representation of it.
15244 Return the position where this entry starts, or nil if there is no such entry."
15245 (interactive "sID: ")
15246 (let ((id (cond
15247 ((stringp ident) ident)
15248 ((symbol-name ident) (symbol-name ident))
15249 ((numberp ident) (number-to-string ident))
15250 (t (error "IDENT %s must be a string, symbol or number" ident))))
15251 (case-fold-search nil))
15252 (save-excursion
15253 (save-restriction
15254 (widen)
15255 (goto-char (point-min))
15256 (when (re-search-forward
15257 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15258 nil t)
15259 (org-back-to-heading t)
15260 (point))))))
15262 ;;;; Timestamps
15264 (defvar org-last-changed-timestamp nil)
15265 (defvar org-last-inserted-timestamp nil
15266 "The last time stamp inserted with `org-insert-time-stamp'.")
15267 (defvar org-time-was-given) ; dynamically scoped parameter
15268 (defvar org-end-time-was-given) ; dynamically scoped parameter
15269 (defvar org-ts-what) ; dynamically scoped parameter
15271 (defun org-time-stamp (arg &optional inactive)
15272 "Prompt for a date/time and insert a time stamp.
15273 If the user specifies a time like HH:MM or if this command is
15274 called with at least one prefix argument, the time stamp contains
15275 the date and the time. Otherwise, only the date is be included.
15277 All parts of a date not specified by the user is filled in from
15278 the current date/time. So if you just press return without
15279 typing anything, the time stamp will represent the current
15280 date/time.
15282 If there is already a timestamp at the cursor, it will be
15283 modified.
15285 With two universal prefix arguments, insert an active timestamp
15286 with the current time without prompting the user."
15287 (interactive "P")
15288 (let* ((ts nil)
15289 (default-time
15290 ;; Default time is either today, or, when entering a range,
15291 ;; the range start.
15292 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15293 (save-excursion
15294 (re-search-backward
15295 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15296 (- (point) 20) t)))
15297 (apply 'encode-time (org-parse-time-string (match-string 1)))
15298 (current-time)))
15299 (default-input (and ts (org-get-compact-tod ts)))
15300 (repeater (save-excursion
15301 (save-match-data
15302 (beginning-of-line)
15303 (when (re-search-forward
15304 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15305 (save-excursion (progn (end-of-line) (point))) t)
15306 (match-string 0)))))
15307 org-time-was-given org-end-time-was-given time)
15308 (cond
15309 ((and (org-at-timestamp-p t)
15310 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15311 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15312 (insert "--")
15313 (setq time (let ((this-command this-command))
15314 (org-read-date arg 'totime nil nil
15315 default-time default-input inactive)))
15316 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15317 ((org-at-timestamp-p t)
15318 (setq time (let ((this-command this-command))
15319 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15320 (when (org-at-timestamp-p t) ; just to get the match data
15321 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15322 (replace-match "")
15323 (setq org-last-changed-timestamp
15324 (org-insert-time-stamp
15325 time (or org-time-was-given arg)
15326 inactive nil nil (list org-end-time-was-given)))
15327 (when repeater (goto-char (1- (point))) (insert " " repeater)
15328 (setq org-last-changed-timestamp
15329 (concat (substring org-last-inserted-timestamp 0 -1)
15330 " " repeater ">"))))
15331 (message "Timestamp updated"))
15332 ((equal arg '(16))
15333 (org-insert-time-stamp (current-time) t))
15335 (setq time (let ((this-command this-command))
15336 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15337 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15338 nil nil (list org-end-time-was-given))))))
15340 ;; FIXME: can we use this for something else, like computing time differences?
15341 (defun org-get-compact-tod (s)
15342 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15343 (let* ((t1 (match-string 1 s))
15344 (h1 (string-to-number (match-string 2 s)))
15345 (m1 (string-to-number (match-string 3 s)))
15346 (t2 (and (match-end 4) (match-string 5 s)))
15347 (h2 (and t2 (string-to-number (match-string 6 s))))
15348 (m2 (and t2 (string-to-number (match-string 7 s))))
15349 dh dm)
15350 (if (not t2)
15352 (setq dh (- h2 h1) dm (- m2 m1))
15353 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15354 (concat t1 "+" (number-to-string dh)
15355 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15357 (defun org-time-stamp-inactive (&optional arg)
15358 "Insert an inactive time stamp.
15359 An inactive time stamp is enclosed in square brackets instead of angle
15360 brackets. It is inactive in the sense that it does not trigger agenda entries,
15361 does not link to the calendar and cannot be changed with the S-cursor keys.
15362 So these are more for recording a certain time/date."
15363 (interactive "P")
15364 (org-time-stamp arg 'inactive))
15366 (defvar org-date-ovl (make-overlay 1 1))
15367 (overlay-put org-date-ovl 'face 'org-date-selected)
15368 (org-detach-overlay org-date-ovl)
15370 (defvar org-ans1) ; dynamically scoped parameter
15371 (defvar org-ans2) ; dynamically scoped parameter
15373 (defvar org-plain-time-of-day-regexp) ; defined below
15375 (defvar org-overriding-default-time nil) ; dynamically scoped
15376 (defvar org-read-date-overlay nil)
15377 (defvar org-dcst nil) ; dynamically scoped
15378 (defvar org-read-date-history nil)
15379 (defvar org-read-date-final-answer nil)
15380 (defvar org-read-date-analyze-futurep nil)
15381 (defvar org-read-date-analyze-forced-year nil)
15382 (defvar org-read-date-inactive)
15384 (defun org-read-date (&optional org-with-time to-time from-string prompt
15385 default-time default-input inactive)
15386 "Read a date, possibly a time, and make things smooth for the user.
15387 The prompt will suggest to enter an ISO date, but you can also enter anything
15388 which will at least partially be understood by `parse-time-string'.
15389 Unrecognized parts of the date will default to the current day, month, year,
15390 hour and minute. If this command is called to replace a timestamp at point,
15391 or to enter the second timestamp of a range, the default time is taken
15392 from the existing stamp. Furthermore, the command prefers the future,
15393 so if you are giving a date where the year is not given, and the day-month
15394 combination is already past in the current year, it will assume you
15395 mean next year. For details, see the manual. A few examples:
15397 3-2-5 --> 2003-02-05
15398 feb 15 --> currentyear-02-15
15399 2/15 --> currentyear-02-15
15400 sep 12 9 --> 2009-09-12
15401 12:45 --> today 12:45
15402 22 sept 0:34 --> currentyear-09-22 0:34
15403 12 --> currentyear-currentmonth-12
15404 Fri --> nearest Friday (today or later)
15405 etc.
15407 Furthermore you can specify a relative date by giving, as the *first* thing
15408 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15409 change in days weeks, months, years.
15410 With a single plus or minus, the date is relative to today. With a double
15411 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15412 +4d --> four days from today
15413 +4 --> same as above
15414 +2w --> two weeks from today
15415 ++5 --> five days from default date
15417 The function understands only English month and weekday abbreviations.
15419 While prompting, a calendar is popped up - you can also select the
15420 date with the mouse (button 1). The calendar shows a period of three
15421 months. To scroll it to other months, use the keys `>' and `<'.
15422 If you don't like the calendar, turn it off with
15423 \(setq org-read-date-popup-calendar nil)
15425 With optional argument TO-TIME, the date will immediately be converted
15426 to an internal time.
15427 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15428 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15429 still enter a time, and this function will inform the calling routine
15430 about this change. The calling routine may then choose to change the
15431 format used to insert the time stamp into the buffer to include the time.
15432 With optional argument FROM-STRING, read from this string instead from
15433 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15434 the time/date that is used for everything that is not specified by the
15435 user."
15436 (require 'parse-time)
15437 (let* ((org-time-stamp-rounding-minutes
15438 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15439 (org-dcst org-display-custom-times)
15440 (ct (org-current-time))
15441 (org-def (or org-overriding-default-time default-time ct))
15442 (org-defdecode (decode-time org-def))
15443 (dummy (progn
15444 (when (< (nth 2 org-defdecode) org-extend-today-until)
15445 (setcar (nthcdr 2 org-defdecode) -1)
15446 (setcar (nthcdr 1 org-defdecode) 59)
15447 (setq org-def (apply 'encode-time org-defdecode)
15448 org-defdecode (decode-time org-def)))))
15449 (calendar-frame-setup nil)
15450 (calendar-setup nil)
15451 (calendar-move-hook nil)
15452 (calendar-view-diary-initially-flag nil)
15453 (calendar-view-holidays-initially-flag nil)
15454 (timestr (format-time-string
15455 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15456 (prompt (concat (if prompt (concat prompt " ") "")
15457 (format "Date+time [%s]: " timestr)))
15458 ans (org-ans0 "") org-ans1 org-ans2 final)
15460 (cond
15461 (from-string (setq ans from-string))
15462 (org-read-date-popup-calendar
15463 (save-excursion
15464 (save-window-excursion
15465 (calendar)
15466 (org-eval-in-calendar '(setq cursor-type nil) t)
15467 (unwind-protect
15468 (progn
15469 (calendar-forward-day (- (time-to-days org-def)
15470 (calendar-absolute-from-gregorian
15471 (calendar-current-date))))
15472 (org-eval-in-calendar nil t)
15473 (let* ((old-map (current-local-map))
15474 (map (copy-keymap calendar-mode-map))
15475 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15476 (org-defkey map (kbd "RET") 'org-calendar-select)
15477 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15478 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15479 (org-defkey minibuffer-local-map [(meta shift left)]
15480 (lambda () (interactive)
15481 (org-eval-in-calendar '(calendar-backward-month 1))))
15482 (org-defkey minibuffer-local-map [(meta shift right)]
15483 (lambda () (interactive)
15484 (org-eval-in-calendar '(calendar-forward-month 1))))
15485 (org-defkey minibuffer-local-map [(meta shift up)]
15486 (lambda () (interactive)
15487 (org-eval-in-calendar '(calendar-backward-year 1))))
15488 (org-defkey minibuffer-local-map [(meta shift down)]
15489 (lambda () (interactive)
15490 (org-eval-in-calendar '(calendar-forward-year 1))))
15491 (org-defkey minibuffer-local-map [?\e (shift left)]
15492 (lambda () (interactive)
15493 (org-eval-in-calendar '(calendar-backward-month 1))))
15494 (org-defkey minibuffer-local-map [?\e (shift right)]
15495 (lambda () (interactive)
15496 (org-eval-in-calendar '(calendar-forward-month 1))))
15497 (org-defkey minibuffer-local-map [?\e (shift up)]
15498 (lambda () (interactive)
15499 (org-eval-in-calendar '(calendar-backward-year 1))))
15500 (org-defkey minibuffer-local-map [?\e (shift down)]
15501 (lambda () (interactive)
15502 (org-eval-in-calendar '(calendar-forward-year 1))))
15503 (org-defkey minibuffer-local-map [(shift up)]
15504 (lambda () (interactive)
15505 (org-eval-in-calendar '(calendar-backward-week 1))))
15506 (org-defkey minibuffer-local-map [(shift down)]
15507 (lambda () (interactive)
15508 (org-eval-in-calendar '(calendar-forward-week 1))))
15509 (org-defkey minibuffer-local-map [(shift left)]
15510 (lambda () (interactive)
15511 (org-eval-in-calendar '(calendar-backward-day 1))))
15512 (org-defkey minibuffer-local-map [(shift right)]
15513 (lambda () (interactive)
15514 (org-eval-in-calendar '(calendar-forward-day 1))))
15515 (org-defkey minibuffer-local-map ">"
15516 (lambda () (interactive)
15517 (org-eval-in-calendar '(scroll-calendar-left 1))))
15518 (org-defkey minibuffer-local-map "<"
15519 (lambda () (interactive)
15520 (org-eval-in-calendar '(scroll-calendar-right 1))))
15521 (org-defkey minibuffer-local-map "\C-v"
15522 (lambda () (interactive)
15523 (org-eval-in-calendar
15524 '(calendar-scroll-left-three-months 1))))
15525 (org-defkey minibuffer-local-map "\M-v"
15526 (lambda () (interactive)
15527 (org-eval-in-calendar
15528 '(calendar-scroll-right-three-months 1))))
15529 (run-hooks 'org-read-date-minibuffer-setup-hook)
15530 (unwind-protect
15531 (progn
15532 (use-local-map map)
15533 (setq org-read-date-inactive inactive)
15534 (add-hook 'post-command-hook 'org-read-date-display)
15535 (setq org-ans0 (read-string prompt default-input
15536 'org-read-date-history nil))
15537 ;; org-ans0: from prompt
15538 ;; org-ans1: from mouse click
15539 ;; org-ans2: from calendar motion
15540 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15541 (remove-hook 'post-command-hook 'org-read-date-display)
15542 (use-local-map old-map)
15543 (when org-read-date-overlay
15544 (delete-overlay org-read-date-overlay)
15545 (setq org-read-date-overlay nil)))))
15546 (bury-buffer "*Calendar*")))))
15548 (t ; Naked prompt only
15549 (unwind-protect
15550 (setq ans (read-string prompt default-input
15551 'org-read-date-history timestr))
15552 (when org-read-date-overlay
15553 (delete-overlay org-read-date-overlay)
15554 (setq org-read-date-overlay nil)))))
15556 (setq final (org-read-date-analyze ans org-def org-defdecode))
15558 (when org-read-date-analyze-forced-year
15559 (message "Year was forced into %s"
15560 (if org-read-date-force-compatible-dates
15561 "compatible range (1970-2037)"
15562 "range representable on this machine"))
15563 (ding))
15565 ;; One round trip to get rid of 34th of August and stuff like that....
15566 (setq final (decode-time (apply 'encode-time final)))
15568 (setq org-read-date-final-answer ans)
15570 (if to-time
15571 (apply 'encode-time final)
15572 (if (and (boundp 'org-time-was-given) org-time-was-given)
15573 (format "%04d-%02d-%02d %02d:%02d"
15574 (nth 5 final) (nth 4 final) (nth 3 final)
15575 (nth 2 final) (nth 1 final))
15576 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15578 (defvar org-def)
15579 (defvar org-defdecode)
15580 (defvar org-with-time)
15581 (defun org-read-date-display ()
15582 "Display the current date prompt interpretation in the minibuffer."
15583 (when org-read-date-display-live
15584 (when org-read-date-overlay
15585 (delete-overlay org-read-date-overlay))
15586 (when (minibufferp (current-buffer))
15587 (save-excursion
15588 (end-of-line 1)
15589 (while (not (equal (buffer-substring
15590 (max (point-min) (- (point) 4)) (point))
15591 " "))
15592 (insert " ")))
15593 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15594 " " (or org-ans1 org-ans2)))
15595 (org-end-time-was-given nil)
15596 (f (org-read-date-analyze ans org-def org-defdecode))
15597 (fmts (if org-dcst
15598 org-time-stamp-custom-formats
15599 org-time-stamp-formats))
15600 (fmt (if (or org-with-time
15601 (and (boundp 'org-time-was-given) org-time-was-given))
15602 (cdr fmts)
15603 (car fmts)))
15604 (txt (format-time-string fmt (apply 'encode-time f)))
15605 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15606 (txt (concat "=> " txt)))
15607 (when (and org-end-time-was-given
15608 (string-match org-plain-time-of-day-regexp txt))
15609 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15610 org-end-time-was-given
15611 (substring txt (match-end 0)))))
15612 (when org-read-date-analyze-futurep
15613 (setq txt (concat txt " (=>F)")))
15614 (setq org-read-date-overlay
15615 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15616 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15618 (defun org-read-date-analyze (ans org-def org-defdecode)
15619 "Analyze the combined answer of the date prompt."
15620 ;; FIXME: cleanup and comment
15621 (let ((nowdecode (decode-time (current-time)))
15622 delta deltan deltaw deltadef year month day
15623 hour minute second wday pm h2 m2 tl wday1
15624 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15625 (setq org-read-date-analyze-futurep nil
15626 org-read-date-analyze-forced-year nil)
15627 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15628 (setq ans "+0"))
15630 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15631 (unless (save-match-data (string-match org-plain-time-of-day-regexp ans))
15632 (setq ans (replace-match "" t t ans)
15633 deltan (car delta)
15634 deltaw (nth 1 delta)
15635 deltadef (nth 2 delta))))
15637 ;; Check if there is an iso week date in there
15638 ;; If yes, store the info and postpone interpreting it until the rest
15639 ;; of the parsing is done
15640 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15641 (setq iso-year (if (match-end 1)
15642 (org-small-year-to-year
15643 (string-to-number (match-string 1 ans))))
15644 iso-weekday (if (match-end 3)
15645 (string-to-number (match-string 3 ans)))
15646 iso-week (string-to-number (match-string 2 ans)))
15647 (setq ans (replace-match "" t t ans)))
15649 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15650 (when (string-match
15651 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15652 (setq year (if (match-end 2)
15653 (string-to-number (match-string 2 ans))
15654 (progn (setq kill-year t)
15655 (string-to-number (format-time-string "%Y"))))
15656 month (string-to-number (match-string 3 ans))
15657 day (string-to-number (match-string 4 ans)))
15658 (if (< year 100) (setq year (+ 2000 year)))
15659 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15660 t nil ans)))
15662 ;; Help matching dotted european dates
15663 (when (string-match
15664 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15665 (setq year (if (match-end 3)
15666 (string-to-number (match-string 3 ans))
15667 (progn (setq kill-year t)
15668 (string-to-number (format-time-string "%Y"))))
15669 day (string-to-number (match-string 1 ans))
15670 month (string-to-number (match-string 2 ans))
15671 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15672 t nil ans)))
15674 ;; Help matching american dates, like 5/30 or 5/30/7
15675 (when (string-match
15676 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15677 (setq year (if (match-end 4)
15678 (string-to-number (match-string 4 ans))
15679 (progn (setq kill-year t)
15680 (string-to-number (format-time-string "%Y"))))
15681 month (string-to-number (match-string 1 ans))
15682 day (string-to-number (match-string 2 ans)))
15683 (if (< year 100) (setq year (+ 2000 year)))
15684 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15685 t nil ans)))
15686 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15687 ;; If there is a time with am/pm, and *no* time without it, we convert
15688 ;; so that matching will be successful.
15689 (loop for i from 1 to 2 do ; twice, for end time as well
15690 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15691 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15692 (setq hour (string-to-number (match-string 1 ans))
15693 minute (if (match-end 3)
15694 (string-to-number (match-string 3 ans))
15696 pm (equal ?p
15697 (string-to-char (downcase (match-string 4 ans)))))
15698 (if (and (= hour 12) (not pm))
15699 (setq hour 0)
15700 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15701 (setq ans (replace-match (format "%02d:%02d" hour minute)
15702 t t ans))))
15704 ;; Check if a time range is given as a duration
15705 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15706 (setq hour (string-to-number (match-string 1 ans))
15707 h2 (+ hour (string-to-number (match-string 3 ans)))
15708 minute (string-to-number (match-string 2 ans))
15709 m2 (+ minute (if (match-end 5) (string-to-number
15710 (match-string 5 ans))0)))
15711 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15712 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15713 t t ans)))
15715 ;; Check if there is a time range
15716 (when (boundp 'org-end-time-was-given)
15717 (setq org-time-was-given nil)
15718 (when (and (string-match org-plain-time-of-day-regexp ans)
15719 (match-end 8))
15720 (setq org-end-time-was-given (match-string 8 ans))
15721 (setq ans (concat (substring ans 0 (match-beginning 7))
15722 (substring ans (match-end 7))))))
15724 (setq tl (parse-time-string ans)
15725 day (or (nth 3 tl) (nth 3 org-defdecode))
15726 month (or (nth 4 tl)
15727 (if (and org-read-date-prefer-future
15728 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15729 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15730 (nth 4 org-defdecode)))
15731 year (or (and (not kill-year) (nth 5 tl))
15732 (if (and org-read-date-prefer-future
15733 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15734 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15735 (nth 5 org-defdecode)))
15736 hour (or (nth 2 tl) (nth 2 org-defdecode))
15737 minute (or (nth 1 tl) (nth 1 org-defdecode))
15738 second (or (nth 0 tl) 0)
15739 wday (nth 6 tl))
15741 (when (and (eq org-read-date-prefer-future 'time)
15742 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15743 (equal day (nth 3 nowdecode))
15744 (equal month (nth 4 nowdecode))
15745 (equal year (nth 5 nowdecode))
15746 (nth 2 tl)
15747 (or (< (nth 2 tl) (nth 2 nowdecode))
15748 (and (= (nth 2 tl) (nth 2 nowdecode))
15749 (nth 1 tl)
15750 (< (nth 1 tl) (nth 1 nowdecode)))))
15751 (setq day (1+ day)
15752 futurep t))
15754 ;; Special date definitions below
15755 (cond
15756 (iso-week
15757 ;; There was an iso week
15758 (require 'cal-iso)
15759 (setq futurep nil)
15760 (setq year (or iso-year year)
15761 day (or iso-weekday wday 1)
15762 wday nil ; to make sure that the trigger below does not match
15763 iso-date (calendar-gregorian-from-absolute
15764 (calendar-absolute-from-iso
15765 (list iso-week day year))))
15766 ; FIXME: Should we also push ISO weeks into the future?
15767 ; (when (and org-read-date-prefer-future
15768 ; (not iso-year)
15769 ; (< (calendar-absolute-from-gregorian iso-date)
15770 ; (time-to-days (current-time))))
15771 ; (setq year (1+ year)
15772 ; iso-date (calendar-gregorian-from-absolute
15773 ; (calendar-absolute-from-iso
15774 ; (list iso-week day year)))))
15775 (setq month (car iso-date)
15776 year (nth 2 iso-date)
15777 day (nth 1 iso-date)))
15778 (deltan
15779 (setq futurep nil)
15780 (unless deltadef
15781 (let ((now (decode-time (current-time))))
15782 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15783 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15784 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15785 ((equal deltaw "m") (setq month (+ month deltan)))
15786 ((equal deltaw "y") (setq year (+ year deltan)))))
15787 ((and wday (not (nth 3 tl)))
15788 ;; Weekday was given, but no day, so pick that day in the week
15789 ;; on or after the derived date.
15790 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15791 (unless (equal wday wday1)
15792 (setq day (+ day (% (- wday wday1 -7) 7))))))
15793 (if (and (boundp 'org-time-was-given)
15794 (nth 2 tl))
15795 (setq org-time-was-given t))
15796 (if (< year 100) (setq year (+ 2000 year)))
15797 ;; Check of the date is representable
15798 (if org-read-date-force-compatible-dates
15799 (progn
15800 (if (< year 1970)
15801 (setq year 1970 org-read-date-analyze-forced-year t))
15802 (if (> year 2037)
15803 (setq year 2037 org-read-date-analyze-forced-year t)))
15804 (condition-case nil
15805 (ignore (encode-time second minute hour day month year))
15806 (error
15807 (setq year (nth 5 org-defdecode))
15808 (setq org-read-date-analyze-forced-year t))))
15809 (setq org-read-date-analyze-futurep futurep)
15810 (list second minute hour day month year)))
15812 (defvar parse-time-weekdays)
15813 (defun org-read-date-get-relative (s today default)
15814 "Check string S for special relative date string.
15815 TODAY and DEFAULT are internal times, for today and for a default.
15816 Return shift list (N what def-flag)
15817 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15818 N is the number of WHATs to shift.
15819 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15820 the DEFAULT date rather than TODAY."
15821 (require 'parse-time)
15822 (when (and
15823 (string-match
15824 (concat
15825 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15826 "\\([0-9]+\\)?"
15827 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15828 "\\([ \t]\\|$\\)") s)
15829 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15830 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15831 (string-to-char (substring (match-string 1 s) -1))
15832 ?+))
15833 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15834 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15835 (what (if (match-end 3) (match-string 3 s) "d"))
15836 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15837 (date (if rel default today))
15838 (wday (nth 6 (decode-time date)))
15839 delta)
15840 (if wday1
15841 (progn
15842 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15843 (if (= dir ?-) (setq delta (- delta 7)))
15844 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15845 (list delta "d" rel))
15846 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15848 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15849 "Turn a user-specified date into the internal representation.
15850 The internal representation needed by the calendar is (month day year).
15851 This is a wrapper to handle the brain-dead convention in calendar that
15852 user function argument order change dependent on argument order."
15853 (if (boundp 'calendar-date-style)
15854 (cond
15855 ((eq calendar-date-style 'american)
15856 (list arg1 arg2 arg3))
15857 ((eq calendar-date-style 'european)
15858 (list arg2 arg1 arg3))
15859 ((eq calendar-date-style 'iso)
15860 (list arg2 arg3 arg1)))
15861 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15862 (if (org-bound-and-true-p european-calendar-style)
15863 (list arg2 arg1 arg3)
15864 (list arg1 arg2 arg3)))))
15866 (defun org-eval-in-calendar (form &optional keepdate)
15867 "Eval FORM in the calendar window and return to current window.
15868 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15869 otherwise stick to the current value of `org-ans2'."
15870 (let ((sf (selected-frame))
15871 (sw (selected-window)))
15872 (select-window (get-buffer-window "*Calendar*" t))
15873 (eval form)
15874 (when (and (not keepdate) (calendar-cursor-to-date))
15875 (let* ((date (calendar-cursor-to-date))
15876 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15877 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15878 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15879 (select-window sw)
15880 (org-select-frame-set-input-focus sf)))
15882 (defun org-calendar-select ()
15883 "Return to `org-read-date' with the date currently selected.
15884 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15885 (interactive)
15886 (when (calendar-cursor-to-date)
15887 (let* ((date (calendar-cursor-to-date))
15888 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15889 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15890 (if (active-minibuffer-window) (exit-minibuffer))))
15892 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15893 "Insert a date stamp for the date given by the internal TIME.
15894 WITH-HM means use the stamp format that includes the time of the day.
15895 INACTIVE means use square brackets instead of angular ones, so that the
15896 stamp will not contribute to the agenda.
15897 PRE and POST are optional strings to be inserted before and after the
15898 stamp.
15899 The command returns the inserted time stamp."
15900 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15901 stamp)
15902 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15903 (insert-before-markers (or pre ""))
15904 (when (listp extra)
15905 (setq extra (car extra))
15906 (if (and (stringp extra)
15907 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15908 (setq extra (format "-%02d:%02d"
15909 (string-to-number (match-string 1 extra))
15910 (string-to-number (match-string 2 extra))))
15911 (setq extra nil)))
15912 (when extra
15913 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15914 (insert-before-markers (setq stamp (format-time-string fmt time)))
15915 (insert-before-markers (or post ""))
15916 (setq org-last-inserted-timestamp stamp)))
15918 (defun org-toggle-time-stamp-overlays ()
15919 "Toggle the use of custom time stamp formats."
15920 (interactive)
15921 (setq org-display-custom-times (not org-display-custom-times))
15922 (unless org-display-custom-times
15923 (let ((p (point-min)) (bmp (buffer-modified-p)))
15924 (while (setq p (next-single-property-change p 'display))
15925 (if (and (get-text-property p 'display)
15926 (eq (get-text-property p 'face) 'org-date))
15927 (remove-text-properties
15928 p (setq p (next-single-property-change p 'display))
15929 '(display t))))
15930 (set-buffer-modified-p bmp)))
15931 (if (featurep 'xemacs)
15932 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15933 (org-restart-font-lock)
15934 (setq org-table-may-need-update t)
15935 (if org-display-custom-times
15936 (message "Time stamps are overlaid with custom format")
15937 (message "Time stamp overlays removed")))
15939 (defun org-display-custom-time (beg end)
15940 "Overlay modified time stamp format over timestamp between BEG and END."
15941 (let* ((ts (buffer-substring beg end))
15942 t1 w1 with-hm tf time str w2 (off 0))
15943 (save-match-data
15944 (setq t1 (org-parse-time-string ts t))
15945 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15946 (setq off (- (match-end 0) (match-beginning 0)))))
15947 (setq end (- end off))
15948 (setq w1 (- end beg)
15949 with-hm (and (nth 1 t1) (nth 2 t1))
15950 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15951 time (org-fix-decoded-time t1)
15952 str (org-add-props
15953 (format-time-string
15954 (substring tf 1 -1) (apply 'encode-time time))
15955 nil 'mouse-face 'highlight)
15956 w2 (length str))
15957 (if (not (= w2 w1))
15958 (add-text-properties (1+ beg) (+ 2 beg)
15959 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15960 (if (featurep 'xemacs)
15961 (progn
15962 (put-text-property beg end 'invisible t)
15963 (put-text-property beg end 'end-glyph (make-glyph str)))
15964 (put-text-property beg end 'display str))))
15966 (defun org-translate-time (string)
15967 "Translate all timestamps in STRING to custom format.
15968 But do this only if the variable `org-display-custom-times' is set."
15969 (when org-display-custom-times
15970 (save-match-data
15971 (let* ((start 0)
15972 (re org-ts-regexp-both)
15973 t1 with-hm inactive tf time str beg end)
15974 (while (setq start (string-match re string start))
15975 (setq beg (match-beginning 0)
15976 end (match-end 0)
15977 t1 (save-match-data
15978 (org-parse-time-string (substring string beg end) t))
15979 with-hm (and (nth 1 t1) (nth 2 t1))
15980 inactive (equal (substring string beg (1+ beg)) "[")
15981 tf (funcall (if with-hm 'cdr 'car)
15982 org-time-stamp-custom-formats)
15983 time (org-fix-decoded-time t1)
15984 str (format-time-string
15985 (concat
15986 (if inactive "[" "<") (substring tf 1 -1)
15987 (if inactive "]" ">"))
15988 (apply 'encode-time time))
15989 string (replace-match str t t string)
15990 start (+ start (length str)))))))
15991 string)
15993 (defun org-fix-decoded-time (time)
15994 "Set 0 instead of nil for the first 6 elements of time.
15995 Don't touch the rest."
15996 (let ((n 0))
15997 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15999 (defun org-days-to-time (timestamp-string)
16000 "Difference between TIMESTAMP-STRING and now in days."
16001 (- (time-to-days (org-time-string-to-time timestamp-string))
16002 (time-to-days (current-time))))
16004 (defun org-deadline-close (timestamp-string &optional ndays)
16005 "Is the time in TIMESTAMP-STRING close to the current date?"
16006 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16007 (and (< (org-days-to-time timestamp-string) ndays)
16008 (not (org-entry-is-done-p))))
16010 (defun org-get-wdays (ts)
16011 "Get the deadline lead time appropriate for timestring TS."
16012 (cond
16013 ((<= org-deadline-warning-days 0)
16014 ;; 0 or negative, enforce this value no matter what
16015 (- org-deadline-warning-days))
16016 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16017 ;; lead time is specified.
16018 (floor (* (string-to-number (match-string 1 ts))
16019 (cdr (assoc (match-string 2 ts)
16020 '(("d" . 1) ("w" . 7)
16021 ("m" . 30.4) ("y" . 365.25)))))))
16022 ;; go for the default.
16023 (t org-deadline-warning-days)))
16025 (defun org-calendar-select-mouse (ev)
16026 "Return to `org-read-date' with the date currently selected.
16027 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16028 (interactive "e")
16029 (mouse-set-point ev)
16030 (when (calendar-cursor-to-date)
16031 (let* ((date (calendar-cursor-to-date))
16032 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16033 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16034 (if (active-minibuffer-window) (exit-minibuffer))))
16036 (defun org-check-deadlines (ndays)
16037 "Check if there are any deadlines due or past due.
16038 A deadline is considered due if it happens within `org-deadline-warning-days'
16039 days from today's date. If the deadline appears in an entry marked DONE,
16040 it is not shown. The prefix arg NDAYS can be used to test that many
16041 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16042 (interactive "P")
16043 (let* ((org-warn-days
16044 (cond
16045 ((equal ndays '(4)) 100000)
16046 (ndays (prefix-numeric-value ndays))
16047 (t (abs org-deadline-warning-days))))
16048 (case-fold-search nil)
16049 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16050 (callback
16051 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16053 (message "%d deadlines past-due or due within %d days"
16054 (org-occur regexp nil callback)
16055 org-warn-days)))
16057 (defsubst org-re-timestamp (type)
16058 "Return a regexp for timestamp TYPE.
16059 Allowed values for TYPE are:
16061 all: all timestamps
16062 active: only active timestamps (<...>)
16063 inactive: only inactive timestamps ([...])
16064 scheduled: only scheduled timestamps
16065 deadline: only deadline timestamps
16067 When TYPE is nil, fall back on returning a regexp that matches
16068 both scheduled and deadline timestamps."
16069 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16070 ((eq type 'active) org-ts-regexp)
16071 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16072 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16073 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16074 ((eq type 'scheduled-or-deadline)
16075 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16077 (defun org-check-before-date (date)
16078 "Check if there are deadlines or scheduled entries before DATE."
16079 (interactive (list (org-read-date)))
16080 (let ((case-fold-search nil)
16081 (regexp (org-re-timestamp org-ts-type))
16082 (callback
16083 (lambda () (time-less-p
16084 (org-time-string-to-time (match-string 1))
16085 (org-time-string-to-time date)))))
16086 (message "%d entries before %s"
16087 (org-occur regexp nil callback) date)))
16089 (defun org-check-after-date (date)
16090 "Check if there are deadlines or scheduled entries after DATE."
16091 (interactive (list (org-read-date)))
16092 (let ((case-fold-search nil)
16093 (regexp (org-re-timestamp org-ts-type))
16094 (callback
16095 (lambda () (not
16096 (time-less-p
16097 (org-time-string-to-time (match-string 1))
16098 (org-time-string-to-time date))))))
16099 (message "%d entries after %s"
16100 (org-occur regexp nil callback) date)))
16102 (defun org-check-dates-range (start-date end-date)
16103 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16104 (interactive (list (org-read-date nil nil nil "Range starts")
16105 (org-read-date nil nil nil "Range end")))
16106 (let ((case-fold-search nil)
16107 (regexp (org-re-timestamp org-ts-type))
16108 (callback
16109 (lambda ()
16110 (let ((match (match-string 1)))
16111 (and
16112 (not (time-less-p
16113 (org-time-string-to-time match)
16114 (org-time-string-to-time start-date)))
16115 (time-less-p
16116 (org-time-string-to-time match)
16117 (org-time-string-to-time end-date)))))))
16118 (message "%d entries between %s and %s"
16119 (org-occur regexp nil callback) start-date end-date)))
16121 (defun org-evaluate-time-range (&optional to-buffer)
16122 "Evaluate a time range by computing the difference between start and end.
16123 Normally the result is just printed in the echo area, but with prefix arg
16124 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16125 If the time range is actually in a table, the result is inserted into the
16126 next column.
16127 For time difference computation, a year is assumed to be exactly 365
16128 days in order to avoid rounding problems."
16129 (interactive "P")
16131 (org-clock-update-time-maybe)
16132 (save-excursion
16133 (unless (org-at-date-range-p t)
16134 (goto-char (point-at-bol))
16135 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16136 (if (not (org-at-date-range-p t))
16137 (error "Not at a time-stamp range, and none found in current line")))
16138 (let* ((ts1 (match-string 1))
16139 (ts2 (match-string 2))
16140 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16141 (match-end (match-end 0))
16142 (time1 (org-time-string-to-time ts1))
16143 (time2 (org-time-string-to-time ts2))
16144 (t1 (org-float-time time1))
16145 (t2 (org-float-time time2))
16146 (diff (abs (- t2 t1)))
16147 (negative (< (- t2 t1) 0))
16148 ;; (ys (floor (* 365 24 60 60)))
16149 (ds (* 24 60 60))
16150 (hs (* 60 60))
16151 (fy "%dy %dd %02d:%02d")
16152 (fy1 "%dy %dd")
16153 (fd "%dd %02d:%02d")
16154 (fd1 "%dd")
16155 (fh "%02d:%02d")
16156 y d h m align)
16157 (if havetime
16158 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16160 d (floor (/ diff ds)) diff (mod diff ds)
16161 h (floor (/ diff hs)) diff (mod diff hs)
16162 m (floor (/ diff 60)))
16163 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16165 d (floor (+ (/ diff ds) 0.5))
16166 h 0 m 0))
16167 (if (not to-buffer)
16168 (message "%s" (org-make-tdiff-string y d h m))
16169 (if (org-at-table-p)
16170 (progn
16171 (goto-char match-end)
16172 (setq align t)
16173 (and (looking-at " *|") (goto-char (match-end 0))))
16174 (goto-char match-end))
16175 (if (looking-at
16176 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16177 (replace-match ""))
16178 (if negative (insert " -"))
16179 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16180 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16181 (insert " " (format fh h m))))
16182 (if align (org-table-align))
16183 (message "Time difference inserted")))))
16185 (defun org-make-tdiff-string (y d h m)
16186 (let ((fmt "")
16187 (l nil))
16188 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16189 l (push y l)))
16190 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16191 l (push d l)))
16192 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16193 l (push h l)))
16194 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16195 l (push m l)))
16196 (apply 'format fmt (nreverse l))))
16198 (defun org-time-string-to-time (s &optional buffer pos)
16199 (condition-case errdata
16200 (apply 'encode-time (org-parse-time-string s))
16201 (error (error "Bad timestamp `%s'%s\nError was: %s"
16202 s (if (not (and buffer pos))
16204 (format " at %d in buffer `%s'" pos buffer))
16205 (cdr errdata)))))
16207 (defun org-time-string-to-seconds (s)
16208 (org-float-time (org-time-string-to-time s)))
16210 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16211 "Convert a time stamp to an absolute day number.
16212 If there is a specifier for a cyclic time stamp, get the closest date to
16213 DAYNR.
16214 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16215 The variable date is bound by the calendar when this is called."
16216 (cond
16217 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16218 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16219 daynr
16220 (+ daynr 1000)))
16221 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16222 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16223 (time-to-days (current-time))) (match-string 0 s)
16224 prefer show-all))
16225 (t (time-to-days
16226 (condition-case errdata
16227 (apply 'encode-time (org-parse-time-string s))
16228 (error (error "Bad timestamp `%s'%s\nError was: %s"
16229 s (if (not (and buffer pos))
16231 (format " at %d in buffer `%s'" pos buffer))
16232 (cdr errdata))))))))
16234 (defun org-days-to-iso-week (days)
16235 "Return the iso week number."
16236 (require 'cal-iso)
16237 (car (calendar-iso-from-absolute days)))
16239 (defun org-small-year-to-year (year)
16240 "Convert 2-digit years into 4-digit years.
16241 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16242 The year 2000 cannot be abbreviated. Any year larger than 99
16243 is returned unchanged."
16244 (if (< year 38)
16245 (setq year (+ 2000 year))
16246 (if (< year 100)
16247 (setq year (+ 1900 year))))
16248 year)
16250 (defun org-time-from-absolute (d)
16251 "Return the time corresponding to date D.
16252 D may be an absolute day number, or a calendar-type list (month day year)."
16253 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16254 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16256 (defun org-calendar-holiday ()
16257 "List of holidays, for Diary display in Org-mode."
16258 (require 'holidays)
16259 (let ((hl (funcall
16260 (if (fboundp 'calendar-check-holidays)
16261 'calendar-check-holidays 'check-calendar-holidays) date)))
16262 (if hl (mapconcat 'identity hl "; "))))
16264 (defun org-diary-sexp-entry (sexp entry date)
16265 "Process a SEXP diary ENTRY for DATE."
16266 (require 'diary-lib)
16267 (let ((result (if calendar-debug-sexp
16268 (let ((stack-trace-on-error t))
16269 (eval (car (read-from-string sexp))))
16270 (condition-case nil
16271 (eval (car (read-from-string sexp)))
16272 (error
16273 (beep)
16274 (message "Bad sexp at line %d in %s: %s"
16275 (org-current-line)
16276 (buffer-file-name) sexp)
16277 (sleep-for 2))))))
16278 (cond ((stringp result) (split-string result "; "))
16279 ((and (consp result)
16280 (not (consp (cdr result)))
16281 (stringp (cdr result))) (cdr result))
16282 ((and (consp result)
16283 (stringp (car result))) result)
16284 (result entry))))
16286 (defun org-diary-to-ical-string (frombuf)
16287 "Get iCalendar entries from diary entries in buffer FROMBUF.
16288 This uses the icalendar.el library."
16289 (let* ((tmpdir (if (featurep 'xemacs)
16290 (temp-directory)
16291 temporary-file-directory))
16292 (tmpfile (make-temp-name
16293 (expand-file-name "orgics" tmpdir)))
16294 buf rtn b e)
16295 (with-current-buffer frombuf
16296 (icalendar-export-region (point-min) (point-max) tmpfile)
16297 (setq buf (find-buffer-visiting tmpfile))
16298 (set-buffer buf)
16299 (goto-char (point-min))
16300 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16301 (setq b (match-beginning 0)))
16302 (goto-char (point-max))
16303 (if (re-search-backward "^END:VEVENT" nil t)
16304 (setq e (match-end 0)))
16305 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16306 (kill-buffer buf)
16307 (delete-file tmpfile)
16308 rtn))
16310 (defun org-closest-date (start current change prefer show-all)
16311 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16312 When PREFER is `past', return a date that is either CURRENT or past.
16313 When PREFER is `future', return a date that is either CURRENT or future.
16314 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16315 ;; Make the proper lists from the dates
16316 (catch 'exit
16317 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16318 dn dw sday cday n1 n2 n0
16319 d m y y1 y2 date1 date2 nmonths nm ny m2)
16321 (setq start (org-date-to-gregorian start)
16322 current (org-date-to-gregorian
16323 (if show-all
16324 current
16325 (time-to-days (current-time))))
16326 sday (calendar-absolute-from-gregorian start)
16327 cday (calendar-absolute-from-gregorian current))
16329 (if (<= cday sday) (throw 'exit sday))
16331 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16332 (setq dn (string-to-number (match-string 1 change))
16333 dw (cdr (assoc (match-string 2 change) a1)))
16334 (error "Invalid change specifier: %s" change))
16335 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16336 (cond
16337 ((eq dw 'day)
16338 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16339 n2 (+ n1 dn)))
16340 ((eq dw 'year)
16341 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16342 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16343 (setq date1 (list m d y1)
16344 n1 (calendar-absolute-from-gregorian date1)
16345 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16346 n2 (calendar-absolute-from-gregorian date2)))
16347 ((eq dw 'month)
16348 ;; approx number of month between the two dates
16349 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16350 ;; How often does dn fit in there?
16351 (setq d (nth 1 start) m (car start) y (nth 2 start)
16352 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16353 m (+ m nm)
16354 ny (floor (/ m 12))
16355 y (+ y ny)
16356 m (- m (* ny 12)))
16357 (while (> m 12) (setq m (- m 12) y (1+ y)))
16358 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16359 (setq m2 (+ m dn) y2 y)
16360 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16361 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16362 (while (<= n2 cday)
16363 (setq n1 n2 m m2 y y2)
16364 (setq m2 (+ m dn) y2 y)
16365 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16366 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16367 ;; Make sure n1 is the earlier date
16368 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16369 (if show-all
16370 (cond
16371 ((eq prefer 'past) (if (= cday n2) n2 n1))
16372 ((eq prefer 'future) (if (= cday n1) n1 n2))
16373 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16374 (cond
16375 ((eq prefer 'past) (if (= cday n2) n2 n1))
16376 ((eq prefer 'future) (if (= cday n1) n1 n2))
16377 (t (if (= cday n1) n1 n2)))))))
16379 (defun org-date-to-gregorian (date)
16380 "Turn any specification of DATE into a Gregorian date for the calendar."
16381 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16382 ((and (listp date) (= (length date) 3)) date)
16383 ((stringp date)
16384 (setq date (org-parse-time-string date))
16385 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16386 ((listp date)
16387 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16389 (defun org-parse-time-string (s &optional nodefault)
16390 "Parse the standard Org-mode time string.
16391 This should be a lot faster than the normal `parse-time-string'.
16392 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16393 hour and minute fields will be nil if not given."
16394 (if (string-match org-ts-regexp0 s)
16395 (list 0
16396 (if (or (match-beginning 8) (not nodefault))
16397 (string-to-number (or (match-string 8 s) "0")))
16398 (if (or (match-beginning 7) (not nodefault))
16399 (string-to-number (or (match-string 7 s) "0")))
16400 (string-to-number (match-string 4 s))
16401 (string-to-number (match-string 3 s))
16402 (string-to-number (match-string 2 s))
16403 nil nil nil)
16404 (error "Not a standard Org-mode time string: %s" s)))
16406 (defun org-timestamp-up (&optional arg)
16407 "Increase the date item at the cursor by one.
16408 If the cursor is on the year, change the year. If it is on the month,
16409 the day or the time, change that.
16410 With prefix ARG, change by that many units."
16411 (interactive "p")
16412 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16414 (defun org-timestamp-down (&optional arg)
16415 "Decrease the date item at the cursor by one.
16416 If the cursor is on the year, change the year. If it is on the month,
16417 the day or the time, change that.
16418 With prefix ARG, change by that many units."
16419 (interactive "p")
16420 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16422 (defun org-timestamp-up-day (&optional arg)
16423 "Increase the date in the time stamp by one day.
16424 With prefix ARG, change that many days."
16425 (interactive "p")
16426 (if (and (not (org-at-timestamp-p t))
16427 (org-at-heading-p))
16428 (org-todo 'up)
16429 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16431 (defun org-timestamp-down-day (&optional arg)
16432 "Decrease the date in the time stamp by one day.
16433 With prefix ARG, change that many days."
16434 (interactive "p")
16435 (if (and (not (org-at-timestamp-p t))
16436 (org-at-heading-p))
16437 (org-todo 'down)
16438 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16440 (defun org-at-timestamp-p (&optional inactive-ok)
16441 "Determine if the cursor is in or at a timestamp."
16442 (interactive)
16443 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16444 (pos (point))
16445 (ans (or (looking-at tsr)
16446 (save-excursion
16447 (skip-chars-backward "^[<\n\r\t")
16448 (if (> (point) (point-min)) (backward-char 1))
16449 (and (looking-at tsr)
16450 (> (- (match-end 0) pos) -1))))))
16451 (and ans
16452 (boundp 'org-ts-what)
16453 (setq org-ts-what
16454 (cond
16455 ((= pos (match-beginning 0)) 'bracket)
16456 ;; Point is considered to be "on the bracket" whether
16457 ;; it's really on it or right after it.
16458 ((= pos (1- (match-end 0))) 'bracket)
16459 ((= pos (match-end 0)) 'after)
16460 ((org-pos-in-match-range pos 2) 'year)
16461 ((org-pos-in-match-range pos 3) 'month)
16462 ((org-pos-in-match-range pos 7) 'hour)
16463 ((org-pos-in-match-range pos 8) 'minute)
16464 ((or (org-pos-in-match-range pos 4)
16465 (org-pos-in-match-range pos 5)) 'day)
16466 ((and (> pos (or (match-end 8) (match-end 5)))
16467 (< pos (match-end 0)))
16468 (- pos (or (match-end 8) (match-end 5))))
16469 (t 'day))))
16470 ans))
16472 (defun org-toggle-timestamp-type ()
16473 "Toggle the type (<active> or [inactive]) of a time stamp."
16474 (interactive)
16475 (when (org-at-timestamp-p t)
16476 (let ((beg (match-beginning 0)) (end (match-end 0))
16477 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16478 (save-excursion
16479 (goto-char beg)
16480 (while (re-search-forward "[][<>]" end t)
16481 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16482 t t)))
16483 (message "Timestamp is now %sactive"
16484 (if (equal (char-after beg) ?<) "" "in")))))
16486 (defvar org-clock-history) ; defined in org-clock.el
16487 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16488 (defun org-timestamp-change (n &optional what updown)
16489 "Change the date in the time stamp at point.
16490 The date will be changed by N times WHAT. WHAT can be `day', `month',
16491 `year', `minute', `second'. If WHAT is not given, the cursor position
16492 in the timestamp determines what will be changed."
16493 (let ((origin (point)) origin-cat
16494 with-hm inactive
16495 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16496 org-ts-what
16497 extra rem
16498 ts time time0 fixnext clrgx)
16499 (if (not (org-at-timestamp-p t))
16500 (error "Not at a timestamp"))
16501 (if (and (not what) (eq org-ts-what 'bracket))
16502 (org-toggle-timestamp-type)
16503 ;; Point isn't on brackets. Remember the part of the time-stamp
16504 ;; the point was in. Indeed, size of time-stamps may change,
16505 ;; but point must be kept in the same category nonetheless.
16506 (setq origin-cat org-ts-what)
16507 (if (and (not what) (not (eq org-ts-what 'day))
16508 org-display-custom-times
16509 (get-text-property (point) 'display)
16510 (not (get-text-property (1- (point)) 'display)))
16511 (setq org-ts-what 'day))
16512 (setq org-ts-what (or what org-ts-what)
16513 inactive (= (char-after (match-beginning 0)) ?\[)
16514 ts (match-string 0))
16515 (replace-match "")
16516 (if (string-match
16517 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16519 (setq extra (match-string 1 ts)))
16520 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16521 (setq with-hm t))
16522 (setq time0 (org-parse-time-string ts))
16523 (when (and updown
16524 (eq org-ts-what 'minute)
16525 (not current-prefix-arg))
16526 ;; This looks like s-up and s-down. Change by one rounding step.
16527 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16528 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16529 (setcar (cdr time0) (+ (nth 1 time0)
16530 (if (> n 0) (- rem) (- dm rem))))))
16531 (setq time
16532 (encode-time (or (car time0) 0)
16533 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16534 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16535 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16536 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16537 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16538 (nthcdr 6 time0)))
16539 (when (and (member org-ts-what '(hour minute))
16540 extra
16541 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16542 (setq extra (org-modify-ts-extra
16543 extra
16544 (if (eq org-ts-what 'hour) 2 5)
16545 n dm)))
16546 (when (integerp org-ts-what)
16547 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16548 (if (eq what 'calendar)
16549 (let ((cal-date (org-get-date-from-calendar)))
16550 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16551 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16552 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16553 (setcar time0 (or (car time0) 0))
16554 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16555 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16556 (setq time (apply 'encode-time time0))))
16557 ;; Insert the new time-stamp, and ensure point stays in the same
16558 ;; category as before (i.e. not after the last position in that
16559 ;; category).
16560 (let ((pos (point)))
16561 ;; Stay before inserted string. `save-excursion' is of no use.
16562 (setq org-last-changed-timestamp
16563 (org-insert-time-stamp time with-hm inactive nil nil extra))
16564 (goto-char pos))
16565 (save-match-data
16566 (looking-at org-ts-regexp3)
16567 (goto-char (cond
16568 ;; `day' category ends before `hour' if any, or at
16569 ;; the end of the day name.
16570 ((eq origin-cat 'day)
16571 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16572 ((eq origin-cat 'hour) (min (match-end 7) origin))
16573 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16574 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16575 ;; `year' and `month' have both fixed size: point
16576 ;; couldn't have moved into another part.
16577 (t origin))))
16578 ;; Update clock if on a CLOCK line.
16579 (org-clock-update-time-maybe)
16580 ;; Maybe adjust the closest clock in `org-clock-history'
16581 (when org-clock-adjust-closest
16582 (if (not (and (org-at-clock-log-p)
16583 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16584 org-clock-history))))))
16585 (message "No clock to adjust")
16586 (cond ((save-excursion ; fix previous clock?
16587 (re-search-backward org-ts-regexp0 nil t)
16588 (org-looking-back (concat org-clock-string " \\[")))
16589 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16590 ((save-excursion ; fix next clock?
16591 (re-search-backward org-ts-regexp0 nil t)
16592 (looking-at (concat org-ts-regexp0 "\\] =>")))
16593 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16594 (save-window-excursion
16595 ;; Find closest clock to point, adjust the previous/next one in history
16596 (let* ((p (save-excursion (org-back-to-heading t)))
16597 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16598 (clfixnth
16599 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16600 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16601 (if (not clfixpos)
16602 (message "No clock to adjust")
16603 (save-excursion
16604 (org-goto-marker-or-bmk clfixpos)
16605 (org-show-subtree)
16606 (when (re-search-forward clrgx nil t)
16607 (goto-char (match-beginning 1))
16608 (let (org-clock-adjust-closest)
16609 (org-timestamp-change n org-ts-what updown))
16610 (message "Clock adjusted in %s for heading: %s"
16611 (file-name-nondirectory (buffer-file-name))
16612 (org-get-heading t t)))))))))
16613 ;; Try to recenter the calendar window, if any.
16614 (if (and org-calendar-follow-timestamp-change
16615 (get-buffer-window "*Calendar*" t)
16616 (memq org-ts-what '(day month year)))
16617 (org-recenter-calendar (time-to-days time))))))
16619 (defun org-modify-ts-extra (s pos n dm)
16620 "Change the different parts of the lead-time and repeat fields in timestamp."
16621 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16622 ng h m new rem)
16623 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16624 (cond
16625 ((or (org-pos-in-match-range pos 2)
16626 (org-pos-in-match-range pos 3))
16627 (setq m (string-to-number (match-string 3 s))
16628 h (string-to-number (match-string 2 s)))
16629 (if (org-pos-in-match-range pos 2)
16630 (setq h (+ h n))
16631 (setq n (* dm (org-no-warnings (signum n))))
16632 (when (not (= 0 (setq rem (% m dm))))
16633 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16634 (setq m (+ m n)))
16635 (if (< m 0) (setq m (+ m 60) h (1- h)))
16636 (if (> m 59) (setq m (- m 60) h (1+ h)))
16637 (setq h (min 24 (max 0 h)))
16638 (setq ng 1 new (format "-%02d:%02d" h m)))
16639 ((org-pos-in-match-range pos 6)
16640 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16641 ((org-pos-in-match-range pos 5)
16642 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16644 ((org-pos-in-match-range pos 9)
16645 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16646 ((org-pos-in-match-range pos 8)
16647 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16649 (when ng
16650 (setq s (concat
16651 (substring s 0 (match-beginning ng))
16653 (substring s (match-end ng))))))
16656 (defun org-recenter-calendar (date)
16657 "If the calendar is visible, recenter it to DATE."
16658 (let ((cwin (get-buffer-window "*Calendar*" t)))
16659 (when cwin
16660 (let ((calendar-move-hook nil))
16661 (with-selected-window cwin
16662 (calendar-goto-date (if (listp date) date
16663 (calendar-gregorian-from-absolute date))))))))
16665 (defun org-goto-calendar (&optional arg)
16666 "Go to the Emacs calendar at the current date.
16667 If there is a time stamp in the current line, go to that date.
16668 A prefix ARG can be used to force the current date."
16669 (interactive "P")
16670 (let ((tsr org-ts-regexp) diff
16671 (calendar-move-hook nil)
16672 (calendar-view-holidays-initially-flag nil)
16673 (calendar-view-diary-initially-flag nil))
16674 (if (or (org-at-timestamp-p)
16675 (save-excursion
16676 (beginning-of-line 1)
16677 (looking-at (concat ".*" tsr))))
16678 (let ((d1 (time-to-days (current-time)))
16679 (d2 (time-to-days
16680 (org-time-string-to-time (match-string 1)))))
16681 (setq diff (- d2 d1))))
16682 (calendar)
16683 (calendar-goto-today)
16684 (if (and diff (not arg)) (calendar-forward-day diff))))
16686 (defun org-get-date-from-calendar ()
16687 "Return a list (month day year) of date at point in calendar."
16688 (with-current-buffer "*Calendar*"
16689 (save-match-data
16690 (calendar-cursor-to-date))))
16692 (defun org-date-from-calendar ()
16693 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16694 If there is already a time stamp at the cursor position, update it."
16695 (interactive)
16696 (if (org-at-timestamp-p t)
16697 (org-timestamp-change 0 'calendar)
16698 (let ((cal-date (org-get-date-from-calendar)))
16699 (org-insert-time-stamp
16700 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16702 (defun org-minutes-to-hh:mm-string (m)
16703 "Compute H:MM from a number of minutes."
16704 (let ((h (/ m 60)))
16705 (setq m (- m (* 60 h)))
16706 (format org-time-clocksum-format h m)))
16708 (defun org-hh:mm-string-to-minutes (s)
16709 "Convert a string H:MM to a number of minutes.
16710 If the string is just a number, interpret it as minutes.
16711 In fact, the first hh:mm or number in the string will be taken,
16712 there can be extra stuff in the string.
16713 If no number is found, the return value is 0."
16714 (cond
16715 ((integerp s) s)
16716 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16717 (+ (* (string-to-number (match-string 1 s)) 60)
16718 (string-to-number (match-string 2 s))))
16719 ((string-match "\\([0-9]+\\)" s)
16720 (string-to-number (match-string 1 s)))
16721 (t 0)))
16723 (defcustom org-effort-durations
16724 `(("h" . 60)
16725 ("d" . ,(* 60 8))
16726 ("w" . ,(* 60 8 5))
16727 ("m" . ,(* 60 8 5 4))
16728 ("y" . ,(* 60 8 5 40)))
16729 "Conversion factor to minutes for an effort modifier.
16731 Each entry has the form (MODIFIER . MINUTES).
16733 In an effort string, a number followed by MODIFIER is multiplied
16734 by the specified number of MINUTES to obtain an effort in
16735 minutes.
16737 For example, if the value of this variable is ((\"hours\" . 60)), then an
16738 effort string \"2hours\" is equivalent to 120 minutes."
16739 :group 'org-agenda
16740 :version "24.1"
16741 :type '(alist :key-type (string :tag "Modifier")
16742 :value-type (number :tag "Minutes")))
16744 (defcustom org-image-actual-width t
16745 "Should we use the actual width of images when inlining them?
16747 When set to `t', always use the image width.
16749 When set to a number, use imagemagick (when available) to set
16750 the image's width to this value.
16752 When set to a number in a list, try to get the width from the
16753 #+ATTR.* keyword if it matches a width specification like
16754 width=\"[0-9]+\", and fall back on that number if none is found.
16756 When set to nil, try to get the width from an #+ATTR.* keyword
16757 and fall back on the original width if none is found.
16759 This requires Emacs >= 24.1, build with imagemagick support."
16760 :group 'org-appearance
16761 :version "24.3"
16762 :type '(choice
16763 (const :tag "Use the image width" t)
16764 (integer :tag "Use a number of pixels")
16765 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16766 (const :tag "Use #+ATTR* or don't resize" nil)))
16768 (defun org-duration-string-to-minutes (s &optional output-to-string)
16769 "Convert a duration string S to minutes.
16771 A bare number is interpreted as minutes, modifiers can be set by
16772 customizing `org-effort-durations' (which see).
16774 Entries containing a colon are interpreted as H:MM by
16775 `org-hh:mm-string-to-minutes'."
16776 (let ((result 0)
16777 (re (concat "\\([0-9.]+\\) *\\("
16778 (regexp-opt (mapcar 'car org-effort-durations))
16779 "\\)")))
16780 (while (string-match re s)
16781 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16782 (string-to-number (match-string 1 s))))
16783 (setq s (replace-match "" nil t s)))
16784 (setq result (floor result))
16785 (incf result (org-hh:mm-string-to-minutes s))
16786 (if output-to-string (number-to-string result) result)))
16788 ;;;; Files
16790 (defun org-save-all-org-buffers ()
16791 "Save all Org-mode buffers without user confirmation."
16792 (interactive)
16793 (message "Saving all Org-mode buffers...")
16794 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16795 (when (featurep 'org-id) (org-id-locations-save))
16796 (message "Saving all Org-mode buffers... done"))
16798 (defun org-revert-all-org-buffers ()
16799 "Revert all Org-mode buffers.
16800 Prompt for confirmation when there are unsaved changes.
16801 Be sure you know what you are doing before letting this function
16802 overwrite your changes.
16804 This function is useful in a setup where one tracks org files
16805 with a version control system, to revert on one machine after pulling
16806 changes from another. I believe the procedure must be like this:
16808 1. M-x org-save-all-org-buffers
16809 2. Pull changes from the other machine, resolve conflicts
16810 3. M-x org-revert-all-org-buffers"
16811 (interactive)
16812 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16813 (error "Abort"))
16814 (save-excursion
16815 (save-window-excursion
16816 (mapc
16817 (lambda (b)
16818 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16819 (with-current-buffer b buffer-file-name))
16820 (org-pop-to-buffer-same-window b)
16821 (revert-buffer t 'no-confirm)))
16822 (buffer-list))
16823 (when (and (featurep 'org-id) org-id-track-globally)
16824 (org-id-locations-load)))))
16826 ;;;; Agenda files
16828 ;;;###autoload
16829 (defun org-switchb (&optional arg)
16830 "Switch between Org buffers.
16831 With one prefix argument, restrict available buffers to files.
16832 With two prefix arguments, restrict available buffers to agenda files.
16834 Defaults to `iswitchb' for buffer name completion.
16835 Set `org-completion-use-ido' to make it use ido instead."
16836 (interactive "P")
16837 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16838 ((equal arg '(16)) (org-buffer-list 'agenda))
16839 (t (org-buffer-list))))
16840 (org-completion-use-iswitchb org-completion-use-iswitchb)
16841 (org-completion-use-ido org-completion-use-ido))
16842 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16843 (setq org-completion-use-iswitchb t))
16844 (org-pop-to-buffer-same-window
16845 (org-icompleting-read "Org buffer: "
16846 (mapcar 'list (mapcar 'buffer-name blist))
16847 nil t))))
16849 ;;; Define some older names previously used for this functionality
16850 ;;;###autoload
16851 (defalias 'org-ido-switchb 'org-switchb)
16852 ;;;###autoload
16853 (defalias 'org-iswitchb 'org-switchb)
16855 (defun org-buffer-list (&optional predicate exclude-tmp)
16856 "Return a list of Org buffers.
16857 PREDICATE can be `export', `files' or `agenda'.
16859 export restrict the list to Export buffers.
16860 files restrict the list to buffers visiting Org files.
16861 agenda restrict the list to buffers visiting agenda files.
16863 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16864 (let* ((bfn nil)
16865 (agenda-files (and (eq predicate 'agenda)
16866 (mapcar 'file-truename (org-agenda-files t))))
16867 (filter
16868 (cond
16869 ((eq predicate 'files)
16870 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16871 ((eq predicate 'export)
16872 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16873 ((eq predicate 'agenda)
16874 (lambda (b)
16875 (with-current-buffer b
16876 (and (derived-mode-p 'org-mode)
16877 (setq bfn (buffer-file-name b))
16878 (member (file-truename bfn) agenda-files)))))
16879 (t (lambda (b) (with-current-buffer b
16880 (or (derived-mode-p 'org-mode)
16881 (string-match "\*Org .*Export"
16882 (buffer-name b)))))))))
16883 (delq nil
16884 (mapcar
16885 (lambda(b)
16886 (if (and (funcall filter b)
16887 (or (not exclude-tmp)
16888 (not (string-match "tmp" (buffer-name b)))))
16890 nil))
16891 (buffer-list)))))
16893 (defun org-agenda-files (&optional unrestricted archives)
16894 "Get the list of agenda files.
16895 Optional UNRESTRICTED means return the full list even if a restriction
16896 is currently in place.
16897 When ARCHIVES is t, include all archive files that are really being
16898 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16899 `org-agenda-archives-mode' is t."
16900 (let ((files
16901 (cond
16902 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16903 ((stringp org-agenda-files) (org-read-agenda-file-list))
16904 ((listp org-agenda-files) org-agenda-files)
16905 (t (error "Invalid value of `org-agenda-files'")))))
16906 (setq files (apply 'append
16907 (mapcar (lambda (f)
16908 (if (file-directory-p f)
16909 (directory-files
16910 f t org-agenda-file-regexp)
16911 (list f)))
16912 files)))
16913 (when org-agenda-skip-unavailable-files
16914 (setq files (delq nil
16915 (mapcar (function
16916 (lambda (file)
16917 (and (file-readable-p file) file)))
16918 files))))
16919 (when (or (eq archives t)
16920 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16921 (setq files (org-add-archive-files files)))
16922 files))
16924 (defun org-agenda-file-p (&optional file)
16925 "Return non-nil, if FILE is an agenda file.
16926 If FILE is omitted, use the file associated with the current
16927 buffer."
16928 (member (or file (buffer-file-name))
16929 (org-agenda-files t)))
16931 (defun org-edit-agenda-file-list ()
16932 "Edit the list of agenda files.
16933 Depending on setup, this either uses customize to edit the variable
16934 `org-agenda-files', or it visits the file that is holding the list. In the
16935 latter case, the buffer is set up in a way that saving it automatically kills
16936 the buffer and restores the previous window configuration."
16937 (interactive)
16938 (if (stringp org-agenda-files)
16939 (let ((cw (current-window-configuration)))
16940 (find-file org-agenda-files)
16941 (org-set-local 'org-window-configuration cw)
16942 (org-add-hook 'after-save-hook
16943 (lambda ()
16944 (set-window-configuration
16945 (prog1 org-window-configuration
16946 (kill-buffer (current-buffer))))
16947 (org-install-agenda-files-menu)
16948 (message "New agenda file list installed"))
16949 nil 'local)
16950 (message "%s" (substitute-command-keys
16951 "Edit list and finish with \\[save-buffer]")))
16952 (customize-variable 'org-agenda-files)))
16954 (defun org-store-new-agenda-file-list (list)
16955 "Set new value for the agenda file list and save it correctly."
16956 (if (stringp org-agenda-files)
16957 (let ((fe (org-read-agenda-file-list t)) b u)
16958 (while (setq b (find-buffer-visiting org-agenda-files))
16959 (kill-buffer b))
16960 (with-temp-file org-agenda-files
16961 (insert
16962 (mapconcat
16963 (lambda (f) ;; Keep un-expanded entries.
16964 (if (setq u (assoc f fe))
16965 (cdr u)
16967 list "\n")
16968 "\n")))
16969 (let ((org-mode-hook nil) (org-inhibit-startup t)
16970 (org-insert-mode-line-in-empty-file nil))
16971 (setq org-agenda-files list)
16972 (customize-save-variable 'org-agenda-files org-agenda-files))))
16974 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16975 "Read the list of agenda files from a file.
16976 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16977 filenames, used by `org-store-new-agenda-file-list' to write back
16978 un-expanded file names."
16979 (when (file-directory-p org-agenda-files)
16980 (error "`org-agenda-files' cannot be a single directory"))
16981 (when (stringp org-agenda-files)
16982 (with-temp-buffer
16983 (insert-file-contents org-agenda-files)
16984 (mapcar
16985 (lambda (f)
16986 (let ((e (expand-file-name (substitute-in-file-name f)
16987 org-directory)))
16988 (if pair-with-expansion
16989 (cons e f)
16990 e)))
16991 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16993 ;;;###autoload
16994 (defun org-cycle-agenda-files ()
16995 "Cycle through the files in `org-agenda-files'.
16996 If the current buffer visits an agenda file, find the next one in the list.
16997 If the current buffer does not, find the first agenda file."
16998 (interactive)
16999 (let* ((fs (org-agenda-files t))
17000 (files (append fs (list (car fs))))
17001 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17002 file)
17003 (unless files (error "No agenda files"))
17004 (catch 'exit
17005 (while (setq file (pop files))
17006 (if (equal (file-truename file) tcf)
17007 (when (car files)
17008 (find-file (car files))
17009 (throw 'exit t))))
17010 (find-file (car fs)))
17011 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17013 (defun org-agenda-file-to-front (&optional to-end)
17014 "Move/add the current file to the top of the agenda file list.
17015 If the file is not present in the list, it is added to the front. If it is
17016 present, it is moved there. With optional argument TO-END, add/move to the
17017 end of the list."
17018 (interactive "P")
17019 (let ((org-agenda-skip-unavailable-files nil)
17020 (file-alist (mapcar (lambda (x)
17021 (cons (file-truename x) x))
17022 (org-agenda-files t)))
17023 (ctf (file-truename buffer-file-name))
17024 x had)
17025 (setq x (assoc ctf file-alist) had x)
17027 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17028 (if to-end
17029 (setq file-alist (append (delq x file-alist) (list x)))
17030 (setq file-alist (cons x (delq x file-alist))))
17031 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17032 (org-install-agenda-files-menu)
17033 (message "File %s to %s of agenda file list"
17034 (if had "moved" "added") (if to-end "end" "front"))))
17036 (defun org-remove-file (&optional file)
17037 "Remove current file from the list of files in variable `org-agenda-files'.
17038 These are the files which are being checked for agenda entries.
17039 Optional argument FILE means use this file instead of the current."
17040 (interactive)
17041 (let* ((org-agenda-skip-unavailable-files nil)
17042 (file (or file buffer-file-name))
17043 (true-file (file-truename file))
17044 (afile (abbreviate-file-name file))
17045 (files (delq nil (mapcar
17046 (lambda (x)
17047 (if (equal true-file
17048 (file-truename x))
17049 nil x))
17050 (org-agenda-files t)))))
17051 (if (not (= (length files) (length (org-agenda-files t))))
17052 (progn
17053 (org-store-new-agenda-file-list files)
17054 (org-install-agenda-files-menu)
17055 (message "Removed file: %s" afile))
17056 (message "File was not in list: %s (not removed)" afile))))
17058 (defun org-file-menu-entry (file)
17059 (vector file (list 'find-file file) t))
17061 (defun org-check-agenda-file (file)
17062 "Make sure FILE exists. If not, ask user what to do."
17063 (when (not (file-exists-p file))
17064 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17065 (abbreviate-file-name file))
17066 (let ((r (downcase (read-char-exclusive))))
17067 (cond
17068 ((equal r ?r)
17069 (org-remove-file file)
17070 (throw 'nextfile t))
17071 (t (error "Abort"))))))
17073 (defun org-get-agenda-file-buffer (file)
17074 "Get a buffer visiting FILE. If the buffer needs to be created, add
17075 it to the list of buffers which might be released later."
17076 (let ((buf (org-find-base-buffer-visiting file)))
17077 (if buf
17078 buf ; just return it
17079 ;; Make a new buffer and remember it
17080 (setq buf (find-file-noselect file))
17081 (if buf (push buf org-agenda-new-buffers))
17082 buf)))
17084 (defun org-release-buffers (blist)
17085 "Release all buffers in list, asking the user for confirmation when needed.
17086 When a buffer is unmodified, it is just killed. When modified, it is saved
17087 \(if the user agrees) and then killed."
17088 (let (buf file)
17089 (while (setq buf (pop blist))
17090 (setq file (buffer-file-name buf))
17091 (when (and (buffer-modified-p buf)
17092 file
17093 (y-or-n-p (format "Save file %s? " file)))
17094 (with-current-buffer buf (save-buffer)))
17095 (kill-buffer buf))))
17097 (defun org-agenda-prepare-buffers (files)
17098 "Create buffers for all agenda files, protect archived trees and comments."
17099 (interactive)
17100 (let ((pa '(:org-archived t))
17101 (pc '(:org-comment t))
17102 (pall '(:org-archived t :org-comment t))
17103 (inhibit-read-only t)
17104 (rea (concat ":" org-archive-tag ":"))
17105 bmp file re)
17106 (save-excursion
17107 (save-restriction
17108 (while (setq file (pop files))
17109 (catch 'nextfile
17110 (if (bufferp file)
17111 (set-buffer file)
17112 (org-check-agenda-file file)
17113 (set-buffer (org-get-agenda-file-buffer file)))
17114 (widen)
17115 (setq bmp (buffer-modified-p))
17116 (org-refresh-category-properties)
17117 (setq org-todo-keywords-for-agenda
17118 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17119 (setq org-done-keywords-for-agenda
17120 (append org-done-keywords-for-agenda org-done-keywords))
17121 (setq org-todo-keyword-alist-for-agenda
17122 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17123 (setq org-drawers-for-agenda
17124 (append org-drawers-for-agenda org-drawers))
17125 (setq org-tag-alist-for-agenda
17126 (append org-tag-alist-for-agenda org-tag-alist))
17128 (save-excursion
17129 (remove-text-properties (point-min) (point-max) pall)
17130 (when org-agenda-skip-archived-trees
17131 (goto-char (point-min))
17132 (while (re-search-forward rea nil t)
17133 (if (org-at-heading-p t)
17134 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17135 (goto-char (point-min))
17136 (setq re (format org-heading-keyword-regexp-format
17137 org-comment-string))
17138 (while (re-search-forward re nil t)
17139 (add-text-properties
17140 (match-beginning 0) (org-end-of-subtree t) pc)))
17141 (set-buffer-modified-p bmp)))))
17142 (setq org-todo-keywords-for-agenda
17143 (org-uniquify org-todo-keywords-for-agenda))
17144 (setq org-todo-keyword-alist-for-agenda
17145 (org-uniquify org-todo-keyword-alist-for-agenda)
17146 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17148 ;;;; Embedded LaTeX
17150 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17151 "Keymap for the minor `org-cdlatex-mode'.")
17153 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17154 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17155 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17156 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17157 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17159 (defvar org-cdlatex-texmathp-advice-is-done nil
17160 "Flag remembering if we have applied the advice to texmathp already.")
17162 (define-minor-mode org-cdlatex-mode
17163 "Toggle the minor `org-cdlatex-mode'.
17164 This mode supports entering LaTeX environment and math in LaTeX fragments
17165 in Org-mode.
17166 \\{org-cdlatex-mode-map}"
17167 nil " OCDL" nil
17168 (when org-cdlatex-mode
17169 (require 'cdlatex)
17170 (run-hooks 'cdlatex-mode-hook)
17171 (cdlatex-compute-tables))
17172 (unless org-cdlatex-texmathp-advice-is-done
17173 (setq org-cdlatex-texmathp-advice-is-done t)
17174 (defadvice texmathp (around org-math-always-on activate)
17175 "Always return t in org-mode buffers.
17176 This is because we want to insert math symbols without dollars even outside
17177 the LaTeX math segments. If Orgmode thinks that point is actually inside
17178 an embedded LaTeX fragment, let texmathp do its job.
17179 \\[org-cdlatex-mode-map]"
17180 (interactive)
17181 (let (p)
17182 (cond
17183 ((not (derived-mode-p 'org-mode)) ad-do-it)
17184 ((eq this-command 'cdlatex-math-symbol)
17185 (setq ad-return-value t
17186 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17188 (let ((p (org-inside-LaTeX-fragment-p)))
17189 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17190 (setq ad-return-value t
17191 texmathp-why '("Org-mode embedded math" . 0))
17192 (if p ad-do-it)))))))))
17194 (defun turn-on-org-cdlatex ()
17195 "Unconditionally turn on `org-cdlatex-mode'."
17196 (org-cdlatex-mode 1))
17198 (defun org-inside-LaTeX-fragment-p ()
17199 "Test if point is inside a LaTeX fragment.
17200 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17201 sequence appearing also before point.
17202 Even though the matchers for math are configurable, this function assumes
17203 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17204 delimiters are skipped when they have been removed by customization.
17205 The return value is nil, or a cons cell with the delimiter and the
17206 position of this delimiter.
17208 This function does a reasonably good job, but can locally be fooled by
17209 for example currency specifications. For example it will assume being in
17210 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17211 fragments that are properly closed, but during editing, we have to live
17212 with the uncertainty caused by missing closing delimiters. This function
17213 looks only before point, not after."
17214 (catch 'exit
17215 (let ((pos (point))
17216 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17217 (lim (progn
17218 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17219 (point)))
17220 dd-on str (start 0) m re)
17221 (goto-char pos)
17222 (when dodollar
17223 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17224 re (nth 1 (assoc "$" org-latex-regexps)))
17225 (while (string-match re str start)
17226 (cond
17227 ((= (match-end 0) (length str))
17228 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17229 ((= (match-end 0) (- (length str) 5))
17230 (throw 'exit nil))
17231 (t (setq start (match-end 0))))))
17232 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17233 (goto-char pos)
17234 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17235 (and (match-beginning 2) (throw 'exit nil))
17236 ;; count $$
17237 (while (re-search-backward "\\$\\$" lim t)
17238 (setq dd-on (not dd-on)))
17239 (goto-char pos)
17240 (if dd-on (cons "$$" m))))))
17242 (defun org-inside-latex-macro-p ()
17243 "Is point inside a LaTeX macro or its arguments?"
17244 (save-match-data
17245 (org-in-regexp
17246 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17248 (defun org-try-cdlatex-tab ()
17249 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17250 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17251 - inside a LaTeX fragment, or
17252 - after the first word in a line, where an abbreviation expansion could
17253 insert a LaTeX environment."
17254 (when org-cdlatex-mode
17255 (cond
17256 ;; Before any word on the line: No expansion possible.
17257 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17258 ;; Just after first word on the line: Expand it. Make sure it
17259 ;; cannot happen on headlines, though.
17260 ((save-excursion
17261 (skip-chars-backward "a-zA-Z0-9*")
17262 (skip-chars-backward " \t")
17263 (and (bolp) (not (org-at-heading-p))))
17264 (cdlatex-tab) t)
17265 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17267 (defun org-cdlatex-underscore-caret (&optional arg)
17268 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17269 Revert to the normal definition outside of these fragments."
17270 (interactive "P")
17271 (if (org-inside-LaTeX-fragment-p)
17272 (call-interactively 'cdlatex-sub-superscript)
17273 (let (org-cdlatex-mode)
17274 (call-interactively (key-binding (vector last-input-event))))))
17276 (defun org-cdlatex-math-modify (&optional arg)
17277 "Execute `cdlatex-math-modify' in LaTeX fragments.
17278 Revert to the normal definition outside of these fragments."
17279 (interactive "P")
17280 (if (org-inside-LaTeX-fragment-p)
17281 (call-interactively 'cdlatex-math-modify)
17282 (let (org-cdlatex-mode)
17283 (call-interactively (key-binding (vector last-input-event))))))
17285 (defvar org-latex-fragment-image-overlays nil
17286 "List of overlays carrying the images of latex fragments.")
17287 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17289 (defun org-remove-latex-fragment-image-overlays ()
17290 "Remove all overlays with LaTeX fragment images in current buffer."
17291 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17292 (setq org-latex-fragment-image-overlays nil))
17294 (defun org-preview-latex-fragment (&optional subtree)
17295 "Preview the LaTeX fragment at point, or all locally or globally.
17296 If the cursor is in a LaTeX fragment, create the image and overlay
17297 it over the source code. If there is no fragment at point, display
17298 all fragments in the current text, from one headline to the next. With
17299 prefix SUBTREE, display all fragments in the current subtree. With a
17300 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17301 the cursor is before the first headline,
17302 display all fragments in the buffer.
17303 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17304 (interactive "P")
17305 (unless buffer-file-name
17306 (error "Can't preview LaTeX fragment in a non-file buffer"))
17307 (org-remove-latex-fragment-image-overlays)
17308 (save-excursion
17309 (save-restriction
17310 (let (beg end at msg)
17311 (cond
17312 ((or (equal subtree '(16))
17313 (not (save-excursion
17314 (re-search-backward org-outline-regexp-bol nil t))))
17315 (setq beg (point-min) end (point-max)
17316 msg "Creating images for buffer...%s"))
17317 ((equal subtree '(4))
17318 (org-back-to-heading)
17319 (setq beg (point) end (org-end-of-subtree t)
17320 msg "Creating images for subtree...%s"))
17322 (if (setq at (org-inside-LaTeX-fragment-p))
17323 (goto-char (max (point-min) (- (cdr at) 2)))
17324 (org-back-to-heading))
17325 (setq beg (point) end (progn (outline-next-heading) (point))
17326 msg (if at "Creating image...%s"
17327 "Creating images for entry...%s"))))
17328 (message msg "")
17329 (narrow-to-region beg end)
17330 (goto-char beg)
17331 (org-format-latex
17332 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17333 (file-name-nondirectory
17334 buffer-file-name)))
17335 default-directory 'overlays msg at 'forbuffer
17336 org-latex-create-formula-image-program)
17337 (message msg "done. Use `C-c C-c' to remove images.")))))
17339 (defvar org-latex-regexps
17340 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17341 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17342 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17343 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17344 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17345 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17346 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17347 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17348 "Regular expressions for matching embedded LaTeX.")
17350 (defvar org-export-have-math nil) ;; dynamic scoping
17351 (defun org-format-latex (prefix &optional dir overlays msg at
17352 forbuffer processing-type)
17353 "Replace LaTeX fragments with links to an image, and produce images.
17354 Some of the options can be changed using the variable
17355 `org-format-latex-options'."
17356 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17357 (let* ((prefixnodir (file-name-nondirectory prefix))
17358 (absprefix (expand-file-name prefix dir))
17359 (todir (file-name-directory absprefix))
17360 (opt org-format-latex-options)
17361 (matchers (plist-get opt :matchers))
17362 (re-list org-latex-regexps)
17363 (org-format-latex-header-extra
17364 (plist-get (org-infile-export-plist) :latex-header-extra))
17365 (cnt 0) txt hash link beg end re e checkdir
17366 executables-checked string
17367 m n block-type block linkfile movefile ov)
17368 ;; Check the different regular expressions
17369 (while (setq e (pop re-list))
17370 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17371 block (if block-type "\n\n" ""))
17372 (when (member m matchers)
17373 (goto-char (point-min))
17374 (while (re-search-forward re nil t)
17375 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17376 (not (get-text-property (match-beginning n)
17377 'org-protected))
17378 (or (not overlays)
17379 (not (eq (get-char-property (match-beginning n)
17380 'org-overlay-type)
17381 'org-latex-overlay))))
17382 (setq org-export-have-math t)
17383 (cond
17384 ((eq processing-type 'verbatim)
17385 ;; Leave the text verbatim, just protect it
17386 (add-text-properties (match-beginning n) (match-end n)
17387 '(org-protected t)))
17388 ((eq processing-type 'mathjax)
17389 ;; Prepare for MathJax processing
17390 (setq string (match-string n))
17391 (if (member m '("$" "$1"))
17392 (save-excursion
17393 (delete-region (match-beginning n) (match-end n))
17394 (goto-char (match-beginning n))
17395 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17396 "\\)")
17397 '(org-protected t))))
17398 (add-text-properties (match-beginning n) (match-end n)
17399 '(org-protected t))))
17400 ((or (eq processing-type 'dvipng)
17401 (eq processing-type 'imagemagick))
17402 ;; Process to an image
17403 (setq txt (match-string n)
17404 beg (match-beginning n) end (match-end n)
17405 cnt (1+ cnt))
17406 (let (print-length print-level) ; make sure full list is printed
17407 (setq hash (sha1 (prin1-to-string
17408 (list org-format-latex-header
17409 org-format-latex-header-extra
17410 org-export-latex-default-packages-alist
17411 org-export-latex-packages-alist
17412 org-format-latex-options
17413 forbuffer txt)))
17414 linkfile (format "%s_%s.png" prefix hash)
17415 movefile (format "%s_%s.png" absprefix hash)))
17416 (setq link (concat block "[[file:" linkfile "]]" block))
17417 (if msg (message msg cnt))
17418 (goto-char beg)
17419 (unless checkdir ; make sure the directory exists
17420 (setq checkdir t)
17421 (or (file-directory-p todir) (make-directory todir t)))
17422 (cond
17423 ((eq processing-type 'dvipng)
17424 (unless executables-checked
17425 (org-check-external-command
17426 "latex" "needed to convert LaTeX fragments to images")
17427 (org-check-external-command
17428 "dvipng" "needed to convert LaTeX fragments to images")
17429 (setq executables-checked t))
17430 (unless (file-exists-p movefile)
17431 (org-create-formula-image-with-dvipng
17432 txt movefile opt forbuffer)))
17433 ((eq processing-type 'imagemagick)
17434 (unless executables-checked
17435 (org-check-external-command
17436 "convert" "you need to install imagemagick")
17437 (setq executables-checked t))
17438 (unless (file-exists-p movefile)
17439 (org-create-formula-image-with-imagemagick
17440 txt movefile opt forbuffer))))
17441 (if overlays
17442 (progn
17443 (mapc (lambda (o)
17444 (if (eq (overlay-get o 'org-overlay-type)
17445 'org-latex-overlay)
17446 (delete-overlay o)))
17447 (overlays-in beg end))
17448 (setq ov (make-overlay beg end))
17449 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17450 (if (featurep 'xemacs)
17451 (progn
17452 (overlay-put ov 'invisible t)
17453 (overlay-put
17454 ov 'end-glyph
17455 (make-glyph (vector 'png :file movefile))))
17456 (overlay-put
17457 ov 'display
17458 (list 'image :type 'png :file movefile :ascent 'center)))
17459 (push ov org-latex-fragment-image-overlays)
17460 (goto-char end))
17461 (delete-region beg end)
17462 (insert (org-add-props link
17463 (list 'org-latex-src
17464 (replace-regexp-in-string
17465 "\"" "" txt)
17466 'org-latex-src-embed-type
17467 (if block-type 'paragraph 'character))))))
17468 ((eq processing-type 'mathml)
17469 ;; Process to MathML
17470 (unless executables-checked
17471 (unless (save-match-data (org-format-latex-mathml-available-p))
17472 (error "LaTeX to MathML converter not configured"))
17473 (setq executables-checked t))
17474 (setq txt (match-string n)
17475 beg (match-beginning n) end (match-end n)
17476 cnt (1+ cnt))
17477 (if msg (message msg cnt))
17478 (goto-char beg)
17479 (delete-region beg end)
17480 (insert (org-format-latex-as-mathml
17481 txt block-type prefix dir)))
17483 (error "Unknown conversion type %s for latex fragments"
17484 processing-type)))))))))
17486 (defun org-create-math-formula (latex-frag &optional mathml-file)
17487 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17488 Use `org-latex-to-mathml-convert-command'. If the conversion is
17489 sucessful, return the portion between \"<math...> </math>\"
17490 elements otherwise return nil. When MATHML-FILE is specified,
17491 write the results in to that file. When invoked as an
17492 interactive command, prompt for LATEX-FRAG, with initial value
17493 set to the current active region and echo the results for user
17494 inspection."
17495 (interactive (list (let ((frag (when (org-region-active-p)
17496 (buffer-substring-no-properties
17497 (region-beginning) (region-end)))))
17498 (read-string "LaTeX Fragment: " frag nil frag))))
17499 (unless latex-frag (error "Invalid latex-frag"))
17500 (let* ((tmp-in-file (file-relative-name
17501 (make-temp-name (expand-file-name "ltxmathml-in"))))
17502 (ignore (write-region latex-frag nil tmp-in-file))
17503 (tmp-out-file (file-relative-name
17504 (make-temp-name (expand-file-name "ltxmathml-out"))))
17505 (cmd (format-spec
17506 org-latex-to-mathml-convert-command
17507 `((?j . ,(shell-quote-argument
17508 (expand-file-name org-latex-to-mathml-jar-file)))
17509 (?I . ,(shell-quote-argument tmp-in-file))
17510 (?o . ,(shell-quote-argument tmp-out-file)))))
17511 mathml shell-command-output)
17512 (when (org-called-interactively-p 'any)
17513 (unless (org-format-latex-mathml-available-p)
17514 (error "LaTeX to MathML converter not configured")))
17515 (message "Running %s" cmd)
17516 (setq shell-command-output (shell-command-to-string cmd))
17517 (setq mathml
17518 (when (file-readable-p tmp-out-file)
17519 (with-current-buffer (find-file-noselect tmp-out-file t)
17520 (goto-char (point-min))
17521 (when (re-search-forward
17522 (concat
17523 (regexp-quote
17524 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17525 "\\(.\\|\n\\)*"
17526 (regexp-quote "</math>")) nil t)
17527 (prog1 (match-string 0) (kill-buffer))))))
17528 (cond
17529 (mathml
17530 (setq mathml
17531 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17532 (when mathml-file
17533 (write-region mathml nil mathml-file))
17534 (when (org-called-interactively-p 'any)
17535 (message mathml)))
17536 ((message "LaTeX to MathML conversion failed")
17537 (message shell-command-output)))
17538 (delete-file tmp-in-file)
17539 (when (file-exists-p tmp-out-file)
17540 (delete-file tmp-out-file))
17541 mathml))
17543 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17544 prefix &optional dir)
17545 "Use `org-create-math-formula' but check local cache first."
17546 (let* ((absprefix (expand-file-name prefix dir))
17547 (print-length nil) (print-level nil)
17548 (formula-id (concat
17549 "formula-"
17550 (sha1
17551 (prin1-to-string
17552 (list latex-frag
17553 org-latex-to-mathml-convert-command)))))
17554 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17555 (formula-cache-dir (file-name-directory formula-cache)))
17557 (unless (file-directory-p formula-cache-dir)
17558 (make-directory formula-cache-dir t))
17560 (unless (file-exists-p formula-cache)
17561 (org-create-math-formula latex-frag formula-cache))
17563 (if (file-exists-p formula-cache)
17564 ;; Successful conversion. Return the link to MathML file.
17565 (org-add-props
17566 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17567 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17568 'org-latex-src-embed-type (if latex-frag-type
17569 'paragraph 'character)))
17570 ;; Failed conversion. Return the LaTeX fragment verbatim
17571 (add-text-properties
17572 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17573 latex-frag)))
17575 ;; This function borrows from Ganesh Swami's latex2png.el
17576 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17577 "This calls dvipng."
17578 (require 'org-latex)
17579 (let* ((tmpdir (if (featurep 'xemacs)
17580 (temp-directory)
17581 temporary-file-directory))
17582 (texfilebase (make-temp-name
17583 (expand-file-name "orgtex" tmpdir)))
17584 (texfile (concat texfilebase ".tex"))
17585 (dvifile (concat texfilebase ".dvi"))
17586 (pngfile (concat texfilebase ".png"))
17587 (fnh (if (featurep 'xemacs)
17588 (font-height (face-font 'default))
17589 (face-attribute 'default :height nil)))
17590 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17591 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17592 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17593 "Black"))
17594 (bg (or (plist-get options (if buffer :background :html-background))
17595 "Transparent")))
17596 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17597 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17598 (with-temp-file texfile
17599 (insert (org-splice-latex-header
17600 org-format-latex-header
17601 org-export-latex-default-packages-alist
17602 org-export-latex-packages-alist t
17603 org-format-latex-header-extra))
17604 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17605 (require 'org-latex)
17606 (org-export-latex-fix-inputenc))
17607 (let ((dir default-directory))
17608 (condition-case nil
17609 (progn
17610 (cd tmpdir)
17611 (call-process "latex" nil nil nil texfile))
17612 (error nil))
17613 (cd dir))
17614 (if (not (file-exists-p dvifile))
17615 (progn (message "Failed to create dvi file from %s" texfile) nil)
17616 (condition-case nil
17617 (if (featurep 'xemacs)
17618 (call-process "dvipng" nil nil nil
17619 "-fg" fg "-bg" bg
17620 "-T" "tight"
17621 "-o" pngfile
17622 dvifile)
17623 (call-process "dvipng" nil nil nil
17624 "-fg" fg "-bg" bg
17625 "-D" dpi
17626 ;;"-x" scale "-y" scale
17627 "-T" "tight"
17628 "-o" pngfile
17629 dvifile))
17630 (error nil))
17631 (if (not (file-exists-p pngfile))
17632 (if org-format-latex-signal-error
17633 (error "Failed to create png file from %s" texfile)
17634 (message "Failed to create png file from %s" texfile)
17635 nil)
17636 ;; Use the requested file name and clean up
17637 (copy-file pngfile tofile 'replace)
17638 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17639 (if (file-exists-p (concat texfilebase e))
17640 (delete-file (concat texfilebase e))))
17641 pngfile))))
17643 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17644 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17645 "This calls convert, which is included into imagemagick."
17646 (require 'org-latex)
17647 (let* ((tmpdir (if (featurep 'xemacs)
17648 (temp-directory)
17649 temporary-file-directory))
17650 (texfilebase (make-temp-name
17651 (expand-file-name "orgtex" tmpdir)))
17652 (texfile (concat texfilebase ".tex"))
17653 (pdffile (concat texfilebase ".pdf"))
17654 (pngfile (concat texfilebase ".png"))
17655 (fnh (if (featurep 'xemacs)
17656 (font-height (face-font 'default))
17657 (face-attribute 'default :height nil)))
17658 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17659 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17660 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17661 "black"))
17662 (bg (or (plist-get options (if buffer :background :html-background))
17663 "white")))
17664 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17665 (setq fg (org-latex-color-format fg)))
17666 (if (eq bg 'default) (setq bg (org-latex-color :background))
17667 (setq bg (org-latex-color-format
17668 (if (string= bg "Transparent")(setq bg "white")))))
17669 (with-temp-file texfile
17670 (insert (org-splice-latex-header
17671 org-format-latex-header
17672 org-export-latex-default-packages-alist
17673 org-export-latex-packages-alist t
17674 org-format-latex-header-extra))
17675 (insert "\n\\begin{document}\n"
17676 "\\definecolor{fg}{rgb}{" fg "}\n"
17677 "\\definecolor{bg}{rgb}{" bg "}\n"
17678 "\n\\pagecolor{bg}\n"
17679 "\n{\\color{fg}\n"
17680 string
17681 "\n}\n"
17682 "\n\\end{document}\n" )
17683 (require 'org-latex)
17684 (org-export-latex-fix-inputenc))
17685 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17686 (condition-case nil
17687 (progn
17688 (cd tmpdir)
17689 (setq cmds org-latex-to-pdf-process)
17690 (while cmds
17691 (setq latex-frags-cmds (pop cmds))
17692 (if (listp latex-frags-cmds)
17693 (setq cmds nil)
17694 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17695 (while latex-frags-cmds
17696 (setq cmd (pop latex-frags-cmds))
17697 (while (string-match "%b" cmd)
17698 (setq cmd (replace-match
17699 (save-match-data
17700 (shell-quote-argument texfile))
17701 t t cmd)))
17702 (while (string-match "%f" cmd)
17703 (setq cmd (replace-match
17704 (save-match-data
17705 (shell-quote-argument (file-name-nondirectory texfile)))
17706 t t cmd)))
17707 (while (string-match "%o" cmd)
17708 (setq cmd (replace-match
17709 (save-match-data
17710 (shell-quote-argument (file-name-directory texfile)))
17711 t t cmd)))
17712 (setq cmd (split-string cmd))
17713 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17714 (error nil))
17715 (cd dir))
17716 (if (not (file-exists-p pdffile))
17717 (progn (message "Failed to create pdf file from %s" texfile) nil)
17718 (condition-case nil
17719 (if (featurep 'xemacs)
17720 (call-process "convert" nil nil nil
17721 "-density" "96"
17722 "-trim"
17723 "-antialias"
17724 pdffile
17725 "-quality" "100"
17726 ;; "-sharpen" "0x1.0"
17727 pngfile)
17728 (call-process "convert" nil nil nil
17729 "-density" dpi
17730 "-trim"
17731 "-antialias"
17732 pdffile
17733 "-quality" "100"
17734 ; "-sharpen" "0x1.0"
17735 pngfile))
17736 (error nil))
17737 (if (not (file-exists-p pngfile))
17738 (if org-format-latex-signal-error
17739 (error "Failed to create png file from %s" texfile)
17740 (message "Failed to create png file from %s" texfile)
17741 nil)
17742 ;; Use the requested file name and clean up
17743 (copy-file pngfile tofile 'replace)
17744 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17745 (if (file-exists-p (concat texfilebase e))
17746 (delete-file (concat texfilebase e))))
17747 pngfile))))
17749 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17750 "Fill a LaTeX header template TPL.
17751 In the template, the following place holders will be recognized:
17753 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17754 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17755 [PACKAGES] \\usepackage statements for PKG
17756 [NO-PACKAGES] do not include PKG
17757 [EXTRA] the string EXTRA
17758 [NO-EXTRA] do not include EXTRA
17760 For backward compatibility, if both the positive and the negative place
17761 holder is missing, the positive one (without the \"NO-\") will be
17762 assumed to be present at the end of the template.
17763 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17764 EXTRA is a string.
17765 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17766 (let (rpl (end ""))
17767 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17768 (setq rpl (if (or (match-end 1) (not def-pkg))
17769 "" (org-latex-packages-to-string def-pkg snippets-p t))
17770 tpl (replace-match rpl t t tpl))
17771 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17773 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17774 (setq rpl (if (or (match-end 1) (not pkg))
17775 "" (org-latex-packages-to-string pkg snippets-p t))
17776 tpl (replace-match rpl t t tpl))
17777 (if pkg (setq end
17778 (concat end "\n"
17779 (org-latex-packages-to-string pkg snippets-p)))))
17781 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17782 (setq rpl (if (or (match-end 1) (not extra))
17783 "" (concat extra "\n"))
17784 tpl (replace-match rpl t t tpl))
17785 (if (and extra (string-match "\\S-" extra))
17786 (setq end (concat end "\n" extra))))
17788 (if (string-match "\\S-" end)
17789 (concat tpl "\n" end)
17790 tpl)))
17792 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17793 "Turn an alist of packages into a string with the \\usepackage macros."
17794 (setq pkg (mapconcat (lambda(p)
17795 (cond
17796 ((stringp p) p)
17797 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17798 (format "%% Package %s omitted" (cadr p)))
17799 ((equal "" (car p))
17800 (format "\\usepackage{%s}" (cadr p)))
17802 (format "\\usepackage[%s]{%s}"
17803 (car p) (cadr p)))))
17805 "\n"))
17806 (if newline (concat pkg "\n") pkg))
17808 (defun org-dvipng-color (attr)
17809 "Return a RGB color specification for dvipng."
17810 (apply 'format "rgb %s %s %s"
17811 (mapcar 'org-normalize-color
17812 (if (featurep 'xemacs)
17813 (color-rgb-components
17814 (face-property 'default
17815 (cond ((eq attr :foreground) 'foreground)
17816 ((eq attr :background) 'background))))
17817 (color-values (face-attribute 'default attr nil))))))
17819 (defun org-latex-color (attr)
17820 "Return a RGB color for the LaTeX color package."
17821 (apply 'format "%s,%s,%s"
17822 (mapcar 'org-normalize-color
17823 (if (featurep 'xemacs)
17824 (color-rgb-components
17825 (face-property 'default
17826 (cond ((eq attr :foreground) 'foreground)
17827 ((eq attr :background) 'background))))
17828 (color-values (face-attribute 'default attr nil))))))
17830 (defun org-latex-color-format (color-name)
17831 "Convert COLOR-NAME to a RGB color value."
17832 (apply 'format "%s,%s,%s"
17833 (mapcar 'org-normalize-color
17834 (color-values color-name))))
17836 (defun org-normalize-color (value)
17837 "Return string to be used as color value for an RGB component."
17838 (format "%g" (/ value 65535.0)))
17840 ;; Image display
17843 (defvar org-inline-image-overlays nil)
17844 (make-variable-buffer-local 'org-inline-image-overlays)
17846 (defun org-toggle-inline-images (&optional include-linked)
17847 "Toggle the display of inline images.
17848 INCLUDE-LINKED is passed to `org-display-inline-images'."
17849 (interactive "P")
17850 (if org-inline-image-overlays
17851 (progn
17852 (org-remove-inline-images)
17853 (message "Inline image display turned off"))
17854 (org-display-inline-images include-linked)
17855 (if org-inline-image-overlays
17856 (message "%d images displayed inline"
17857 (length org-inline-image-overlays))
17858 (message "No images to display inline"))))
17860 (defun org-redisplay-inline-images ()
17861 "Refresh the display of inline images."
17862 (interactive)
17863 (if (not org-inline-image-overlays)
17864 (org-toggle-inline-images)
17865 (org-toggle-inline-images)
17866 (org-toggle-inline-images)))
17868 (defun org-display-inline-images (&optional include-linked refresh beg end)
17869 "Display inline images.
17870 Normally only links without a description part are inlined, because this
17871 is how it will work for export. When INCLUDE-LINKED is set, also links
17872 with a description part will be inlined. This can be nice for a quick
17873 look at those images, but it does not reflect what exported files will look
17874 like.
17875 When REFRESH is set, refresh existing images between BEG and END.
17876 This will create new image displays only if necessary.
17877 BEG and END default to the buffer boundaries."
17878 (interactive "P")
17879 (unless refresh
17880 (org-remove-inline-images)
17881 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17882 (save-excursion
17883 (save-restriction
17884 (widen)
17885 (setq beg (or beg (point-min)) end (or end (point-max)))
17886 (goto-char beg)
17887 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17888 (substring (org-image-file-name-regexp) 0 -2)
17889 "\\)\\]" (if include-linked "" "\\]")))
17890 old file ov img type attrwidth width)
17891 (while (re-search-forward re end t)
17892 (setq old (get-char-property-and-overlay (match-beginning 1)
17893 'org-image-overlay)
17894 file (expand-file-name
17895 (concat (or (match-string 3) "") (match-string 4))))
17896 (when (image-type-available-p 'imagemagick)
17897 (setq attrwidth (if (or (listp org-image-actual-width)
17898 (null org-image-actual-width))
17899 (save-excursion
17900 (save-match-data
17901 (move-beginning-of-line 0)
17902 (if (looking-at "#\\+ATTR.*width=\"\\([^\"]+\\)\"")
17903 (string-to-number (match-string 1))))))
17904 width (cond ((eq org-image-actual-width t) nil)
17905 ((null org-image-actual-width) attrwidth)
17906 ((numberp org-image-actual-width)
17907 org-image-actual-width)
17908 ((listp org-image-actual-width)
17909 (or attrwidth (car org-image-actual-width))))
17910 type (if width 'imagemagick)))
17911 (when (file-exists-p file)
17912 (if (and (car-safe old) refresh)
17913 (image-refresh (overlay-get (cdr old) 'display))
17914 (setq img (save-match-data (create-image file type nil :width width)))
17915 (when img
17916 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17917 (overlay-put ov 'display img)
17918 (overlay-put ov 'face 'default)
17919 (overlay-put ov 'org-image-overlay t)
17920 (overlay-put ov 'modification-hooks
17921 (list 'org-display-inline-modification-hook))
17922 (push ov org-inline-image-overlays)))))))))
17924 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17925 "Remove inline-display overlay if a corresponding region is modified."
17926 (let ((inhibit-modification-hooks t))
17927 (when (and ov after)
17928 (delete ov org-inline-image-overlays)
17929 (delete-overlay ov))))
17931 (defun org-remove-inline-images ()
17932 "Remove inline display of images."
17933 (interactive)
17934 (mapc 'delete-overlay org-inline-image-overlays)
17935 (setq org-inline-image-overlays nil))
17937 ;;;; Key bindings
17939 ;; Outline functions from `outline-mode-prefix-map'
17940 ;; that can be remapped in Org:
17941 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17942 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17943 (define-key org-mode-map [remap outline-forward-same-level]
17944 'org-forward-heading-same-level)
17945 (define-key org-mode-map [remap outline-backward-same-level]
17946 'org-backward-heading-same-level)
17947 (define-key org-mode-map [remap show-branches]
17948 'org-kill-note-or-show-branches)
17949 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17950 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17951 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17953 ;; Outline functions from `outline-mode-prefix-map' that can not
17954 ;; be remapped in Org:
17956 ;; - the column "key binding" shows whether the Outline function is still
17957 ;; available in Org mode on the same key that it has been bound to in
17958 ;; Outline mode:
17959 ;; - "overridden": key used for a different functionality in Org mode
17960 ;; - else: key still bound to the same Outline function in Org mode
17962 ;; | Outline function | key binding | Org replacement |
17963 ;; |------------------------------------+-------------+-----------------------|
17964 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17965 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17966 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17967 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17968 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17969 ;; | `show-entry' | overridden | no replacement |
17970 ;; | `show-children' | `C-c C-i' | visibility cycling |
17971 ;; | `show-branches' | `C-c C-k' | still same function |
17972 ;; | `show-subtree' | overridden | visibility cycling |
17973 ;; | `show-all' | overridden | no replacement |
17974 ;; | `hide-subtree' | overridden | visibility cycling |
17975 ;; | `hide-body' | overridden | no replacement |
17976 ;; | `hide-entry' | overridden | visibility cycling |
17977 ;; | `hide-leaves' | overridden | no replacement |
17978 ;; | `hide-sublevels' | overridden | no replacement |
17979 ;; | `hide-other' | overridden | no replacement |
17981 ;; Make `C-c C-x' a prefix key
17982 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17984 ;; TAB key with modifiers
17985 (org-defkey org-mode-map "\C-i" 'org-cycle)
17986 (org-defkey org-mode-map [(tab)] 'org-cycle)
17987 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17988 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17989 ;; The following line is necessary under Suse GNU/Linux
17990 (unless (featurep 'xemacs)
17991 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17992 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17993 (define-key org-mode-map [backtab] 'org-shifttab)
17995 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17996 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17997 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17999 ;; Cursor keys with modifiers
18000 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18001 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18002 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18003 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18005 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18006 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18007 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18008 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18010 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18011 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18012 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18013 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18015 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18016 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18017 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18018 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18020 ;; Babel keys
18021 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18022 (mapc (lambda (pair)
18023 (define-key org-babel-map (car pair) (cdr pair)))
18024 org-babel-key-bindings)
18026 ;;; Extra keys for tty access.
18027 ;; We only set them when really needed because otherwise the
18028 ;; menus don't show the simple keys
18030 (when (or org-use-extra-keys
18031 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18032 (not window-system))
18033 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18034 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18035 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18036 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18037 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18038 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18039 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18040 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18041 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18042 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18043 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18044 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18045 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18046 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18047 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18048 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18049 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18050 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18051 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18052 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18053 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18054 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18055 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18056 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18057 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18058 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18059 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18060 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18062 ;; All the other keys
18064 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18065 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18066 (if (boundp 'narrow-map)
18067 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18068 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18069 (if (boundp 'narrow-map)
18070 (org-defkey narrow-map "b" 'org-narrow-to-block)
18071 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18072 (if (boundp 'narrow-map)
18073 (org-defkey narrow-map "e" 'org-narrow-to-element)
18074 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18075 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18076 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18077 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18078 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18079 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18080 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18081 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18082 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18083 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18084 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18085 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18086 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18087 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18088 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18089 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18090 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18091 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18092 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18093 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18094 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18095 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18096 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18097 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18098 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18099 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18100 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18101 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18102 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18103 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18104 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18105 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18106 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18107 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18108 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18109 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18110 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18111 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18112 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18113 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18114 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18115 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18116 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18117 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18118 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18119 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18120 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18121 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18122 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18123 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18124 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18125 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18126 (org-defkey org-mode-map "\C-c^" 'org-sort)
18127 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18128 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18129 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18130 (org-defkey org-mode-map "\C-m" 'org-return)
18131 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18132 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18133 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18134 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18135 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18136 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18137 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18138 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18139 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18140 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18141 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18142 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18143 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18144 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18145 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18146 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18147 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18148 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18149 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18150 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18151 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18152 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18153 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18155 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18156 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18157 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18158 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18160 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18161 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18162 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18163 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18164 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18165 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18166 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18167 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18168 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18169 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18170 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18171 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18172 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18173 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18174 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18175 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18176 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18177 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18178 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18179 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18180 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18181 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18183 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18184 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18185 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18186 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18187 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18189 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18191 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18193 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18194 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18196 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18199 (when (featurep 'xemacs)
18200 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18203 (defconst org-speed-commands-default
18205 ("Outline Navigation")
18206 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18207 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18208 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18209 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18210 ("u" . (org-speed-move-safe 'outline-up-heading))
18211 ("j" . org-goto)
18212 ("g" . (org-refile t))
18213 ("Outline Visibility")
18214 ("c" . org-cycle)
18215 ("C" . org-shifttab)
18216 (" " . org-display-outline-path)
18217 (":" . org-columns)
18218 ("Outline Structure Editing")
18219 ("U" . org-shiftmetaup)
18220 ("D" . org-shiftmetadown)
18221 ("r" . org-metaright)
18222 ("l" . org-metaleft)
18223 ("R" . org-shiftmetaright)
18224 ("L" . org-shiftmetaleft)
18225 ("i" . (progn (forward-char 1) (call-interactively
18226 'org-insert-heading-respect-content)))
18227 ("^" . org-sort)
18228 ("w" . org-refile)
18229 ("a" . org-archive-subtree-default-with-confirmation)
18230 ("." . org-mark-subtree)
18231 ("#" . org-toggle-comment)
18232 ("Clock Commands")
18233 ("I" . org-clock-in)
18234 ("O" . org-clock-out)
18235 ("Meta Data Editing")
18236 ("t" . org-todo)
18237 ("0" . (org-priority ?\ ))
18238 ("1" . (org-priority ?A))
18239 ("2" . (org-priority ?B))
18240 ("3" . (org-priority ?C))
18241 (";" . org-set-tags-command)
18242 ("e" . org-set-effort)
18243 ("E" . org-inc-effort)
18244 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18245 (org-entry-put (point) "APPT_WARNTIME" m)))
18246 ("Agenda Views etc")
18247 ("v" . org-agenda)
18248 ("/" . org-sparse-tree)
18249 ("Misc")
18250 ("o" . org-open-at-point)
18251 ("?" . org-speed-command-help)
18252 ("<" . (org-agenda-set-restriction-lock 'subtree))
18253 (">" . (org-agenda-remove-restriction-lock))
18255 "The default speed commands.")
18257 (defun org-print-speed-command (e)
18258 (if (> (length (car e)) 1)
18259 (progn
18260 (princ "\n")
18261 (princ (car e))
18262 (princ "\n")
18263 (princ (make-string (length (car e)) ?-))
18264 (princ "\n"))
18265 (princ (car e))
18266 (princ " ")
18267 (if (symbolp (cdr e))
18268 (princ (symbol-name (cdr e)))
18269 (prin1 (cdr e)))
18270 (princ "\n")))
18272 (defun org-speed-command-help ()
18273 "Show the available speed commands."
18274 (interactive)
18275 (if (not org-use-speed-commands)
18276 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18277 (with-output-to-temp-buffer "*Help*"
18278 (princ "User-defined Speed commands\n===========================\n")
18279 (mapc 'org-print-speed-command org-speed-commands-user)
18280 (princ "\n")
18281 (princ "Built-in Speed commands\n=======================\n")
18282 (mapc 'org-print-speed-command org-speed-commands-default))
18283 (with-current-buffer "*Help*"
18284 (setq truncate-lines t))))
18286 (defun org-speed-move-safe (cmd)
18287 "Execute CMD, but make sure that the cursor always ends up in a headline.
18288 If not, return to the original position and throw an error."
18289 (interactive)
18290 (let ((pos (point)))
18291 (call-interactively cmd)
18292 (unless (and (bolp) (org-at-heading-p))
18293 (goto-char pos)
18294 (error "Boundary reached while executing %s" cmd))))
18296 (defvar org-self-insert-command-undo-counter 0)
18298 (defvar org-table-auto-blank-field) ; defined in org-table.el
18299 (defvar org-speed-command nil)
18301 (defun org-speed-command-default-hook (keys)
18302 "Hook for activating single-letter speed commands.
18303 `org-speed-commands-default' specifies a minimal command set.
18304 Use `org-speed-commands-user' for further customization."
18305 (when (or (and (bolp) (looking-at org-outline-regexp))
18306 (and (functionp org-use-speed-commands)
18307 (funcall org-use-speed-commands)))
18308 (cdr (assoc keys (append org-speed-commands-user
18309 org-speed-commands-default)))))
18311 (defun org-babel-speed-command-hook (keys)
18312 "Hook for activating single-letter code block commands."
18313 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18314 (cdr (assoc keys org-babel-key-bindings))))
18316 (defcustom org-speed-command-hook
18317 '(org-speed-command-default-hook org-babel-speed-command-hook)
18318 "Hook for activating speed commands at strategic locations.
18319 Hook functions are called in sequence until a valid handler is
18320 found.
18322 Each hook takes a single argument, a user-pressed command key
18323 which is also a `self-insert-command' from the global map.
18325 Within the hook, examine the cursor position and the command key
18326 and return nil or a valid handler as appropriate. Handler could
18327 be one of an interactive command, a function, or a form.
18329 Set `org-use-speed-commands' to non-nil value to enable this
18330 hook. The default setting is `org-speed-command-default-hook'."
18331 :group 'org-structure
18332 :version "24.1"
18333 :type 'hook)
18335 (defun org-self-insert-command (N)
18336 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18337 If the cursor is in a table looking at whitespace, the whitespace is
18338 overwritten, and the table is not marked as requiring realignment."
18339 (interactive "p")
18340 (org-check-before-invisible-edit 'insert)
18341 (cond
18342 ((and org-use-speed-commands
18343 (setq org-speed-command
18344 (run-hook-with-args-until-success
18345 'org-speed-command-hook (this-command-keys))))
18346 (cond
18347 ((commandp org-speed-command)
18348 (setq this-command org-speed-command)
18349 (call-interactively org-speed-command))
18350 ((functionp org-speed-command)
18351 (funcall org-speed-command))
18352 ((and org-speed-command (listp org-speed-command))
18353 (eval org-speed-command))
18354 (t (let (org-use-speed-commands)
18355 (call-interactively 'org-self-insert-command)))))
18356 ((and
18357 (org-table-p)
18358 (progn
18359 ;; check if we blank the field, and if that triggers align
18360 (and (featurep 'org-table) org-table-auto-blank-field
18361 (member last-command
18362 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18363 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18364 ;; got extra space, this field does not determine column width
18365 (let (org-table-may-need-update) (org-table-blank-field))
18366 ;; no extra space, this field may determine column width
18367 (org-table-blank-field)))
18369 (eq N 1)
18370 (looking-at "[^|\n]* |"))
18371 (let (org-table-may-need-update)
18372 (goto-char (1- (match-end 0)))
18373 (backward-delete-char 1)
18374 (goto-char (match-beginning 0))
18375 (self-insert-command N)))
18377 (setq org-table-may-need-update t)
18378 (self-insert-command N)
18379 (org-fix-tags-on-the-fly)
18380 (if org-self-insert-cluster-for-undo
18381 (if (not (eq last-command 'org-self-insert-command))
18382 (setq org-self-insert-command-undo-counter 1)
18383 (if (>= org-self-insert-command-undo-counter 20)
18384 (setq org-self-insert-command-undo-counter 1)
18385 (and (> org-self-insert-command-undo-counter 0)
18386 buffer-undo-list (listp buffer-undo-list)
18387 (not (cadr buffer-undo-list)) ; remove nil entry
18388 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18389 (setq org-self-insert-command-undo-counter
18390 (1+ org-self-insert-command-undo-counter))))))))
18392 (defun org-check-before-invisible-edit (kind)
18393 "Check is editing if kind KIND would be dangerous with invisible text around.
18394 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18395 ;; First, try to get out of here as quickly as possible, to reduce overhead
18396 (if (and org-catch-invisible-edits
18397 (or (not (boundp 'visible-mode)) (not visible-mode))
18398 (or (get-char-property (point) 'invisible)
18399 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18400 ;; OK, we need to take a closer look
18401 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18402 (invisible-before-point (if (bobp) nil (get-char-property
18403 (1- (point)) 'invisible)))
18404 (border-and-ok-direction
18406 ;; Check if we are acting predictably before invisible text
18407 (and invisible-at-point (not invisible-before-point)
18408 (memq kind '(insert delete-backward)))
18409 ;; Check if we are acting predictably after invisible text
18410 ;; This works not well, and I have turned it off. It seems
18411 ;; better to always show and stop after invisible text.
18412 ;; (and (not invisible-at-point) invisible-before-point
18413 ;; (memq kind '(insert delete)))
18415 (when (or (memq invisible-at-point '(outline org-hide-block t))
18416 (memq invisible-before-point '(outline org-hide-block t)))
18417 (if (eq org-catch-invisible-edits 'error)
18418 (error "Editing in invisible areas is prohibited - make visible first"))
18419 (if (and org-custom-properties-overlays
18420 (y-or-n-p "Display invisible properties in this buffer? "))
18421 (org-toggle-custom-properties-visibility)
18422 ;; Make the area visible
18423 (save-excursion
18424 (if invisible-before-point
18425 (goto-char (previous-single-char-property-change
18426 (point) 'invisible)))
18427 (org-cycle))
18428 (cond
18429 ((eq org-catch-invisible-edits 'show)
18430 ;; That's it, we do the edit after showing
18431 (message
18432 "Unfolding invisible region around point before editing")
18433 (sit-for 1))
18434 ((and (eq org-catch-invisible-edits 'smart)
18435 border-and-ok-direction)
18436 (message "Unfolding invisible region around point before editing"))
18438 ;; Don't do the edit, make the user repeat it in full visibility
18439 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18441 (defun org-fix-tags-on-the-fly ()
18442 (when (and (equal (char-after (point-at-bol)) ?*)
18443 (org-at-heading-p))
18444 (org-align-tags-here org-tags-column)))
18446 (defun org-delete-backward-char (N)
18447 "Like `delete-backward-char', insert whitespace at field end in tables.
18448 When deleting backwards, in tables this function will insert whitespace in
18449 front of the next \"|\" separator, to keep the table aligned. The table will
18450 still be marked for re-alignment if the field did fill the entire column,
18451 because, in this case the deletion might narrow the column."
18452 (interactive "p")
18453 (org-check-before-invisible-edit 'delete-backward)
18454 (if (and (org-table-p)
18455 (eq N 1)
18456 (string-match "|" (buffer-substring (point-at-bol) (point)))
18457 (looking-at ".*?|"))
18458 (let ((pos (point))
18459 (noalign (looking-at "[^|\n\r]* |"))
18460 (c org-table-may-need-update))
18461 (backward-delete-char N)
18462 (if (not overwrite-mode)
18463 (progn
18464 (skip-chars-forward "^|")
18465 (insert " ")
18466 (goto-char (1- pos))))
18467 ;; noalign: if there were two spaces at the end, this field
18468 ;; does not determine the width of the column.
18469 (if noalign (setq org-table-may-need-update c)))
18470 (backward-delete-char N)
18471 (org-fix-tags-on-the-fly)))
18473 (defun org-delete-char (N)
18474 "Like `delete-char', but insert whitespace at field end in tables.
18475 When deleting characters, in tables this function will insert whitespace in
18476 front of the next \"|\" separator, to keep the table aligned. The table will
18477 still be marked for re-alignment if the field did fill the entire column,
18478 because, in this case the deletion might narrow the column."
18479 (interactive "p")
18480 (org-check-before-invisible-edit 'delete)
18481 (if (and (org-table-p)
18482 (not (bolp))
18483 (not (= (char-after) ?|))
18484 (eq N 1))
18485 (if (looking-at ".*?|")
18486 (let ((pos (point))
18487 (noalign (looking-at "[^|\n\r]* |"))
18488 (c org-table-may-need-update))
18489 (replace-match (concat
18490 (substring (match-string 0) 1 -1)
18491 " |"))
18492 (goto-char pos)
18493 ;; noalign: if there were two spaces at the end, this field
18494 ;; does not determine the width of the column.
18495 (if noalign (setq org-table-may-need-update c)))
18496 (delete-char N))
18497 (delete-char N)
18498 (org-fix-tags-on-the-fly)))
18500 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18501 (put 'org-self-insert-command 'delete-selection t)
18502 (put 'orgtbl-self-insert-command 'delete-selection t)
18503 (put 'org-delete-char 'delete-selection 'supersede)
18504 (put 'org-delete-backward-char 'delete-selection 'supersede)
18505 (put 'org-yank 'delete-selection 'yank)
18507 ;; Make `flyspell-mode' delay after some commands
18508 (put 'org-self-insert-command 'flyspell-delayed t)
18509 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18510 (put 'org-delete-char 'flyspell-delayed t)
18511 (put 'org-delete-backward-char 'flyspell-delayed t)
18513 ;; Make pabbrev-mode expand after org-mode commands
18514 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18515 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18517 ;; How to do this: Measure non-white length of current string
18518 ;; If equal to column width, we should realign.
18520 (defun org-remap (map &rest commands)
18521 "In MAP, remap the functions given in COMMANDS.
18522 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18523 (let (new old)
18524 (while commands
18525 (setq old (pop commands) new (pop commands))
18526 (if (fboundp 'command-remapping)
18527 (org-defkey map (vector 'remap old) new)
18528 (substitute-key-definition old new map global-map)))))
18530 (when (eq org-enable-table-editor 'optimized)
18531 ;; If the user wants maximum table support, we need to hijack
18532 ;; some standard editing functions
18533 (org-remap org-mode-map
18534 'self-insert-command 'org-self-insert-command
18535 'delete-char 'org-delete-char
18536 'delete-backward-char 'org-delete-backward-char)
18537 (org-defkey org-mode-map "|" 'org-force-self-insert))
18539 (defvar org-ctrl-c-ctrl-c-hook nil
18540 "Hook for functions attaching themselves to `C-c C-c'.
18542 This can be used to add additional functionality to the C-c C-c
18543 key which executes context-dependent commands. This hook is run
18544 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18545 run after the last test.
18547 Each function will be called with no arguments. The function
18548 must check if the context is appropriate for it to act. If yes,
18549 it should do its thing and then return a non-nil value. If the
18550 context is wrong, just do nothing and return nil.")
18552 (defvar org-ctrl-c-ctrl-c-final-hook nil
18553 "Hook for functions attaching themselves to `C-c C-c'.
18555 This can be used to add additional functionality to the C-c C-c
18556 key which executes context-dependent commands. This hook is run
18557 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18558 before the first test.
18560 Each function will be called with no arguments. The function
18561 must check if the context is appropriate for it to act. If yes,
18562 it should do its thing and then return a non-nil value. If the
18563 context is wrong, just do nothing and return nil.")
18565 (defvar org-tab-first-hook nil
18566 "Hook for functions to attach themselves to TAB.
18567 See `org-ctrl-c-ctrl-c-hook' for more information.
18568 This hook runs as the first action when TAB is pressed, even before
18569 `org-cycle' messes around with the `outline-regexp' to cater for
18570 inline tasks and plain list item folding.
18571 If any function in this hook returns t, any other actions that
18572 would have been caused by TAB (such as table field motion or visibility
18573 cycling) will not occur.")
18575 (defvar org-tab-after-check-for-table-hook nil
18576 "Hook for functions to attach themselves to TAB.
18577 See `org-ctrl-c-ctrl-c-hook' for more information.
18578 This hook runs after it has been established that the cursor is not in a
18579 table, but before checking if the cursor is in a headline or if global cycling
18580 should be done.
18581 If any function in this hook returns t, not other actions like visibility
18582 cycling will be done.")
18584 (defvar org-tab-after-check-for-cycling-hook nil
18585 "Hook for functions to attach themselves to TAB.
18586 See `org-ctrl-c-ctrl-c-hook' for more information.
18587 This hook runs after it has been established that not table field motion and
18588 not visibility should be done because of current context. This is probably
18589 the place where a package like yasnippets can hook in.")
18591 (defvar org-tab-before-tab-emulation-hook nil
18592 "Hook for functions to attach themselves to TAB.
18593 See `org-ctrl-c-ctrl-c-hook' for more information.
18594 This hook runs after every other options for TAB have been exhausted, but
18595 before indentation and \t insertion takes place.")
18597 (defvar org-metaleft-hook nil
18598 "Hook for functions attaching themselves to `M-left'.
18599 See `org-ctrl-c-ctrl-c-hook' for more information.")
18600 (defvar org-metaright-hook nil
18601 "Hook for functions attaching themselves to `M-right'.
18602 See `org-ctrl-c-ctrl-c-hook' for more information.")
18603 (defvar org-metaup-hook nil
18604 "Hook for functions attaching themselves to `M-up'.
18605 See `org-ctrl-c-ctrl-c-hook' for more information.")
18606 (defvar org-metadown-hook nil
18607 "Hook for functions attaching themselves to `M-down'.
18608 See `org-ctrl-c-ctrl-c-hook' for more information.")
18609 (defvar org-shiftmetaleft-hook nil
18610 "Hook for functions attaching themselves to `M-S-left'.
18611 See `org-ctrl-c-ctrl-c-hook' for more information.")
18612 (defvar org-shiftmetaright-hook nil
18613 "Hook for functions attaching themselves to `M-S-right'.
18614 See `org-ctrl-c-ctrl-c-hook' for more information.")
18615 (defvar org-shiftmetaup-hook nil
18616 "Hook for functions attaching themselves to `M-S-up'.
18617 See `org-ctrl-c-ctrl-c-hook' for more information.")
18618 (defvar org-shiftmetadown-hook nil
18619 "Hook for functions attaching themselves to `M-S-down'.
18620 See `org-ctrl-c-ctrl-c-hook' for more information.")
18621 (defvar org-metareturn-hook nil
18622 "Hook for functions attaching themselves to `M-RET'.
18623 See `org-ctrl-c-ctrl-c-hook' for more information.")
18624 (defvar org-shiftup-hook nil
18625 "Hook for functions attaching themselves to `S-up'.
18626 See `org-ctrl-c-ctrl-c-hook' for more information.")
18627 (defvar org-shiftup-final-hook nil
18628 "Hook for functions attaching themselves to `S-up'.
18629 This one runs after all other options except shift-select have been excluded.
18630 See `org-ctrl-c-ctrl-c-hook' for more information.")
18631 (defvar org-shiftdown-hook nil
18632 "Hook for functions attaching themselves to `S-down'.
18633 See `org-ctrl-c-ctrl-c-hook' for more information.")
18634 (defvar org-shiftdown-final-hook nil
18635 "Hook for functions attaching themselves to `S-down'.
18636 This one runs after all other options except shift-select have been excluded.
18637 See `org-ctrl-c-ctrl-c-hook' for more information.")
18638 (defvar org-shiftleft-hook nil
18639 "Hook for functions attaching themselves to `S-left'.
18640 See `org-ctrl-c-ctrl-c-hook' for more information.")
18641 (defvar org-shiftleft-final-hook nil
18642 "Hook for functions attaching themselves to `S-left'.
18643 This one runs after all other options except shift-select have been excluded.
18644 See `org-ctrl-c-ctrl-c-hook' for more information.")
18645 (defvar org-shiftright-hook nil
18646 "Hook for functions attaching themselves to `S-right'.
18647 See `org-ctrl-c-ctrl-c-hook' for more information.")
18648 (defvar org-shiftright-final-hook nil
18649 "Hook for functions attaching themselves to `S-right'.
18650 This one runs after all other options except shift-select have been excluded.
18651 See `org-ctrl-c-ctrl-c-hook' for more information.")
18653 (defun org-modifier-cursor-error ()
18654 "Throw an error, a modified cursor command was applied in wrong context."
18655 (error "This command is active in special context like tables, headlines or items"))
18657 (defun org-shiftselect-error ()
18658 "Throw an error because Shift-Cursor command was applied in wrong context."
18659 (if (and (boundp 'shift-select-mode) shift-select-mode)
18660 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18661 (error "This command works only in special context like headlines or timestamps")))
18663 (defun org-call-for-shift-select (cmd)
18664 (let ((this-command-keys-shift-translated t))
18665 (call-interactively cmd)))
18667 (defun org-shifttab (&optional arg)
18668 "Global visibility cycling or move to previous table field.
18669 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18670 on context.
18671 See the individual commands for more information."
18672 (interactive "P")
18673 (cond
18674 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18675 ((integerp arg)
18676 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18677 (message "Content view to level: %d" arg)
18678 (org-content (prefix-numeric-value arg2))
18679 (setq org-cycle-global-status 'overview)))
18680 (t (call-interactively 'org-global-cycle))))
18682 (defun org-shiftmetaleft ()
18683 "Promote subtree or delete table column.
18684 Calls `org-promote-subtree', `org-outdent-item-tree', or
18685 `org-table-delete-column', depending on context. See the
18686 individual commands for more information."
18687 (interactive)
18688 (cond
18689 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18690 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18691 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18692 ((if (not (org-region-active-p)) (org-at-item-p)
18693 (save-excursion (goto-char (region-beginning))
18694 (org-at-item-p)))
18695 (call-interactively 'org-outdent-item-tree))
18696 (t (org-modifier-cursor-error))))
18698 (defun org-shiftmetaright ()
18699 "Demote subtree or insert table column.
18700 Calls `org-demote-subtree', `org-indent-item-tree', or
18701 `org-table-insert-column', depending on context. See the
18702 individual commands for more information."
18703 (interactive)
18704 (cond
18705 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18706 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18707 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18708 ((if (not (org-region-active-p)) (org-at-item-p)
18709 (save-excursion (goto-char (region-beginning))
18710 (org-at-item-p)))
18711 (call-interactively 'org-indent-item-tree))
18712 (t (org-modifier-cursor-error))))
18714 (defun org-shiftmetaup (&optional arg)
18715 "Move subtree up or kill table row.
18716 Calls `org-move-subtree-up' or `org-table-kill-row' or
18717 `org-move-item-up' or `org-timestamp-up', depending on context.
18718 See the individual commands for more information."
18719 (interactive "P")
18720 (cond
18721 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18722 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18723 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18724 ((org-at-item-p) (call-interactively 'org-move-item-up))
18725 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18726 (call-interactively 'org-timestamp-up)))
18727 (t (org-modifier-cursor-error))))
18729 (defun org-shiftmetadown (&optional arg)
18730 "Move subtree down or insert table row.
18731 Calls `org-move-subtree-down' or `org-table-insert-row' or
18732 `org-move-item-down' or `org-timestamp-up', depending on context.
18733 See the individual commands for more information."
18734 (interactive "P")
18735 (cond
18736 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18737 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18738 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18739 ((org-at-item-p) (call-interactively 'org-move-item-down))
18740 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18741 (call-interactively 'org-timestamp-down)))
18742 (t (org-modifier-cursor-error))))
18744 (defsubst org-hidden-tree-error ()
18745 (error
18746 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18748 (defun org-metaleft (&optional arg)
18749 "Promote heading or move table column to left.
18750 Calls `org-do-promote' or `org-table-move-column', depending on context.
18751 With no specific context, calls the Emacs default `backward-word'.
18752 See the individual commands for more information."
18753 (interactive "P")
18754 (cond
18755 ((run-hook-with-args-until-success 'org-metaleft-hook))
18756 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18757 ((org-with-limited-levels
18758 (or (org-at-heading-p)
18759 (and (org-region-active-p)
18760 (save-excursion
18761 (goto-char (region-beginning))
18762 (org-at-heading-p)))))
18763 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18764 (call-interactively 'org-do-promote))
18765 ;; At an inline task.
18766 ((org-at-heading-p)
18767 (call-interactively 'org-inlinetask-promote))
18768 ((or (org-at-item-p)
18769 (and (org-region-active-p)
18770 (save-excursion
18771 (goto-char (region-beginning))
18772 (org-at-item-p))))
18773 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18774 (call-interactively 'org-outdent-item))
18775 (t (call-interactively 'backward-word))))
18777 (defun org-metaright (&optional arg)
18778 "Demote a subtree, a list item or move table column to right.
18779 In front of a drawer or a block keyword, indent it correctly.
18780 With no specific context, calls the Emacs default `forward-word'.
18781 See the individual commands for more information."
18782 (interactive "P")
18783 (cond
18784 ((run-hook-with-args-until-success 'org-metaright-hook))
18785 ((org-at-table-p) (call-interactively 'org-table-move-column))
18786 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18787 ((org-at-block-p) (call-interactively 'org-indent-block))
18788 ((org-with-limited-levels
18789 (or (org-at-heading-p)
18790 (and (org-region-active-p)
18791 (save-excursion
18792 (goto-char (region-beginning))
18793 (org-at-heading-p)))))
18794 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18795 (call-interactively 'org-do-demote))
18796 ;; At an inline task.
18797 ((org-at-heading-p)
18798 (call-interactively 'org-inlinetask-demote))
18799 ((or (org-at-item-p)
18800 (and (org-region-active-p)
18801 (save-excursion
18802 (goto-char (region-beginning))
18803 (org-at-item-p))))
18804 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18805 (call-interactively 'org-indent-item))
18806 (t (call-interactively 'forward-word))))
18808 (defun org-check-for-hidden (what)
18809 "Check if there are hidden headlines/items in the current visual line.
18810 WHAT can be either `headlines' or `items'. If the current line is
18811 an outline or item heading and it has a folded subtree below it,
18812 this function returns t, nil otherwise."
18813 (let ((re (cond
18814 ((eq what 'headlines) org-outline-regexp-bol)
18815 ((eq what 'items) (org-item-beginning-re))
18816 (t (error "This should not happen"))))
18817 beg end)
18818 (save-excursion
18819 (catch 'exit
18820 (unless (org-region-active-p)
18821 (setq beg (point-at-bol))
18822 (beginning-of-line 2)
18823 (while (and (not (eobp)) ;; this is like `next-line'
18824 (get-char-property (1- (point)) 'invisible))
18825 (beginning-of-line 2))
18826 (setq end (point))
18827 (goto-char beg)
18828 (goto-char (point-at-eol))
18829 (setq end (max end (point)))
18830 (while (re-search-forward re end t)
18831 (if (get-char-property (match-beginning 0) 'invisible)
18832 (throw 'exit t))))
18833 nil))))
18835 (autoload 'org-element-at-point "org-element")
18837 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18838 (declare-function org-element-type "org-element" (element))
18839 (declare-function org-element-contents "org-element" (element))
18840 (declare-function org-element-property "org-element" (property element))
18841 (declare-function org-element-paragraph-parser "org-element" (limit))
18842 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18843 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18844 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18845 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18846 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18848 (defun org-metaup (&optional arg)
18849 "Move subtree up or move table row up.
18850 Calls `org-move-subtree-up' or `org-table-move-row' or
18851 `org-move-item-up', depending on context. See the individual commands
18852 for more information."
18853 (interactive "P")
18854 (cond
18855 ((run-hook-with-args-until-success 'org-metaup-hook))
18856 ((org-region-active-p)
18857 (let* ((a (min (region-beginning) (region-end)))
18858 (b (1- (max (region-beginning) (region-end))))
18859 (c (save-excursion (goto-char a)
18860 (move-beginning-of-line 0)))
18861 (d (save-excursion (goto-char a)
18862 (move-end-of-line 0) (point))))
18863 (transpose-regions a b c d)
18864 (goto-char c)))
18865 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18866 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18867 ((org-at-item-p) (call-interactively 'org-move-item-up))
18868 (t (org-drag-element-backward))))
18870 (defun org-metadown (&optional arg)
18871 "Move subtree down or move table row down.
18872 Calls `org-move-subtree-down' or `org-table-move-row' or
18873 `org-move-item-down', depending on context. See the individual
18874 commands for more information."
18875 (interactive "P")
18876 (cond
18877 ((run-hook-with-args-until-success 'org-metadown-hook))
18878 ((org-region-active-p)
18879 (let* ((a (min (region-beginning) (region-end)))
18880 (b (max (region-beginning) (region-end)))
18881 (c (save-excursion (goto-char b)
18882 (move-beginning-of-line 1)))
18883 (d (save-excursion (goto-char b)
18884 (move-end-of-line 1) (1+ (point)))))
18885 (transpose-regions a b c d)
18886 (goto-char d)))
18887 ((org-at-table-p) (call-interactively 'org-table-move-row))
18888 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18889 ((org-at-item-p) (call-interactively 'org-move-item-down))
18890 (t (org-drag-element-forward))))
18892 (defun org-shiftup (&optional arg)
18893 "Increase item in timestamp or increase priority of current headline.
18894 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18895 depending on context. See the individual commands for more information."
18896 (interactive "P")
18897 (cond
18898 ((run-hook-with-args-until-success 'org-shiftup-hook))
18899 ((and org-support-shift-select (org-region-active-p))
18900 (org-call-for-shift-select 'previous-line))
18901 ((org-at-timestamp-p t)
18902 (call-interactively (if org-edit-timestamp-down-means-later
18903 'org-timestamp-down 'org-timestamp-up)))
18904 ((and (not (eq org-support-shift-select 'always))
18905 org-enable-priority-commands
18906 (org-at-heading-p))
18907 (call-interactively 'org-priority-up))
18908 ((and (not org-support-shift-select) (org-at-item-p))
18909 (call-interactively 'org-previous-item))
18910 ((org-clocktable-try-shift 'up arg))
18911 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18912 (org-support-shift-select
18913 (org-call-for-shift-select 'previous-line))
18914 (t (org-shiftselect-error))))
18916 (defun org-shiftdown (&optional arg)
18917 "Decrease item in timestamp or decrease priority of current headline.
18918 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18919 depending on context. See the individual commands for more information."
18920 (interactive "P")
18921 (cond
18922 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18923 ((and org-support-shift-select (org-region-active-p))
18924 (org-call-for-shift-select 'next-line))
18925 ((org-at-timestamp-p t)
18926 (call-interactively (if org-edit-timestamp-down-means-later
18927 'org-timestamp-up 'org-timestamp-down)))
18928 ((and (not (eq org-support-shift-select 'always))
18929 org-enable-priority-commands
18930 (org-at-heading-p))
18931 (call-interactively 'org-priority-down))
18932 ((and (not org-support-shift-select) (org-at-item-p))
18933 (call-interactively 'org-next-item))
18934 ((org-clocktable-try-shift 'down arg))
18935 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18936 (org-support-shift-select
18937 (org-call-for-shift-select 'next-line))
18938 (t (org-shiftselect-error))))
18940 (defun org-shiftright (&optional arg)
18941 "Cycle the thing at point or in the current line, depending on context.
18942 Depending on context, this does one of the following:
18944 - switch a timestamp at point one day into the future
18945 - on a headline, switch to the next TODO keyword.
18946 - on an item, switch entire list to the next bullet type
18947 - on a property line, switch to the next allowed value
18948 - on a clocktable definition line, move time block into the future"
18949 (interactive "P")
18950 (cond
18951 ((run-hook-with-args-until-success 'org-shiftright-hook))
18952 ((and org-support-shift-select (org-region-active-p))
18953 (org-call-for-shift-select 'forward-char))
18954 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18955 ((and (not (eq org-support-shift-select 'always))
18956 (org-at-heading-p))
18957 (let ((org-inhibit-logging
18958 (not org-treat-S-cursor-todo-selection-as-state-change))
18959 (org-inhibit-blocking
18960 (not org-treat-S-cursor-todo-selection-as-state-change)))
18961 (org-call-with-arg 'org-todo 'right)))
18962 ((or (and org-support-shift-select
18963 (not (eq org-support-shift-select 'always))
18964 (org-at-item-bullet-p))
18965 (and (not org-support-shift-select) (org-at-item-p)))
18966 (org-call-with-arg 'org-cycle-list-bullet nil))
18967 ((and (not (eq org-support-shift-select 'always))
18968 (org-at-property-p))
18969 (call-interactively 'org-property-next-allowed-value))
18970 ((org-clocktable-try-shift 'right arg))
18971 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18972 (org-support-shift-select
18973 (org-call-for-shift-select 'forward-char))
18974 (t (org-shiftselect-error))))
18976 (defun org-shiftleft (&optional arg)
18977 "Cycle the thing at point or in the current line, depending on context.
18978 Depending on context, this does one of the following:
18980 - switch a timestamp at point one day into the past
18981 - on a headline, switch to the previous TODO keyword.
18982 - on an item, switch entire list to the previous bullet type
18983 - on a property line, switch to the previous allowed value
18984 - on a clocktable definition line, move time block into the past"
18985 (interactive "P")
18986 (cond
18987 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18988 ((and org-support-shift-select (org-region-active-p))
18989 (org-call-for-shift-select 'backward-char))
18990 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18991 ((and (not (eq org-support-shift-select 'always))
18992 (org-at-heading-p))
18993 (let ((org-inhibit-logging
18994 (not org-treat-S-cursor-todo-selection-as-state-change))
18995 (org-inhibit-blocking
18996 (not org-treat-S-cursor-todo-selection-as-state-change)))
18997 (org-call-with-arg 'org-todo 'left)))
18998 ((or (and org-support-shift-select
18999 (not (eq org-support-shift-select 'always))
19000 (org-at-item-bullet-p))
19001 (and (not org-support-shift-select) (org-at-item-p)))
19002 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19003 ((and (not (eq org-support-shift-select 'always))
19004 (org-at-property-p))
19005 (call-interactively 'org-property-previous-allowed-value))
19006 ((org-clocktable-try-shift 'left arg))
19007 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19008 (org-support-shift-select
19009 (org-call-for-shift-select 'backward-char))
19010 (t (org-shiftselect-error))))
19012 (defun org-shiftcontrolright ()
19013 "Switch to next TODO set."
19014 (interactive)
19015 (cond
19016 ((and org-support-shift-select (org-region-active-p))
19017 (org-call-for-shift-select 'forward-word))
19018 ((and (not (eq org-support-shift-select 'always))
19019 (org-at-heading-p))
19020 (org-call-with-arg 'org-todo 'nextset))
19021 (org-support-shift-select
19022 (org-call-for-shift-select 'forward-word))
19023 (t (org-shiftselect-error))))
19025 (defun org-shiftcontrolleft ()
19026 "Switch to previous TODO set."
19027 (interactive)
19028 (cond
19029 ((and org-support-shift-select (org-region-active-p))
19030 (org-call-for-shift-select 'backward-word))
19031 ((and (not (eq org-support-shift-select 'always))
19032 (org-at-heading-p))
19033 (org-call-with-arg 'org-todo 'previousset))
19034 (org-support-shift-select
19035 (org-call-for-shift-select 'backward-word))
19036 (t (org-shiftselect-error))))
19038 (defun org-shiftcontrolup ()
19039 "Change timestamps synchronously up in CLOCK log lines."
19040 (interactive)
19041 (cond ((and (not org-support-shift-select)
19042 (org-at-clock-log-p)
19043 (org-at-timestamp-p t))
19044 (org-clock-timestamps-up))
19045 (t (org-shiftselect-error))))
19047 (defun org-shiftcontroldown ()
19048 "Change timestamps synchronously down in CLOCK log lines."
19049 (interactive)
19050 (cond ((and (not org-support-shift-select)
19051 (org-at-clock-log-p)
19052 (org-at-timestamp-p t))
19053 (org-clock-timestamps-down))
19054 (t (org-shiftselect-error))))
19056 (defun org-ctrl-c-ret ()
19057 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19058 (interactive)
19059 (cond
19060 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19061 (t (call-interactively 'org-insert-heading))))
19063 (defun org-find-visible ()
19064 (let ((s (point)))
19065 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19066 (get-char-property s 'invisible)))
19068 (defun org-find-invisible ()
19069 (let ((s (point)))
19070 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19071 (not (get-char-property s 'invisible))))
19074 (defun org-copy-visible (beg end)
19075 "Copy the visible parts of the region."
19076 (interactive "r")
19077 (let (snippets s)
19078 (save-excursion
19079 (save-restriction
19080 (narrow-to-region beg end)
19081 (setq s (goto-char (point-min)))
19082 (while (not (= (point) (point-max)))
19083 (goto-char (org-find-invisible))
19084 (push (buffer-substring s (point)) snippets)
19085 (setq s (goto-char (org-find-visible))))))
19086 (kill-new (apply 'concat (nreverse snippets)))))
19088 (defun org-copy-special ()
19089 "Copy region in table or copy current subtree.
19090 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19091 See the individual commands for more information."
19092 (interactive)
19093 (call-interactively
19094 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19096 (defun org-cut-special ()
19097 "Cut region in table or cut current subtree.
19098 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19099 See the individual commands for more information."
19100 (interactive)
19101 (call-interactively
19102 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19104 (defun org-paste-special (arg)
19105 "Paste rectangular region into table, or past subtree relative to level.
19106 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19107 See the individual commands for more information."
19108 (interactive "P")
19109 (if (org-at-table-p)
19110 (org-table-paste-rectangle)
19111 (org-paste-subtree arg)))
19113 (defun org-edit-special (&optional arg)
19114 "Call a special editor for the stuff at point.
19115 When at a table, call the formula editor with `org-table-edit-formulas'.
19116 When at the first line of an src example, call `org-edit-src-code'.
19117 When in an #+include line, visit the include file. Otherwise call
19118 `ffap' to visit the file at point."
19119 (interactive)
19120 ;; possibly prep session before editing source
19121 (when arg
19122 (let* ((info (org-babel-get-src-block-info))
19123 (lang (nth 0 info))
19124 (params (nth 2 info))
19125 (session (cdr (assoc :session params))))
19126 (when (and info session) ;; we are in a source-code block with a session
19127 (funcall
19128 (intern (concat "org-babel-prep-session:" lang)) session params))))
19129 (cond ;; proceed with `org-edit-special'
19130 ((save-excursion
19131 (beginning-of-line 1)
19132 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19133 (find-file (org-trim (match-string 1))))
19134 ((org-edit-src-code))
19135 ((org-edit-fixed-width-region))
19136 ((org-at-table.el-p)
19137 (org-edit-src-code))
19138 ((or (org-at-table-p)
19139 (save-excursion
19140 (beginning-of-line 1)
19141 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19142 (call-interactively 'org-table-edit-formulas))
19143 (t (call-interactively 'ffap))))
19145 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19146 (defun org-ctrl-c-ctrl-c (&optional arg)
19147 "Set tags in headline, or update according to changed information at point.
19149 This command does many different things, depending on context:
19151 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19152 this is what we do.
19154 - If the cursor is on a statistics cookie, update it.
19156 - If the cursor is in a headline, prompt for tags and insert them
19157 into the current line, aligned to `org-tags-column'. When called
19158 with prefix arg, realign all tags in the current buffer.
19160 - If the cursor is in one of the special #+KEYWORD lines, this
19161 triggers scanning the buffer for these lines and updating the
19162 information.
19164 - If the cursor is inside a table, realign the table. This command
19165 works even if the automatic table editor has been turned off.
19167 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19168 the entire table.
19170 - If the cursor is at a footnote reference or definition, jump to
19171 the corresponding definition or references, respectively.
19173 - If the cursor is a the beginning of a dynamic block, update it.
19175 - If the current buffer is a capture buffer, close note and file it.
19177 - If the cursor is on a <<<target>>>, update radio targets and
19178 corresponding links in this buffer.
19180 - If the cursor is on a numbered item in a plain list, renumber the
19181 ordered list.
19183 - If the cursor is on a checkbox, toggle it.
19185 - If the cursor is on a code block, evaluate it. The variable
19186 `org-confirm-babel-evaluate' can be used to control prompting
19187 before code block evaluation, by default every code block
19188 evaluation requires confirmation. Code block evaluation can be
19189 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19190 (interactive "P")
19191 (let ((org-enable-table-editor t))
19192 (cond
19193 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19194 org-occur-highlights
19195 org-latex-fragment-image-overlays)
19196 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19197 (org-remove-occur-highlights)
19198 (org-remove-latex-fragment-image-overlays)
19199 (message "Temporary highlights/overlays removed from current buffer"))
19200 ((and (local-variable-p 'org-finish-function (current-buffer))
19201 (fboundp org-finish-function))
19202 (funcall org-finish-function))
19203 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19204 ((org-in-regexp org-ts-regexp-both)
19205 (org-timestamp-change 0 'day))
19206 ((or (looking-at org-property-start-re)
19207 (org-at-property-p))
19208 (call-interactively 'org-property-action))
19209 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19210 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19211 (or (org-at-heading-p) (org-at-item-p)))
19212 (call-interactively 'org-update-statistics-cookies))
19213 ((org-at-heading-p) (call-interactively 'org-set-tags))
19214 ((org-at-table.el-p)
19215 (message "Use C-c ' to edit table.el tables"))
19216 ((org-at-table-p)
19217 (org-table-maybe-eval-formula)
19218 (if arg
19219 (call-interactively 'org-table-recalculate)
19220 (org-table-maybe-recalculate-line))
19221 (call-interactively 'org-table-align)
19222 (orgtbl-send-table 'maybe))
19223 ((or (org-footnote-at-reference-p)
19224 (org-footnote-at-definition-p))
19225 (call-interactively 'org-footnote-action))
19226 ((org-at-item-checkbox-p)
19227 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19228 ;; list only if at top item.
19229 (let* ((cbox (match-string 1))
19230 (struct (org-list-struct))
19231 (old-struct (copy-tree struct))
19232 (parents (org-list-parents-alist struct))
19233 (orderedp (org-entry-get nil "ORDERED"))
19234 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19235 block-item)
19236 ;; Use a light version of `org-toggle-checkbox' to avoid
19237 ;; computing list structure twice.
19238 (let ((new-box (cond
19239 ((equal arg '(16)) "[-]")
19240 ((equal arg '(4)) nil)
19241 ((equal "[X]" cbox) "[ ]")
19242 (t "[X]"))))
19243 (if (and firstp arg)
19244 ;; If at first item of sub-list, remove check-box from
19245 ;; every item at the same level.
19246 (mapc
19247 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19248 (org-list-get-all-items
19249 (point-at-bol) struct (org-list-prevs-alist struct)))
19250 (org-list-set-checkbox (point-at-bol) struct new-box)))
19251 ;; Replicate `org-list-write-struct', while grabbing a return
19252 ;; value from `org-list-struct-fix-box'.
19253 (org-list-struct-fix-ind struct parents 2)
19254 (org-list-struct-fix-item-end struct)
19255 (let ((prevs (org-list-prevs-alist struct)))
19256 (org-list-struct-fix-bul struct prevs)
19257 (org-list-struct-fix-ind struct parents)
19258 (setq block-item
19259 (org-list-struct-fix-box struct parents prevs orderedp)))
19260 (org-list-struct-apply-struct struct old-struct)
19261 (org-update-checkbox-count-maybe)
19262 (when block-item
19263 (message
19264 "Checkboxes were removed due to unchecked box at line %d"
19265 (org-current-line block-item)))
19266 (when firstp (org-list-send-list 'maybe))))
19267 ((org-at-item-p)
19268 ;; Cursor at an item: repair list. Do checkbox related actions
19269 ;; only if function was called with an argument. Send list only
19270 ;; if at top item.
19271 (let* ((struct (org-list-struct))
19272 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19273 old-struct)
19274 (when arg
19275 (setq old-struct (copy-tree struct))
19276 (if firstp
19277 ;; If at first item of sub-list, add check-box to every
19278 ;; item at the same level.
19279 (mapc
19280 (lambda (pos)
19281 (unless (org-list-get-checkbox pos struct)
19282 (org-list-set-checkbox pos struct "[ ]")))
19283 (org-list-get-all-items
19284 (point-at-bol) struct (org-list-prevs-alist struct)))
19285 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19286 (org-list-write-struct
19287 struct (org-list-parents-alist struct) old-struct)
19288 (when arg (org-update-checkbox-count-maybe))
19289 (when firstp (org-list-send-list 'maybe))))
19290 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19291 ;; Dynamic block
19292 (beginning-of-line 1)
19293 (save-excursion (org-update-dblock)))
19294 ((save-excursion
19295 (let ((case-fold-search t))
19296 (beginning-of-line 1)
19297 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19298 (cond
19299 ((or (equal (match-string 1) "TBLFM")
19300 (equal (match-string 1) "tblfm"))
19301 ;; Recalculate the table before this line
19302 (save-excursion
19303 (beginning-of-line 1)
19304 (skip-chars-backward " \r\n\t")
19305 (if (org-at-table-p)
19306 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19308 (let ((org-inhibit-startup-visibility-stuff t)
19309 (org-startup-align-all-tables nil))
19310 (when (boundp 'org-table-coordinate-overlays)
19311 (mapc 'delete-overlay org-table-coordinate-overlays)
19312 (setq org-table-coordinate-overlays nil))
19313 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19314 (message "Local setup has been refreshed"))))
19315 ((org-clock-update-time-maybe))
19317 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19318 (error "C-c C-c can do nothing useful at this location"))))))
19320 (defun org-mode-restart ()
19321 "Restart Org-mode, to scan again for special lines.
19322 Also updates the keyword regular expressions."
19323 (interactive)
19324 (org-mode)
19325 (message "Org-mode restarted"))
19327 (defun org-kill-note-or-show-branches ()
19328 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19329 (interactive)
19330 (if (not org-finish-function)
19331 (progn
19332 (hide-subtree)
19333 (call-interactively 'show-branches))
19334 (let ((org-note-abort t))
19335 (funcall org-finish-function))))
19337 (defun org-return (&optional indent)
19338 "Goto next table row or insert a newline.
19339 Calls `org-table-next-row' or `newline', depending on context.
19340 See the individual commands for more information."
19341 (interactive)
19342 (let (org-ts-what)
19343 (cond
19344 ((or (bobp) (org-in-src-block-p))
19345 (if indent (newline-and-indent) (newline)))
19346 ((org-at-table-p)
19347 (org-table-justify-field-maybe)
19348 (call-interactively 'org-table-next-row))
19349 ;; when `newline-and-indent' is called within a list, make sure
19350 ;; text moved stays inside the item.
19351 ((and (org-in-item-p) indent)
19352 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19353 (progn
19354 (save-match-data (newline))
19355 (org-indent-line-to (length (match-string 0))))
19356 (let ((ind (org-get-indentation)))
19357 (newline)
19358 (if (org-looking-back org-list-end-re)
19359 (org-indent-line)
19360 (org-indent-line-to ind)))))
19361 ((and org-return-follows-link
19362 (org-at-timestamp-p t)
19363 (not (eq org-ts-what 'after)))
19364 (org-follow-timestamp-link))
19365 ((and org-return-follows-link
19366 (let ((tprop (get-text-property (point) 'face)))
19367 (or (eq tprop 'org-link)
19368 (and (listp tprop) (memq 'org-link tprop)))))
19369 (call-interactively 'org-open-at-point))
19370 ((and (org-at-heading-p)
19371 (looking-at
19372 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19373 (org-show-entry)
19374 (end-of-line 1)
19375 (newline))
19376 (t (if indent (newline-and-indent) (newline))))))
19378 (defun org-return-indent ()
19379 "Goto next table row or insert a newline and indent.
19380 Calls `org-table-next-row' or `newline-and-indent', depending on
19381 context. See the individual commands for more information."
19382 (interactive)
19383 (org-return t))
19385 (defun org-ctrl-c-star ()
19386 "Compute table, or change heading status of lines.
19387 Calls `org-table-recalculate' or `org-toggle-heading',
19388 depending on context."
19389 (interactive)
19390 (cond
19391 ((org-at-table-p)
19392 (call-interactively 'org-table-recalculate))
19394 ;; Convert all lines in region to list items
19395 (call-interactively 'org-toggle-heading))))
19397 (defun org-ctrl-c-minus ()
19398 "Insert separator line in table or modify bullet status of line.
19399 Also turns a plain line or a region of lines into list items.
19400 Calls `org-table-insert-hline', `org-toggle-item', or
19401 `org-cycle-list-bullet', depending on context."
19402 (interactive)
19403 (cond
19404 ((org-at-table-p)
19405 (call-interactively 'org-table-insert-hline))
19406 ((org-region-active-p)
19407 (call-interactively 'org-toggle-item))
19408 ((org-in-item-p)
19409 (call-interactively 'org-cycle-list-bullet))
19411 (call-interactively 'org-toggle-item))))
19413 (defun org-toggle-item (arg)
19414 "Convert headings or normal lines to items, items to normal lines.
19415 If there is no active region, only the current line is considered.
19417 If the first non blank line in the region is an headline, convert
19418 all headlines to items, shifting text accordingly.
19420 If it is an item, convert all items to normal lines.
19422 If it is normal text, change region into an item. With a prefix
19423 argument ARG, change each line in region into an item."
19424 (interactive "P")
19425 (let ((shift-text
19426 (function
19427 ;; Shift text in current section to IND, from point to END.
19428 ;; The function leaves point to END line.
19429 (lambda (ind end)
19430 (let ((min-i 1000) (end (copy-marker end)))
19431 ;; First determine the minimum indentation (MIN-I) of
19432 ;; the text.
19433 (save-excursion
19434 (catch 'exit
19435 (while (< (point) end)
19436 (let ((i (org-get-indentation)))
19437 (cond
19438 ;; Skip blank lines and inline tasks.
19439 ((looking-at "^[ \t]*$"))
19440 ((looking-at org-outline-regexp-bol))
19441 ;; We can't find less than 0 indentation.
19442 ((zerop i) (throw 'exit (setq min-i 0)))
19443 ((< i min-i) (setq min-i i))))
19444 (forward-line))))
19445 ;; Then indent each line so that a line indented to
19446 ;; MIN-I becomes indented to IND. Ignore blank lines
19447 ;; and inline tasks in the process.
19448 (let ((delta (- ind min-i)))
19449 (while (< (point) end)
19450 (unless (or (looking-at "^[ \t]*$")
19451 (looking-at org-outline-regexp-bol))
19452 (org-indent-line-to (+ (org-get-indentation) delta)))
19453 (forward-line)))))))
19454 (skip-blanks
19455 (function
19456 ;; Return beginning of first non-blank line, starting from
19457 ;; line at POS.
19458 (lambda (pos)
19459 (save-excursion
19460 (goto-char pos)
19461 (skip-chars-forward " \r\t\n")
19462 (point-at-bol)))))
19463 beg end)
19464 ;; Determine boundaries of changes.
19465 (if (org-region-active-p)
19466 (setq beg (funcall skip-blanks (region-beginning))
19467 end (copy-marker (region-end)))
19468 (setq beg (funcall skip-blanks (point-at-bol))
19469 end (copy-marker (point-at-eol))))
19470 ;; Depending on the starting line, choose an action on the text
19471 ;; between BEG and END.
19472 (org-with-limited-levels
19473 (save-excursion
19474 (goto-char beg)
19475 (cond
19476 ;; Case 1. Start at an item: de-itemize. Note that it only
19477 ;; happens when a region is active: `org-ctrl-c-minus'
19478 ;; would call `org-cycle-list-bullet' otherwise.
19479 ((org-at-item-p)
19480 (while (< (point) end)
19481 (when (org-at-item-p)
19482 (skip-chars-forward " \t")
19483 (delete-region (point) (match-end 0)))
19484 (forward-line)))
19485 ;; Case 2. Start at an heading: convert to items.
19486 ((org-at-heading-p)
19487 (let* ((bul (org-list-bullet-string "-"))
19488 (bul-len (length bul))
19489 ;; Indentation of the first heading. It should be
19490 ;; relative to the indentation of its parent, if any.
19491 (start-ind (save-excursion
19492 (cond
19493 ((not org-adapt-indentation) 0)
19494 ((not (outline-previous-heading)) 0)
19495 (t (length (match-string 0))))))
19496 ;; Level of first heading. Further headings will be
19497 ;; compared to it to determine hierarchy in the list.
19498 (ref-level (org-reduced-level (org-outline-level))))
19499 (while (< (point) end)
19500 (let* ((level (org-reduced-level (org-outline-level)))
19501 (delta (max 0 (- level ref-level))))
19502 ;; If current headline is less indented than the first
19503 ;; one, set it as reference, in order to preserve
19504 ;; subtrees.
19505 (when (< level ref-level) (setq ref-level level))
19506 (replace-match bul t t)
19507 (org-indent-line-to (+ start-ind (* delta bul-len)))
19508 ;; Ensure all text down to END (or SECTION-END) belongs
19509 ;; to the newly created item.
19510 (let ((section-end (save-excursion
19511 (or (outline-next-heading) (point)))))
19512 (forward-line)
19513 (funcall shift-text
19514 (+ start-ind (* (1+ delta) bul-len))
19515 (min end section-end)))))))
19516 ;; Case 3. Normal line with ARG: turn each non-item line into
19517 ;; an item.
19518 (arg
19519 (while (< (point) end)
19520 (unless (or (org-at-heading-p) (org-at-item-p))
19521 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19522 (replace-match
19523 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19524 (forward-line)))
19525 ;; Case 4. Normal line without ARG: make the first line of
19526 ;; region an item, and shift indentation of others
19527 ;; lines to set them as item's body.
19528 (t (let* ((bul (org-list-bullet-string "-"))
19529 (bul-len (length bul))
19530 (ref-ind (org-get-indentation)))
19531 (skip-chars-forward " \t")
19532 (insert bul)
19533 (forward-line)
19534 (while (< (point) end)
19535 ;; Ensure that lines less indented than first one
19536 ;; still get included in item body.
19537 (funcall shift-text
19538 (+ ref-ind bul-len)
19539 (min end (save-excursion (or (outline-next-heading)
19540 (point)))))
19541 (forward-line)))))))))
19543 (defun org-toggle-heading (&optional nstars)
19544 "Convert headings to normal text, or items or text to headings.
19545 If there is no active region, only the current line is considered.
19547 With a \\[universal-argument] prefix, convert the whole list at
19548 point into heading.
19550 In a region:
19552 - If the first non blank line is an headline, remove the stars
19553 from all headlines in the region.
19555 - If it is a normal line turn each and every normal line (i.e. not an
19556 heading or an item) in the region into a heading.
19558 - If it is a plain list item, turn all plain list items into headings.
19560 When converting a line into a heading, the number of stars is chosen
19561 such that the lines become children of the current entry. However,
19562 when a prefix argument is given, its value determines the number of
19563 stars to add."
19564 (interactive "P")
19565 (let ((skip-blanks
19566 (function
19567 ;; Return beginning of first non-blank line, starting from
19568 ;; line at POS.
19569 (lambda (pos)
19570 (save-excursion
19571 (goto-char pos)
19572 (while (org-at-comment-p) (forward-line))
19573 (skip-chars-forward " \r\t\n")
19574 (point-at-bol)))))
19575 beg end toggled)
19576 ;; Determine boundaries of changes. If a universal prefix has
19577 ;; been given, put the list in a region. If region ends at a bol,
19578 ;; do not consider the last line to be in the region.
19580 (when (and current-prefix-arg (org-at-item-p))
19581 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19582 (org-mark-element))
19584 (if (org-region-active-p)
19585 (setq beg (funcall skip-blanks (region-beginning))
19586 end (copy-marker (save-excursion
19587 (goto-char (region-end))
19588 (if (bolp) (point) (point-at-eol)))))
19589 (setq beg (funcall skip-blanks (point-at-bol))
19590 end (copy-marker (point-at-eol))))
19591 ;; Ensure inline tasks don't count as headings.
19592 (org-with-limited-levels
19593 (save-excursion
19594 (goto-char beg)
19595 (cond
19596 ;; Case 1. Started at an heading: de-star headings.
19597 ((org-at-heading-p)
19598 (while (< (point) end)
19599 (when (org-at-heading-p t)
19600 (looking-at org-outline-regexp) (replace-match "")
19601 (setq toggled t))
19602 (forward-line)))
19603 ;; Case 2. Started at an item: change items into headlines.
19604 ;; One star will be added by `org-list-to-subtree'.
19605 ((org-at-item-p)
19606 (let* ((stars (make-string
19607 (if nstars
19608 ;; subtract the star that will be added again by
19609 ;; `org-list-to-subtree'
19610 (1- (prefix-numeric-value current-prefix-arg))
19611 (or (org-current-level) 0))
19612 ?*))
19613 (add-stars
19614 (cond (nstars "") ; stars from prefix only
19615 ((equal stars "") "") ; before first heading
19616 (org-odd-levels-only "*") ; inside heading, odd
19617 (t "")))) ; inside heading, oddeven
19618 (while (< (point) end)
19619 (when (org-at-item-p)
19620 ;; Pay attention to cases when region ends before list.
19621 (let* ((struct (org-list-struct))
19622 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19623 (save-restriction
19624 (narrow-to-region (point) list-end)
19625 (insert
19626 (org-list-to-subtree
19627 (org-list-parse-list t)
19628 '(:istart (concat stars add-stars (funcall get-stars depth))
19629 :icount (concat stars add-stars (funcall get-stars depth)))))))
19630 (setq toggled t))
19631 (forward-line))))
19632 ;; Case 3. Started at normal text: make every line an heading,
19633 ;; skipping headlines and items.
19634 (t (let* ((stars (make-string
19635 (if nstars
19636 (prefix-numeric-value current-prefix-arg)
19637 (or (org-current-level) 0))
19638 ?*))
19639 (add-stars
19640 (cond (nstars "") ; stars from prefix only
19641 ((equal stars "") "*") ; before first heading
19642 (org-odd-levels-only "**") ; inside heading, odd
19643 (t "*"))) ; inside heading, oddeven
19644 (rpl (concat stars add-stars " ")))
19645 (while (< (point) end)
19646 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19647 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19648 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19649 (forward-line)))))))
19650 (unless toggled (message "Cannot toggle heading from here"))))
19652 (defun org-meta-return (&optional arg)
19653 "Insert a new heading or wrap a region in a table.
19654 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19655 See the individual commands for more information."
19656 (interactive "P")
19657 (cond
19658 ((run-hook-with-args-until-success 'org-metareturn-hook))
19659 ((or (org-at-drawer-p) (org-at-property-p))
19660 (newline-and-indent))
19661 ((org-at-table-p)
19662 (call-interactively 'org-table-wrap-region))
19663 (t (call-interactively 'org-insert-heading))))
19665 ;;; Menu entries
19667 ;; Define the Org-mode menus
19668 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19669 '("Tbl"
19670 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19671 ["Next Field" org-cycle (org-at-table-p)]
19672 ["Previous Field" org-shifttab (org-at-table-p)]
19673 ["Next Row" org-return (org-at-table-p)]
19674 "--"
19675 ["Blank Field" org-table-blank-field (org-at-table-p)]
19676 ["Edit Field" org-table-edit-field (org-at-table-p)]
19677 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19678 "--"
19679 ("Column"
19680 ["Move Column Left" org-metaleft (org-at-table-p)]
19681 ["Move Column Right" org-metaright (org-at-table-p)]
19682 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19683 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19684 ("Row"
19685 ["Move Row Up" org-metaup (org-at-table-p)]
19686 ["Move Row Down" org-metadown (org-at-table-p)]
19687 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19688 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19689 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19690 "--"
19691 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19692 ("Rectangle"
19693 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19694 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19695 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19696 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19697 "--"
19698 ("Calculate"
19699 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19700 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19701 ["Edit Formulas" org-edit-special (org-at-table-p)]
19702 "--"
19703 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19704 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19705 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19706 "--"
19707 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19708 "--"
19709 ["Sum Column/Rectangle" org-table-sum
19710 (or (org-at-table-p) (org-region-active-p))]
19711 ["Which Column?" org-table-current-column (org-at-table-p)])
19712 ["Debug Formulas"
19713 org-table-toggle-formula-debugger
19714 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19715 ["Show Col/Row Numbers"
19716 org-table-toggle-coordinate-overlays
19717 :style toggle
19718 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19719 "--"
19720 ["Create" org-table-create (and (not (org-at-table-p))
19721 org-enable-table-editor)]
19722 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19723 ["Import from File" org-table-import (not (org-at-table-p))]
19724 ["Export to File" org-table-export (org-at-table-p)]
19725 "--"
19726 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19728 (easy-menu-define org-org-menu org-mode-map "Org menu"
19729 '("Org"
19730 ("Show/Hide"
19731 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19732 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19733 ["Sparse Tree..." org-sparse-tree t]
19734 ["Reveal Context" org-reveal t]
19735 ["Show All" show-all t]
19736 "--"
19737 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19738 "--"
19739 ["New Heading" org-insert-heading t]
19740 ("Navigate Headings"
19741 ["Up" outline-up-heading t]
19742 ["Next" outline-next-visible-heading t]
19743 ["Previous" outline-previous-visible-heading t]
19744 ["Next Same Level" outline-forward-same-level t]
19745 ["Previous Same Level" outline-backward-same-level t]
19746 "--"
19747 ["Jump" org-goto t])
19748 ("Edit Structure"
19749 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19750 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19751 "--"
19752 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19753 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19754 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19755 "--"
19756 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19757 "--"
19758 ["Copy visible text" org-copy-visible t]
19759 "--"
19760 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19761 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19762 ["Demote Heading" org-metaright (not (org-at-table-p))]
19763 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19764 "--"
19765 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19766 "--"
19767 ["Convert to odd levels" org-convert-to-odd-levels t]
19768 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19769 ("Editing"
19770 ["Emphasis..." org-emphasize t]
19771 ["Edit Source Example" org-edit-special t]
19772 "--"
19773 ["Footnote new/jump" org-footnote-action t]
19774 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19775 ("Archive"
19776 ["Archive (default method)" org-archive-subtree-default t]
19777 "--"
19778 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19779 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19780 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19782 "--"
19783 ("Hyperlinks"
19784 ["Store Link (Global)" org-store-link t]
19785 ["Find existing link to here" org-occur-link-in-agenda-files t]
19786 ["Insert Link" org-insert-link t]
19787 ["Follow Link" org-open-at-point t]
19788 "--"
19789 ["Next link" org-next-link t]
19790 ["Previous link" org-previous-link t]
19791 "--"
19792 ["Descriptive Links"
19793 org-toggle-link-display
19794 :style radio
19795 :selected org-descriptive-links
19797 ["Literal Links"
19798 org-toggle-link-display
19799 :style radio
19800 :selected (not org-descriptive-links)])
19801 "--"
19802 ("TODO Lists"
19803 ["TODO/DONE/-" org-todo t]
19804 ("Select keyword"
19805 ["Next keyword" org-shiftright (org-at-heading-p)]
19806 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19807 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19808 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19809 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19810 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19811 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19812 "--"
19813 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19814 :selected org-enforce-todo-dependencies :style toggle :active t]
19815 "Settings for tree at point"
19816 ["Do Children sequentially" org-toggle-ordered-property :style radio
19817 :selected (org-entry-get nil "ORDERED")
19818 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19819 ["Do Children parallel" org-toggle-ordered-property :style radio
19820 :selected (not (org-entry-get nil "ORDERED"))
19821 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19822 "--"
19823 ["Set Priority" org-priority t]
19824 ["Priority Up" org-shiftup t]
19825 ["Priority Down" org-shiftdown t]
19826 "--"
19827 ["Get news from all feeds" org-feed-update-all t]
19828 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19829 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19830 ("TAGS and Properties"
19831 ["Set Tags" org-set-tags-command t]
19832 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19833 "--"
19834 ["Set property" org-set-property t]
19835 ["Column view of properties" org-columns t]
19836 ["Insert Column View DBlock" org-insert-columns-dblock t])
19837 ("Dates and Scheduling"
19838 ["Timestamp" org-time-stamp t]
19839 ["Timestamp (inactive)" org-time-stamp-inactive t]
19840 ("Change Date"
19841 ["1 Day Later" org-shiftright t]
19842 ["1 Day Earlier" org-shiftleft t]
19843 ["1 ... Later" org-shiftup t]
19844 ["1 ... Earlier" org-shiftdown t])
19845 ["Compute Time Range" org-evaluate-time-range t]
19846 ["Schedule Item" org-schedule t]
19847 ["Deadline" org-deadline t]
19848 "--"
19849 ["Custom time format" org-toggle-time-stamp-overlays
19850 :style radio :selected org-display-custom-times]
19851 "--"
19852 ["Goto Calendar" org-goto-calendar t]
19853 ["Date from Calendar" org-date-from-calendar t]
19854 "--"
19855 ["Start/Restart Timer" org-timer-start t]
19856 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19857 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19858 ["Insert Timer String" org-timer t]
19859 ["Insert Timer Item" org-timer-item t])
19860 ("Logging work"
19861 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19862 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19863 ["Clock out" org-clock-out t]
19864 ["Clock cancel" org-clock-cancel t]
19865 "--"
19866 ["Mark as default task" org-clock-mark-default-task t]
19867 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19868 ["Goto running clock" org-clock-goto t]
19869 "--"
19870 ["Display times" org-clock-display t]
19871 ["Create clock table" org-clock-report t]
19872 "--"
19873 ["Record DONE time"
19874 (progn (setq org-log-done (not org-log-done))
19875 (message "Switching to %s will %s record a timestamp"
19876 (car org-done-keywords)
19877 (if org-log-done "automatically" "not")))
19878 :style toggle :selected org-log-done])
19879 "--"
19880 ["Agenda Command..." org-agenda t]
19881 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19882 ("File List for Agenda")
19883 ("Special views current file"
19884 ["TODO Tree" org-show-todo-tree t]
19885 ["Check Deadlines" org-check-deadlines t]
19886 ["Timeline" org-timeline t]
19887 ["Tags/Property tree" org-match-sparse-tree t])
19888 "--"
19889 ["Export/Publish..." org-export t]
19890 ("LaTeX"
19891 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19892 :selected org-cdlatex-mode]
19893 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19894 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19895 ["Modify math symbol" org-cdlatex-math-modify
19896 (org-inside-LaTeX-fragment-p)]
19897 ["Insert citation" org-reftex-citation t]
19898 "--"
19899 ["Template for BEAMER" (progn (require 'org-beamer)
19900 (org-insert-beamer-options-template)) t])
19901 "--"
19902 ("MobileOrg"
19903 ["Push Files and Views" org-mobile-push t]
19904 ["Get Captured and Flagged" org-mobile-pull t]
19905 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19906 "--"
19907 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19908 "--"
19909 ("Documentation"
19910 ["Show Version" org-version t]
19911 ["Info Documentation" org-info t])
19912 ("Customize"
19913 ["Browse Org Group" org-customize t]
19914 "--"
19915 ["Expand This Menu" org-create-customize-menu
19916 (fboundp 'customize-menu-create)])
19917 ["Send bug report" org-submit-bug-report t]
19918 "--"
19919 ("Refresh/Reload"
19920 ["Refresh setup current buffer" org-mode-restart t]
19921 ["Reload Org (after update)" org-reload t]
19922 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19925 (defun org-info (&optional node)
19926 "Read documentation for Org-mode in the info system.
19927 With optional NODE, go directly to that node."
19928 (interactive)
19929 (info (format "(org)%s" (or node ""))))
19931 ;;;###autoload
19932 (defun org-submit-bug-report ()
19933 "Submit a bug report on Org-mode via mail.
19935 Don't hesitate to report any problems or inaccurate documentation.
19937 If you don't have setup sending mail from (X)Emacs, please copy the
19938 output buffer into your mail program, as it gives us important
19939 information about your Org-mode version and configuration."
19940 (interactive)
19941 (require 'reporter)
19942 (org-load-modules-maybe)
19943 (org-require-autoloaded-modules)
19944 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19945 (reporter-submit-bug-report
19946 "emacs-orgmode@gnu.org"
19947 (org-version nil 'full)
19948 (let (list)
19949 (save-window-excursion
19950 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19951 (delete-other-windows)
19952 (erase-buffer)
19953 (insert "You are about to submit a bug report to the Org-mode mailing list.
19955 We would like to add your full Org-mode and Outline configuration to the
19956 bug report. This greatly simplifies the work of the maintainer and
19957 other experts on the mailing list.
19959 HOWEVER, some variables you have customized may contain private
19960 information. The names of customers, colleagues, or friends, might
19961 appear in the form of file names, tags, todo states, or search strings.
19962 If you answer yes to the prompt, you might want to check and remove
19963 such private information before sending the email.")
19964 (add-text-properties (point-min) (point-max) '(face org-warning))
19965 (when (yes-or-no-p "Include your Org-mode configuration ")
19966 (mapatoms
19967 (lambda (v)
19968 (and (boundp v)
19969 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19970 (or (and (symbol-value v)
19971 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19972 (and
19973 (get v 'custom-type) (get v 'standard-value)
19974 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19975 (push v list)))))
19976 (kill-buffer (get-buffer "*Warn about privacy*"))
19977 list))
19978 nil nil
19979 "Remember to cover the basics, that is, what you expected to happen and
19980 what in fact did happen. You don't know how to make a good report? See
19982 http://orgmode.org/manual/Feedback.html#Feedback
19984 Your bug report will be posted to the Org-mode mailing list.
19985 ------------------------------------------------------------------------")
19986 (save-excursion
19987 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19988 (replace-match "\\1Bug: \\3 [\\2]")))))
19991 (defun org-install-agenda-files-menu ()
19992 (let ((bl (buffer-list)))
19993 (save-excursion
19994 (while bl
19995 (set-buffer (pop bl))
19996 (if (derived-mode-p 'org-mode) (setq bl nil)))
19997 (when (derived-mode-p 'org-mode)
19998 (easy-menu-change
19999 '("Org") "File List for Agenda"
20000 (append
20001 (list
20002 ["Edit File List" (org-edit-agenda-file-list) t]
20003 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20004 ["Remove Current File from List" org-remove-file t]
20005 ["Cycle through agenda files" org-cycle-agenda-files t]
20006 ["Occur in all agenda files" org-occur-in-agenda-files t]
20007 "--")
20008 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20010 ;;;; Documentation
20012 ;;;###autoload
20013 (defun org-require-autoloaded-modules ()
20014 (interactive)
20015 (mapc 'require
20016 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20017 org-docbook org-exp org-html org-icalendar
20018 org-id org-latex
20019 org-publish org-remember org-table
20020 org-timer org-xoxo)))
20022 ;;;###autoload
20023 (defun org-reload (&optional uncompiled)
20024 "Reload all org lisp files.
20025 With prefix arg UNCOMPILED, load the uncompiled versions."
20026 (interactive "P")
20027 (require 'find-func)
20028 (let* ((file-re "^org\\(-.*\\)?\\.el")
20029 (dir-org (file-name-directory (org-find-library-dir "org")))
20030 (dir-org-contrib (ignore-errors
20031 (file-name-directory
20032 (org-find-library-dir "org-contribdir"))))
20033 (babel-files
20034 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20035 (append (list nil "comint" "eval" "exp" "keys"
20036 "lob" "ref" "table" "tangle")
20037 (delq nil
20038 (mapcar
20039 (lambda (lang)
20040 (when (cdr lang) (symbol-name (car lang))))
20041 org-babel-load-languages)))))
20042 (files
20043 (append babel-files
20044 (and dir-org-contrib
20045 (directory-files dir-org-contrib t file-re))
20046 (directory-files dir-org t file-re)))
20047 (remove-re (concat (if (featurep 'xemacs)
20048 "org-colview" "org-colview-xemacs")
20049 "\\'")))
20050 (setq files (mapcar 'file-name-sans-extension files))
20051 (setq files (mapcar
20052 (lambda (x) (if (string-match remove-re x) nil x))
20053 files))
20054 (setq files (delq nil files))
20055 (mapc
20056 (lambda (f)
20057 (when (featurep (intern (file-name-nondirectory f)))
20058 (if (and (not uncompiled)
20059 (file-exists-p (concat f ".elc")))
20060 (load (concat f ".elc") nil nil 'nosuffix)
20061 (load (concat f ".el") nil nil 'nosuffix))))
20062 files)
20063 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20064 (org-version nil 'full 'message))
20066 ;;;###autoload
20067 (defun org-customize ()
20068 "Call the customize function with org as argument."
20069 (interactive)
20070 (org-load-modules-maybe)
20071 (org-require-autoloaded-modules)
20072 (customize-browse 'org))
20074 (defun org-create-customize-menu ()
20075 "Create a full customization menu for Org-mode, insert it into the menu."
20076 (interactive)
20077 (org-load-modules-maybe)
20078 (org-require-autoloaded-modules)
20079 (if (fboundp 'customize-menu-create)
20080 (progn
20081 (easy-menu-change
20082 '("Org") "Customize"
20083 `(["Browse Org group" org-customize t]
20084 "--"
20085 ,(customize-menu-create 'org)
20086 ["Set" Custom-set t]
20087 ["Save" Custom-save t]
20088 ["Reset to Current" Custom-reset-current t]
20089 ["Reset to Saved" Custom-reset-saved t]
20090 ["Reset to Standard Settings" Custom-reset-standard t]))
20091 (message "\"Org\"-menu now contains full customization menu"))
20092 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20094 ;;;; Miscellaneous stuff
20096 ;;; Generally useful functions
20098 (defun org-get-at-bol (property)
20099 "Get text property PROPERTY at beginning of line."
20100 (get-text-property (point-at-bol) property))
20102 (defun org-find-text-property-in-string (prop s)
20103 "Return the first non-nil value of property PROP in string S."
20104 (or (get-text-property 0 prop s)
20105 (get-text-property (or (next-single-property-change 0 prop s) 0)
20106 prop s)))
20108 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20109 "Display the given MESSAGE as a warning."
20110 (if (fboundp 'display-warning)
20111 (display-warning 'org message
20112 (if (featurep 'xemacs) 'warning :warning))
20113 (let ((buf (get-buffer-create "*Org warnings*")))
20114 (with-current-buffer buf
20115 (goto-char (point-max))
20116 (insert "Warning (Org): " message)
20117 (unless (bolp)
20118 (newline)))
20119 (display-buffer buf)
20120 (sit-for 0))))
20122 (defun org-eval (form)
20123 "Eval FORM and return result."
20124 (condition-case error
20125 (eval form)
20126 (error (format "%%![Error: %s]" error))))
20128 (defun org-in-clocktable-p ()
20129 "Check if the cursor is in a clocktable."
20130 (let ((pos (point)) start)
20131 (save-excursion
20132 (end-of-line 1)
20133 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20134 (setq start (match-beginning 0))
20135 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20136 (>= (match-end 0) pos)
20137 start))))
20139 (defun org-in-commented-line ()
20140 "Is point in a line starting with `#'?"
20141 (equal (char-after (point-at-bol)) ?#))
20143 (defun org-in-indented-comment-line ()
20144 "Is point in a line starting with `#' after some white space?"
20145 (save-excursion
20146 (save-match-data
20147 (goto-char (point-at-bol))
20148 (looking-at "[ \t]*#"))))
20150 (defun org-in-verbatim-emphasis ()
20151 (save-match-data
20152 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20154 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20155 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20156 (if (and marker (marker-buffer marker)
20157 (buffer-live-p (marker-buffer marker)))
20158 (progn
20159 (org-pop-to-buffer-same-window (marker-buffer marker))
20160 (if (or (> marker (point-max)) (< marker (point-min)))
20161 (widen))
20162 (goto-char marker)
20163 (org-show-context 'org-goto))
20164 (if bookmark
20165 (bookmark-jump bookmark)
20166 (error "Cannot find location"))))
20168 (defun org-quote-csv-field (s)
20169 "Quote field for inclusion in CSV material."
20170 (if (string-match "[\",]" s)
20171 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20174 (defun org-force-self-insert (N)
20175 "Needed to enforce self-insert under remapping."
20176 (interactive "p")
20177 (self-insert-command N))
20179 (defun org-string-width (s)
20180 "Compute width of string, ignoring invisible characters.
20181 This ignores character with invisibility property `org-link', and also
20182 characters with property `org-cwidth', because these will become invisible
20183 upon the next fontification round."
20184 (let (b l)
20185 (when (or (eq t buffer-invisibility-spec)
20186 (assq 'org-link buffer-invisibility-spec))
20187 (while (setq b (text-property-any 0 (length s)
20188 'invisible 'org-link s))
20189 (setq s (concat (substring s 0 b)
20190 (substring s (or (next-single-property-change
20191 b 'invisible s) (length s)))))))
20192 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20193 (setq s (concat (substring s 0 b)
20194 (substring s (or (next-single-property-change
20195 b 'org-cwidth s) (length s))))))
20196 (setq l (string-width s) b -1)
20197 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20198 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20201 (defun org-shorten-string (s maxlength)
20202 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20203 If the string is shorter or has length MAXLENGTH, just return the
20204 original string. If it is longer, the functions finds a space in the
20205 string, breaks this string off at that locations and adds three dots
20206 as ellipsis. Including the ellipsis, the string will not be longer
20207 than MAXLENGTH. If finding a good breaking point in the string does
20208 not work, the string is just chopped off in the middle of a word
20209 if necessary."
20210 (if (<= (length s) maxlength)
20212 (let* ((n (max (- maxlength 4) 1))
20213 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20214 (if (string-match re s)
20215 (concat (match-string 1 s) "...")
20216 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20218 (defun org-get-indentation (&optional line)
20219 "Get the indentation of the current line, interpreting tabs.
20220 When LINE is given, assume it represents a line and compute its indentation."
20221 (if line
20222 (if (string-match "^ *" (org-remove-tabs line))
20223 (match-end 0))
20224 (save-excursion
20225 (beginning-of-line 1)
20226 (skip-chars-forward " \t")
20227 (current-column))))
20229 (defun org-get-string-indentation (s)
20230 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20231 (let ((n -1) (i 0) (w tab-width) c)
20232 (catch 'exit
20233 (while (< (setq n (1+ n)) (length s))
20234 (setq c (aref s n))
20235 (cond ((= c ?\ ) (setq i (1+ i)))
20236 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20237 (t (throw 'exit t)))))
20240 (defun org-remove-tabs (s &optional width)
20241 "Replace tabulators in S with spaces.
20242 Assumes that s is a single line, starting in column 0."
20243 (setq width (or width tab-width))
20244 (while (string-match "\t" s)
20245 (setq s (replace-match
20246 (make-string
20247 (- (* width (/ (+ (match-beginning 0) width) width))
20248 (match-beginning 0)) ?\ )
20249 t t s)))
20252 (defun org-fix-indentation (line ind)
20253 "Fix indentation in LINE.
20254 IND is a cons cell with target and minimum indentation.
20255 If the current indentation in LINE is smaller than the minimum,
20256 leave it alone. If it is larger than ind, set it to the target."
20257 (let* ((l (org-remove-tabs line))
20258 (i (org-get-indentation l))
20259 (i1 (car ind)) (i2 (cdr ind)))
20260 (if (>= i i2) (setq l (substring line i2)))
20261 (if (> i1 0)
20262 (concat (make-string i1 ?\ ) l)
20263 l)))
20265 (defun org-remove-indentation (code &optional n)
20266 "Remove the maximum common indentation from the lines in CODE.
20267 N may optionally be the number of spaces to remove."
20268 (with-temp-buffer
20269 (insert code)
20270 (org-do-remove-indentation n)
20271 (buffer-string)))
20273 (defun org-do-remove-indentation (&optional n)
20274 "Remove the maximum common indentation from the buffer."
20275 (untabify (point-min) (point-max))
20276 (let ((min 10000) re)
20277 (if n
20278 (setq min n)
20279 (goto-char (point-min))
20280 (while (re-search-forward "^ *[^ \n]" nil t)
20281 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20282 (unless (or (= min 0) (= min 10000))
20283 (setq re (format "^ \\{%d\\}" min))
20284 (goto-char (point-min))
20285 (while (re-search-forward re nil t)
20286 (replace-match "")
20287 (end-of-line 1))
20288 min)))
20290 (defun org-fill-template (template alist)
20291 "Find each %key of ALIST in TEMPLATE and replace it."
20292 (let ((case-fold-search nil)
20293 entry key value)
20294 (setq alist (sort (copy-sequence alist)
20295 (lambda (a b) (< (length (car a)) (length (car b))))))
20296 (while (setq entry (pop alist))
20297 (setq template
20298 (replace-regexp-in-string
20299 (concat "%" (regexp-quote (car entry)))
20300 (or (cdr entry) "") template t t)))
20301 template))
20303 (defun org-base-buffer (buffer)
20304 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20305 (if (not buffer)
20306 buffer
20307 (or (buffer-base-buffer buffer)
20308 buffer)))
20310 (defun org-trim (s)
20311 "Remove whitespace at beginning and end of string."
20312 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20313 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20316 (defun org-wrap (string &optional width lines)
20317 "Wrap string to either a number of lines, or a width in characters.
20318 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20319 that costs. If there is a word longer than WIDTH, the text is actually
20320 wrapped to the length of that word.
20321 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20322 many lines, whatever width that takes.
20323 The return value is a list of lines, without newlines at the end."
20324 (let* ((words (org-split-string string "[ \t\n]+"))
20325 (maxword (apply 'max (mapcar 'org-string-width words)))
20326 w ll)
20327 (cond (width
20328 (org-do-wrap words (max maxword width)))
20329 (lines
20330 (setq w maxword)
20331 (setq ll (org-do-wrap words maxword))
20332 (if (<= (length ll) lines)
20334 (setq ll words)
20335 (while (> (length ll) lines)
20336 (setq w (1+ w))
20337 (setq ll (org-do-wrap words w)))
20338 ll))
20339 (t (error "Cannot wrap this")))))
20341 (defun org-do-wrap (words width)
20342 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20343 (let (lines line)
20344 (while words
20345 (setq line (pop words))
20346 (while (and words (< (+ (length line) (length (car words))) width))
20347 (setq line (concat line " " (pop words))))
20348 (setq lines (push line lines)))
20349 (nreverse lines)))
20351 (defun org-split-string (string &optional separators)
20352 "Splits STRING into substrings at SEPARATORS.
20353 No empty strings are returned if there are matches at the beginning
20354 and end of string."
20355 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20356 (start 0)
20357 notfirst
20358 (list nil))
20359 (while (and (string-match rexp string
20360 (if (and notfirst
20361 (= start (match-beginning 0))
20362 (< start (length string)))
20363 (1+ start) start))
20364 (< (match-beginning 0) (length string)))
20365 (setq notfirst t)
20366 (or (eq (match-beginning 0) 0)
20367 (and (eq (match-beginning 0) (match-end 0))
20368 (eq (match-beginning 0) start))
20369 (setq list
20370 (cons (substring string start (match-beginning 0))
20371 list)))
20372 (setq start (match-end 0)))
20373 (or (eq start (length string))
20374 (setq list
20375 (cons (substring string start)
20376 list)))
20377 (nreverse list)))
20379 (defun org-quote-vert (s)
20380 "Replace \"|\" with \"\\vert\"."
20381 (while (string-match "|" s)
20382 (setq s (replace-match "\\vert" t t s)))
20385 (defun org-uuidgen-p (s)
20386 "Is S an ID created by UUIDGEN?"
20387 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20389 (defun org-in-src-block-p nil
20390 "Whether point is in a code source block."
20391 (let (ov)
20392 (when (setq ov (overlays-at (point)))
20393 (memq 'org-block-background
20394 (overlay-properties
20395 (car ov))))))
20397 (defun org-context ()
20398 "Return a list of contexts of the current cursor position.
20399 If several contexts apply, all are returned.
20400 Each context entry is a list with a symbol naming the context, and
20401 two positions indicating start and end of the context. Possible
20402 contexts are:
20404 :headline anywhere in a headline
20405 :headline-stars on the leading stars in a headline
20406 :todo-keyword on a TODO keyword (including DONE) in a headline
20407 :tags on the TAGS in a headline
20408 :priority on the priority cookie in a headline
20409 :item on the first line of a plain list item
20410 :item-bullet on the bullet/number of a plain list item
20411 :checkbox on the checkbox in a plain list item
20412 :table in an org-mode table
20413 :table-special on a special filed in a table
20414 :table-table in a table.el table
20415 :clocktable in a clocktable
20416 :src-block in a source block
20417 :link on a hyperlink
20418 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20419 :target on a <<target>>
20420 :radio-target on a <<<radio-target>>>
20421 :latex-fragment on a LaTeX fragment
20422 :latex-preview on a LaTeX fragment with overlaid preview image
20424 This function expects the position to be visible because it uses font-lock
20425 faces as a help to recognize the following contexts: :table-special, :link,
20426 and :keyword."
20427 (let* ((f (get-text-property (point) 'face))
20428 (faces (if (listp f) f (list f)))
20429 (case-fold-search t)
20430 (p (point)) clist o)
20431 ;; First the large context
20432 (cond
20433 ((org-at-heading-p t)
20434 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20435 (when (progn
20436 (beginning-of-line 1)
20437 (looking-at org-todo-line-tags-regexp))
20438 (push (org-point-in-group p 1 :headline-stars) clist)
20439 (push (org-point-in-group p 2 :todo-keyword) clist)
20440 (push (org-point-in-group p 4 :tags) clist))
20441 (goto-char p)
20442 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20443 (if (looking-at "\\[#[A-Z0-9]\\]")
20444 (push (org-point-in-group p 0 :priority) clist)))
20446 ((org-at-item-p)
20447 (push (org-point-in-group p 2 :item-bullet) clist)
20448 (push (list :item (point-at-bol)
20449 (save-excursion (org-end-of-item) (point)))
20450 clist)
20451 (and (org-at-item-checkbox-p)
20452 (push (org-point-in-group p 0 :checkbox) clist)))
20454 ((org-at-table-p)
20455 (push (list :table (org-table-begin) (org-table-end)) clist)
20456 (if (memq 'org-formula faces)
20457 (push (list :table-special
20458 (previous-single-property-change p 'face)
20459 (next-single-property-change p 'face)) clist)))
20460 ((org-at-table-p 'any)
20461 (push (list :table-table) clist)))
20462 (goto-char p)
20464 (let ((case-fold-search t))
20465 ;; New the "medium" contexts: clocktables, source blocks
20466 (cond ((org-in-clocktable-p)
20467 (push (list :clocktable
20468 (and (or (looking-at "#\\+BEGIN: clocktable")
20469 (search-backward "#+BEGIN: clocktable" nil t))
20470 (match-beginning 0))
20471 (and (re-search-forward "#\\+END:?" nil t)
20472 (match-end 0))) clist))
20473 ((org-in-src-block-p)
20474 (push (list :src-block
20475 (and (or (looking-at "#\\+BEGIN_SRC")
20476 (search-backward "#+BEGIN_SRC" nil t))
20477 (match-beginning 0))
20478 (and (search-forward "#+END_SRC" nil t)
20479 (match-beginning 0))) clist))))
20480 (goto-char p)
20482 ;; Now the small context
20483 (cond
20484 ((org-at-timestamp-p)
20485 (push (org-point-in-group p 0 :timestamp) clist))
20486 ((memq 'org-link faces)
20487 (push (list :link
20488 (previous-single-property-change p 'face)
20489 (next-single-property-change p 'face)) clist))
20490 ((memq 'org-special-keyword faces)
20491 (push (list :keyword
20492 (previous-single-property-change p 'face)
20493 (next-single-property-change p 'face)) clist))
20494 ((org-at-target-p)
20495 (push (org-point-in-group p 0 :target) clist)
20496 (goto-char (1- (match-beginning 0)))
20497 (if (looking-at org-radio-target-regexp)
20498 (push (org-point-in-group p 0 :radio-target) clist))
20499 (goto-char p))
20500 ((setq o (car (delq nil
20501 (mapcar
20502 (lambda (x)
20503 (if (memq x org-latex-fragment-image-overlays) x))
20504 (overlays-at (point))))))
20505 (push (list :latex-fragment
20506 (overlay-start o) (overlay-end o)) clist)
20507 (push (list :latex-preview
20508 (overlay-start o) (overlay-end o)) clist))
20509 ((org-inside-LaTeX-fragment-p)
20510 ;; FIXME: positions wrong.
20511 (push (list :latex-fragment (point) (point)) clist)))
20513 (setq clist (nreverse (delq nil clist)))
20514 clist))
20516 ;; FIXME: Compare with at-regexp-p Do we need both?
20517 (defun org-in-regexp (re &optional nlines visually)
20518 "Check if point is inside a match of regexp.
20519 Normally only the current line is checked, but you can include NLINES extra
20520 lines both before and after point into the search.
20521 If VISUALLY is set, require that the cursor is not after the match but
20522 really on, so that the block visually is on the match."
20523 (catch 'exit
20524 (let ((pos (point))
20525 (eol (point-at-eol (+ 1 (or nlines 0))))
20526 (inc (if visually 1 0)))
20527 (save-excursion
20528 (beginning-of-line (- 1 (or nlines 0)))
20529 (while (re-search-forward re eol t)
20530 (if (and (<= (match-beginning 0) pos)
20531 (>= (+ inc (match-end 0)) pos))
20532 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20534 (defun org-at-regexp-p (regexp)
20535 "Is point inside a match of REGEXP in the current line?"
20536 (catch 'exit
20537 (save-excursion
20538 (let ((pos (point)) (end (point-at-eol)))
20539 (beginning-of-line 1)
20540 (while (re-search-forward regexp end t)
20541 (if (and (<= (match-beginning 0) pos)
20542 (>= (match-end 0) pos))
20543 (throw 'exit t)))
20544 nil))))
20546 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20547 "Non-nil when point is between matches of START-RE and END-RE.
20549 Also return a non-nil value when point is on one of the matches.
20551 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20552 buffer positions. Default values are the positions of headlines
20553 surrounding the point.
20555 The functions returns a cons cell whose car (resp. cdr) is the
20556 position before START-RE (resp. after END-RE)."
20557 (save-match-data
20558 (let ((pos (point))
20559 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20560 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20561 beg end)
20562 (save-excursion
20563 ;; Point is on a block when on START-RE or if START-RE can be
20564 ;; found before it...
20565 (and (or (org-at-regexp-p start-re)
20566 (re-search-backward start-re limit-up t))
20567 (setq beg (match-beginning 0))
20568 ;; ... and END-RE after it...
20569 (goto-char (match-end 0))
20570 (re-search-forward end-re limit-down t)
20571 (> (setq end (match-end 0)) pos)
20572 ;; ... without another START-RE in-between.
20573 (goto-char (match-beginning 0))
20574 (not (re-search-backward start-re (1+ beg) t))
20575 ;; Return value.
20576 (cons beg end))))))
20578 (defun org-in-block-p (names)
20579 "Non-nil when point belongs to a block whose name belongs to NAMES.
20581 NAMES is a list of strings containing names of blocks.
20583 Return first block name matched, or nil. Beware that in case of
20584 nested blocks, the returned name may not belong to the closest
20585 block from point."
20586 (save-match-data
20587 (catch 'exit
20588 (let ((case-fold-search t)
20589 (lim-up (save-excursion (outline-previous-heading)))
20590 (lim-down (save-excursion (outline-next-heading))))
20591 (mapc (lambda (name)
20592 (let ((n (regexp-quote name)))
20593 (when (org-between-regexps-p
20594 (concat "^[ \t]*#\\+begin_" n)
20595 (concat "^[ \t]*#\\+end_" n)
20596 lim-up lim-down)
20597 (throw 'exit n))))
20598 names))
20599 nil)))
20601 (defun org-occur-in-agenda-files (regexp &optional nlines)
20602 "Call `multi-occur' with buffers for all agenda files."
20603 (interactive "sOrg-files matching: \np")
20604 (let* ((files (org-agenda-files))
20605 (tnames (mapcar 'file-truename files))
20606 (extra org-agenda-text-search-extra-files)
20608 (when (eq (car extra) 'agenda-archives)
20609 (setq extra (cdr extra))
20610 (setq files (org-add-archive-files files)))
20611 (while (setq f (pop extra))
20612 (unless (member (file-truename f) tnames)
20613 (add-to-list 'files f 'append)
20614 (add-to-list 'tnames (file-truename f) 'append)))
20615 (multi-occur
20616 (mapcar (lambda (x)
20617 (with-current-buffer
20618 (or (get-file-buffer x) (find-file-noselect x))
20619 (widen)
20620 (current-buffer)))
20621 files)
20622 regexp)))
20624 (if (boundp 'occur-mode-find-occurrence-hook)
20625 ;; Emacs 23
20626 (add-hook 'occur-mode-find-occurrence-hook
20627 (lambda ()
20628 (when (derived-mode-p 'org-mode)
20629 (org-reveal))))
20630 ;; Emacs 22
20631 (defadvice occur-mode-goto-occurrence
20632 (after org-occur-reveal activate)
20633 (and (derived-mode-p 'org-mode) (org-reveal)))
20634 (defadvice occur-mode-goto-occurrence-other-window
20635 (after org-occur-reveal activate)
20636 (and (derived-mode-p 'org-mode) (org-reveal)))
20637 (defadvice occur-mode-display-occurrence
20638 (after org-occur-reveal activate)
20639 (when (derived-mode-p 'org-mode)
20640 (let ((pos (occur-mode-find-occurrence)))
20641 (with-current-buffer (marker-buffer pos)
20642 (save-excursion
20643 (goto-char pos)
20644 (org-reveal)))))))
20646 (defun org-occur-link-in-agenda-files ()
20647 "Create a link and search for it in the agendas.
20648 The link is not stored in `org-stored-links', it is just created
20649 for the search purpose."
20650 (interactive)
20651 (let ((link (condition-case nil
20652 (org-store-link nil)
20653 (error "Unable to create a link to here"))))
20654 (org-occur-in-agenda-files (regexp-quote link))))
20656 (defun org-uniquify (list)
20657 "Remove duplicate elements from LIST."
20658 (let (res)
20659 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20660 res))
20662 (defun org-delete-all (elts list)
20663 "Remove all elements in ELTS from LIST."
20664 (while elts
20665 (setq list (delete (pop elts) list)))
20666 list)
20668 (defun org-count (cl-item cl-seq)
20669 "Count the number of occurrences of ITEM in SEQ.
20670 Taken from `count' in cl-seq.el with all keyword arguments removed."
20671 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20672 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20673 (while (< cl-start cl-end)
20674 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20675 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20676 (setq cl-start (1+ cl-start)))
20677 cl-count))
20679 (defun org-remove-if (predicate seq)
20680 "Remove everything from SEQ that fulfills PREDICATE."
20681 (let (res e)
20682 (while seq
20683 (setq e (pop seq))
20684 (if (not (funcall predicate e)) (push e res)))
20685 (nreverse res)))
20687 (defun org-remove-if-not (predicate seq)
20688 "Remove everything from SEQ that does not fulfill PREDICATE."
20689 (let (res e)
20690 (while seq
20691 (setq e (pop seq))
20692 (if (funcall predicate e) (push e res)))
20693 (nreverse res)))
20695 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20696 "Reduce two-argument FUNCTION across SEQ.
20697 Taken from `reduce' in cl-seq.el with all keyword arguments but
20698 \":initial-value\" removed."
20699 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20700 (cadr (memq :initial-value cl-keys)))
20701 (cl-seq (pop cl-seq))
20702 (t (funcall cl-func)))))
20703 (while cl-seq
20704 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20705 cl-accum))
20707 (defun org-back-over-empty-lines ()
20708 "Move backwards over whitespace, to the beginning of the first empty line.
20709 Returns the number of empty lines passed."
20710 (let ((pos (point)))
20711 (if (cdr (assoc 'heading org-blank-before-new-entry))
20712 (skip-chars-backward " \t\n\r")
20713 (unless (eobp)
20714 (forward-line -1)))
20715 (beginning-of-line 2)
20716 (goto-char (min (point) pos))
20717 (count-lines (point) pos)))
20719 (defun org-skip-whitespace ()
20720 (skip-chars-forward " \t\n\r"))
20722 (defun org-point-in-group (point group &optional context)
20723 "Check if POINT is in match-group GROUP.
20724 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20725 match. If the match group does not exist or point is not inside it,
20726 return nil."
20727 (and (match-beginning group)
20728 (>= point (match-beginning group))
20729 (<= point (match-end group))
20730 (if context
20731 (list context (match-beginning group) (match-end group))
20732 t)))
20734 (defun org-switch-to-buffer-other-window (&rest args)
20735 "Switch to buffer in a second window on the current frame.
20736 In particular, do not allow pop-up frames.
20737 Returns the newly created buffer."
20738 (let (pop-up-frames special-display-buffer-names special-display-regexps
20739 special-display-function)
20740 (apply 'switch-to-buffer-other-window args)))
20742 (defun org-combine-plists (&rest plists)
20743 "Create a single property list from all plists in PLISTS.
20744 The process starts by copying the first list, and then setting properties
20745 from the other lists. Settings in the last list are the most significant
20746 ones and overrule settings in the other lists."
20747 (let ((rtn (copy-sequence (pop plists)))
20748 p v ls)
20749 (while plists
20750 (setq ls (pop plists))
20751 (while ls
20752 (setq p (pop ls) v (pop ls))
20753 (setq rtn (plist-put rtn p v))))
20754 rtn))
20756 (defun org-replace-escapes (string table)
20757 "Replace %-escapes in STRING with values in TABLE.
20758 TABLE is an association list with keys like \"%a\" and string values.
20759 The sequences in STRING may contain normal field width and padding information,
20760 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20761 so values can contain further %-escapes if they are define later in TABLE."
20762 (let ((tbl (copy-alist table))
20763 (case-fold-search nil)
20764 (pchg 0)
20765 e re rpl)
20766 (while (setq e (pop tbl))
20767 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20768 (when (and (cdr e) (string-match re (cdr e)))
20769 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20770 (safe "SREF"))
20771 (add-text-properties 0 3 (list 'sref sref) safe)
20772 (setcdr e (replace-match safe t t (cdr e)))))
20773 (while (string-match re string)
20774 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20775 (cdr e)))
20776 (setq string (replace-match rpl t t string))))
20777 (while (setq pchg (next-property-change pchg string))
20778 (let ((sref (get-text-property pchg 'sref string)))
20779 (when (and sref (string-match "SREF" string pchg))
20780 (setq string (replace-match sref t t string)))))
20781 string))
20783 (defun org-sublist (list start end)
20784 "Return a section of LIST, from START to END.
20785 Counting starts at 1."
20786 (let (rtn (c start))
20787 (setq list (nthcdr (1- start) list))
20788 (while (and list (<= c end))
20789 (push (pop list) rtn)
20790 (setq c (1+ c)))
20791 (nreverse rtn)))
20793 (defun org-find-base-buffer-visiting (file)
20794 "Like `find-buffer-visiting' but always return the base buffer and
20795 not an indirect buffer."
20796 (let ((buf (or (get-file-buffer file)
20797 (find-buffer-visiting file))))
20798 (if buf
20799 (or (buffer-base-buffer buf) buf)
20800 nil)))
20802 (defun org-image-file-name-regexp (&optional extensions)
20803 "Return regexp matching the file names of images.
20804 If EXTENSIONS is given, only match these."
20805 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20806 (image-file-name-regexp)
20807 (let ((image-file-name-extensions
20808 (or extensions
20809 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20810 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20811 (concat "\\."
20812 (regexp-opt (nconc (mapcar 'upcase
20813 image-file-name-extensions)
20814 image-file-name-extensions)
20816 "\\'"))))
20818 (defun org-file-image-p (file &optional extensions)
20819 "Return non-nil if FILE is an image."
20820 (save-match-data
20821 (string-match (org-image-file-name-regexp extensions) file)))
20823 (defun org-get-cursor-date ()
20824 "Return the date at cursor in as a time.
20825 This works in the calendar and in the agenda, anywhere else it just
20826 returns the current time."
20827 (let (date day defd)
20828 (cond
20829 ((eq major-mode 'calendar-mode)
20830 (setq date (calendar-cursor-to-date)
20831 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20832 ((eq major-mode 'org-agenda-mode)
20833 (setq day (get-text-property (point) 'day))
20834 (if day
20835 (setq date (calendar-gregorian-from-absolute day)
20836 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20837 (nth 2 date))))))
20838 (or defd (current-time))))
20840 (defvar org-agenda-action-marker (make-marker)
20841 "Marker pointing to the entry for the next agenda action.")
20843 (defun org-mark-entry-for-agenda-action ()
20844 "Mark the current entry as target of an agenda action.
20845 Agenda actions are actions executed from the agenda with the key `k',
20846 which make use of the date at the cursor."
20847 (interactive)
20848 (move-marker org-agenda-action-marker
20849 (save-excursion (org-back-to-heading t) (point))
20850 (current-buffer))
20851 (message
20852 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20854 (defun org-mark-subtree (&optional up)
20855 "Mark the current subtree.
20856 This puts point at the start of the current subtree, and mark at
20857 the end. If a numeric prefix UP is given, move up into the
20858 hierarchy of headlines by UP levels before marking the subtree."
20859 (interactive "P")
20860 (org-with-limited-levels
20861 (cond ((org-at-heading-p) (beginning-of-line))
20862 ((org-before-first-heading-p) (error "Not in a subtree"))
20863 (t (outline-previous-visible-heading 1))))
20864 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20865 (if (org-called-interactively-p 'any)
20866 (call-interactively 'org-mark-element)
20867 (org-mark-element)))
20870 ;;; Macros
20872 ;; Macros are expanded with `org-macro-replace-all', which relies
20873 ;; internally on `org-macro-expand'.
20875 ;; Templates for expansion are stored in the buffer-local variable
20876 ;; `org-macro-templates'. This variable is updated by
20877 ;; `org-macro-initialize-templates'.
20880 (defvar org-macro-templates nil
20881 "Alist containing all macro templates in current buffer.
20882 Associations are in the shape of (NAME . TEMPLATE) where NAME
20883 stands for macro's name and template for its replacement value,
20884 both as strings. This is an internal variable. Do not set it
20885 directly, use instead:
20887 #+MACRO: name template")
20888 (make-variable-buffer-local 'org-macro-templates)
20890 (defun org-macro-expand (macro)
20891 "Return expanded MACRO, as a string.
20892 MACRO is an object, obtained, for example, with
20893 `org-element-context'. Return nil if no template was found."
20894 (let ((template
20895 (cdr (assoc-string (org-element-property :key macro)
20896 org-macro-templates
20897 ;; Macro names are case-insensitive.
20898 t))))
20899 (when template
20900 (let ((value (replace-regexp-in-string
20901 "\\$[0-9]+"
20902 (lambda (arg)
20903 (or (nth (1- (string-to-number (substring arg 1)))
20904 (org-element-property :args macro))
20905 ;; No argument provided: remove
20906 ;; place-holder.
20907 ""))
20908 template)))
20909 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20910 (when (string-match "\\`(eval\\>" value)
20911 (setq value (eval (read value))))
20912 ;; Return string.
20913 (format "%s" (or value ""))))))
20915 (defun org-macro-replace-all ()
20916 "Replace all macros in current buffer by their expansion."
20917 (save-excursion
20918 (goto-char (point-min))
20919 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20920 (let ((object (org-element-context)))
20921 (when (eq (org-element-type object) 'macro)
20922 (let ((value (org-macro-expand object)))
20923 (when value
20924 (delete-region
20925 (org-element-property :begin object)
20926 ;; Preserve white spaces after the macro.
20927 (progn (goto-char (org-element-property :end object))
20928 (skip-chars-backward " \t")
20929 (point)))
20930 ;; Leave point before replacement in case of recursive
20931 ;; expansions.
20932 (save-excursion (insert value)))))))))
20934 (defun org-macro-initialize-templates ()
20935 "Collect macro templates defined in current buffer.
20936 Templates are stored in buffer-local variable
20937 `org-macro-templates'. In addition to buffer-defined macros, the
20938 function installs the following ones: \"property\", \"date\",
20939 \"time\". and, if appropriate, \"input-file\" and
20940 \"modification-time\"."
20941 (let ((case-fold-search t)
20942 (set-template
20943 (lambda (cell)
20944 ;; Add CELL to `org-macro-templates' if there's no
20945 ;; association matching its name already. Otherwise,
20946 ;; replace old association with the new one in that
20947 ;; variable.
20948 (let ((old-template (assoc (car cell) org-macro-templates)))
20949 (if old-template (setcdr old-template (cdr cell))
20950 (push cell org-macro-templates))))))
20951 ;; Install buffer-local macros.
20952 (org-with-wide-buffer
20953 (goto-char (point-min))
20954 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20955 (let ((element (org-element-at-point)))
20956 (when (eq (org-element-type element) 'keyword)
20957 (let ((value (org-element-property :value element)))
20958 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
20959 (funcall set-template
20960 (cons (match-string 1 value)
20961 (or (match-string 2 value) "")))))))))
20962 ;; Install hard-coded macros.
20963 (mapc (lambda (cell) (funcall set-template cell))
20964 (list
20965 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
20966 (cons "date" "(eval (format-time-string \"$1\"))")
20967 (cons "time" "(eval (format-time-string \"$1\"))")))
20968 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
20969 (when (and visited-file (file-exists-p visited-file))
20970 (mapc (lambda (cell) (funcall set-template cell))
20971 (list
20972 (cons "input-file" (file-name-nondirectory visited-file))
20973 (cons "modification-time"
20974 (format "(eval (format-time-string \"$1\" '%s))"
20975 (prin1-to-string
20976 (nth 5 (file-attributes visited-file)))))))))))
20979 ;;; Indentation
20981 (defun org-indent-line ()
20982 "Indent line depending on context."
20983 (interactive)
20984 (let* ((pos (point))
20985 (itemp (org-at-item-p))
20986 (case-fold-search t)
20987 (org-drawer-regexp (or org-drawer-regexp "\000"))
20988 (inline-task-p (and (featurep 'org-inlinetask)
20989 (org-inlinetask-in-task-p)))
20990 (inline-re (and inline-task-p
20991 (org-inlinetask-outline-regexp)))
20992 column)
20993 (if (and orgstruct-is-++ (eq pos (point)))
20994 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20995 (indent-according-to-mode))
20996 (beginning-of-line 1)
20997 (cond
20998 ;; Headings
20999 ((looking-at org-outline-regexp) (setq column 0))
21000 ;; Included files
21001 ((looking-at "#\\+include:") (setq column 0))
21002 ;; Footnote definition
21003 ((looking-at org-footnote-definition-re) (setq column 0))
21004 ;; Literal examples
21005 ((looking-at "[ \t]*:\\( \\|$\\)")
21006 (setq column (org-get-indentation))) ; do nothing
21007 ;; Lists
21008 ((ignore-errors (goto-char (org-in-item-p)))
21009 (setq column (if itemp
21010 (org-get-indentation)
21011 (org-list-item-body-column (point))))
21012 (goto-char pos))
21013 ;; Drawers
21014 ((and (looking-at "[ \t]*:END:")
21015 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21016 (save-excursion
21017 (goto-char (1- (match-beginning 1)))
21018 (setq column (current-column))))
21019 ;; Special blocks
21020 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21021 (save-excursion
21022 (re-search-backward
21023 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21024 (setq column (org-get-indentation (match-string 0))))
21025 ((and (not (looking-at "[ \t]*#\\+begin_"))
21026 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21027 (save-excursion
21028 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21029 (setq column
21030 (cond ((equal (downcase (match-string 1)) "src")
21031 ;; src blocks: let `org-edit-src-exit' handle them
21032 (org-get-indentation))
21033 ((equal (downcase (match-string 1)) "example")
21034 (max (org-get-indentation)
21035 (org-get-indentation (match-string 0))))
21037 (org-get-indentation (match-string 0))))))
21038 ;; This line has nothing special, look at the previous relevant
21039 ;; line to compute indentation
21041 (beginning-of-line 0)
21042 (while (and (not (bobp))
21043 (not (looking-at org-drawer-regexp))
21044 ;; When point started in an inline task, do not move
21045 ;; above task starting line.
21046 (not (and inline-task-p (looking-at inline-re)))
21047 ;; Skip drawers, blocks, empty lines, verbatim,
21048 ;; comments, tables, footnotes definitions, lists,
21049 ;; inline tasks.
21050 (or (and (looking-at "[ \t]*:END:")
21051 (re-search-backward org-drawer-regexp nil t))
21052 (and (looking-at "[ \t]*#\\+end_")
21053 (re-search-backward "[ \t]*#\\+begin_"nil t))
21054 (looking-at "[ \t]*[\n:#|]")
21055 (looking-at org-footnote-definition-re)
21056 (and (ignore-errors (goto-char (org-in-item-p)))
21057 (goto-char
21058 (org-list-get-top-point (org-list-struct))))
21059 (and (not inline-task-p)
21060 (featurep 'org-inlinetask)
21061 (org-inlinetask-in-task-p)
21062 (or (org-inlinetask-goto-beginning) t))))
21063 (beginning-of-line 0))
21064 (cond
21065 ;; There was an heading above.
21066 ((looking-at "\\*+[ \t]+")
21067 (if (not org-adapt-indentation)
21068 (setq column 0)
21069 (goto-char (match-end 0))
21070 (setq column (current-column))))
21071 ;; A drawer had started and is unfinished
21072 ((looking-at org-drawer-regexp)
21073 (goto-char (1- (match-beginning 1)))
21074 (setq column (current-column)))
21075 ;; Else, nothing noticeable found: get indentation and go on.
21076 (t (setq column (org-get-indentation))))))
21077 ;; Now apply indentation and move cursor accordingly
21078 (goto-char pos)
21079 (if (<= (current-column) (current-indentation))
21080 (org-indent-line-to column)
21081 (save-excursion (org-indent-line-to column)))
21082 ;; Special polishing for properties, see `org-property-format'
21083 (setq column (current-column))
21084 (beginning-of-line 1)
21085 (if (looking-at
21086 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21087 (replace-match (concat (match-string 1)
21088 (format org-property-format
21089 (match-string 2) (match-string 3)))
21090 t t))
21091 (org-move-to-column column))))
21093 (defun org-indent-drawer ()
21094 "Indent the drawer at point."
21095 (interactive)
21096 (let ((p (point))
21097 (e (and (save-excursion (re-search-forward ":END:" nil t))
21098 (match-end 0)))
21099 (folded
21100 (save-excursion
21101 (end-of-line)
21102 (when (overlays-at (point))
21103 (member 'invisible (overlay-properties
21104 (car (overlays-at (point)))))))))
21105 (when folded (org-cycle))
21106 (indent-for-tab-command)
21107 (while (and (move-beginning-of-line 2) (< (point) e))
21108 (indent-for-tab-command))
21109 (goto-char p)
21110 (when folded (org-cycle)))
21111 (message "Drawer at point indented"))
21113 (defun org-indent-block ()
21114 "Indent the block at point."
21115 (interactive)
21116 (let ((p (point))
21117 (case-fold-search t)
21118 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21119 (match-end 0)))
21120 (folded
21121 (save-excursion
21122 (end-of-line)
21123 (when (overlays-at (point))
21124 (member 'invisible (overlay-properties
21125 (car (overlays-at (point)))))))))
21126 (when folded (org-cycle))
21127 (indent-for-tab-command)
21128 (while (and (move-beginning-of-line 2) (< (point) e))
21129 (indent-for-tab-command))
21130 (goto-char p)
21131 (when folded (org-cycle)))
21132 (message "Block at point indented"))
21134 (defun org-indent-region (start end)
21135 "Indent region."
21136 (interactive "r")
21137 (save-excursion
21138 (let ((line-end (org-current-line end)))
21139 (goto-char start)
21140 (while (< (org-current-line) line-end)
21141 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21142 (t (call-interactively 'org-indent-line)))
21143 (move-beginning-of-line 2)))))
21146 ;;; Filling
21148 ;; We use our own fill-paragraph and auto-fill functions.
21150 ;; `org-fill-paragraph' relies on adaptive filling and context
21151 ;; checking. Appropriate `fill-prefix' is computed with
21152 ;; `org-adaptive-fill-function'.
21154 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21155 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21156 ;; `org-adaptive-fill-function' value. Internally,
21157 ;; `org-comment-line-break-function' breaks the line.
21159 ;; `org-setup-filling' installs filling and auto-filling related
21160 ;; variables during `org-mode' initialization.
21162 (defun org-setup-filling ()
21163 (interactive)
21164 ;; Prevent auto-fill from inserting unwanted new items.
21165 (when (boundp 'fill-nobreak-predicate)
21166 (org-set-local
21167 'fill-nobreak-predicate
21168 (org-uniquify
21169 (append fill-nobreak-predicate
21170 '(org-fill-paragraph-separate-nobreak-p
21171 org-fill-line-break-nobreak-p)))))
21172 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21173 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21174 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21175 (org-set-local 'comment-line-break-function 'org-comment-line-break-function)
21176 (org-set-local 'align-mode-rules-list
21177 '((org-in-buffer-settings
21178 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
21179 (modes . '(org-mode))))))
21181 (defvar org-element-paragraph-separate) ; org-element.el
21182 (defun org-fill-paragraph-separate-nobreak-p ()
21183 "Non-nil when a line break at point would insert a new item."
21184 (looking-at (substring org-element-paragraph-separate 1)))
21186 (defun org-fill-line-break-nobreak-p ()
21187 "Non-nil when a line break at point would create an Org line break."
21188 (save-excursion
21189 (skip-chars-backward "[ \t]")
21190 (skip-chars-backward "\\\\")
21191 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21193 (declare-function message-in-body-p "message" ())
21194 (defvar org-element--affiliated-re) ; From org-element.el
21195 (defun org-adaptive-fill-function ()
21196 "Compute a fill prefix for the current line.
21197 Return fill prefix, as a string, or nil if current line isn't
21198 meant to be filled."
21199 (org-with-wide-buffer
21200 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21201 ;; FIXME: This is really the job of orgstruct++-mode
21202 (let* ((p (line-beginning-position))
21203 (element (save-excursion (beginning-of-line)
21204 (org-element-at-point)))
21205 (type (org-element-type element))
21206 (post-affiliated
21207 (save-excursion
21208 (goto-char (org-element-property :begin element))
21209 (while (looking-at org-element--affiliated-re) (forward-line))
21210 (point))))
21211 (unless (< p post-affiliated)
21212 (case type
21213 (comment (looking-at "[ \t]*# ?") (match-string 0))
21214 (footnote-definition "")
21215 ((item plain-list)
21216 (make-string (org-list-item-body-column post-affiliated) ? ))
21217 (paragraph
21218 ;; Fill prefix is usually the same as the current line,
21219 ;; except if the paragraph is at the beginning of an item.
21220 (let ((parent (org-element-property :parent element)))
21221 (cond ((eq (org-element-type parent) 'item)
21222 (make-string (org-list-item-body-column
21223 (org-element-property :begin parent))
21224 ? ))
21225 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21226 (match-string 0))
21227 (t ""))))
21228 (comment-block
21229 ;; Only fill contents if P is within block boundaries.
21230 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21231 (forward-line)
21232 (point)))
21233 (cend (save-excursion
21234 (goto-char (org-element-property :end element))
21235 (skip-chars-backward " \r\t\n")
21236 (line-beginning-position))))
21237 (when (and (>= p cbeg) (< p cend))
21238 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21239 (match-string 0)
21240 ""))))))))))
21242 (declare-function message-goto-body "message" ())
21243 (defvar message-cite-prefix-regexp) ; From message.el
21244 (defvar org-element-all-objects) ; From org-element.el
21245 (defun org-fill-paragraph (&optional justify)
21246 "Fill element at point, when applicable.
21248 This function only applies to comment blocks, comments, example
21249 blocks and paragraphs. Also, as a special case, re-align table
21250 when point is at one.
21252 If JUSTIFY is non-nil (interactively, with prefix argument),
21253 justify as well. If `sentence-end-double-space' is non-nil, then
21254 period followed by one space does not end a sentence, so don't
21255 break a line there. The variable `fill-column' controls the
21256 width for filling.
21258 For convenience, when point is at a plain list, an item or
21259 a footnote definition, try to fill the first paragraph within."
21260 ;; Falls back on message-fill-paragraph when necessary
21261 (interactive)
21262 (if (and (derived-mode-p 'message-mode)
21263 (or (not (message-in-body-p))
21264 (save-excursion (move-beginning-of-line 1)
21265 (looking-at message-cite-prefix-regexp))))
21266 (let ((fill-paragraph-function
21267 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21268 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21269 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21270 (paragraph-separate
21271 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21272 (fill-paragraph nil))
21273 (save-excursion
21274 ;; Move to end of line in order to get the first paragraph
21275 ;; within a plain list or a footnote definition.
21276 (end-of-line)
21277 (let ((element (org-element-at-point)))
21278 ;; First check if point is in a blank line at the beginning of
21279 ;; the buffer. In that case, ignore filling.
21280 (if (< (point) (org-element-property :begin element)) t
21281 (case (org-element-type element)
21282 ;; Align Org tables, leave table.el tables as-is.
21283 (table-row (org-table-align) t)
21284 (table
21285 (when (eq (org-element-property :type element) 'org)
21286 (org-table-align))
21288 (paragraph
21289 ;; Paragraphs may contain `line-break' type objects.
21290 (let ((beg (max (point-min)
21291 (org-element-property :contents-begin element)))
21292 (end (min (point-max)
21293 (org-element-property :contents-end element))))
21294 ;; Do nothing if point is at an affiliated keyword.
21295 (if (< (point) beg) t
21296 (when (derived-mode-p 'message-mode)
21297 ;; In `message-mode', do not fill following
21298 ;; citation in current paragraph nor text before
21299 ;; message body.
21300 (let ((body-start (save-excursion (message-goto-body))))
21301 (when body-start (setq beg (max body-start beg))))
21302 (when (save-excursion
21303 (re-search-forward
21304 (concat "^" message-cite-prefix-regexp) end t))
21305 (setq end (match-beginning 0))))
21306 ;; Fill paragraph, taking line breaks into
21307 ;; consideration. For that, slice the paragraph
21308 ;; using line breaks as separators, and fill the
21309 ;; parts in reverse order to avoid messing with
21310 ;; markers.
21311 (save-excursion
21312 (goto-char end)
21313 (mapc
21314 (lambda (pos)
21315 (fill-region-as-paragraph pos (point) justify)
21316 (goto-char pos))
21317 ;; Find the list of ending positions for line
21318 ;; breaks in the current paragraph. Add paragraph
21319 ;; beginning to include first slice.
21320 (nreverse
21321 (cons
21323 (org-element-map
21324 (org-element--parse-objects
21325 beg end nil org-element-all-objects)
21326 'line-break
21327 (lambda (lb) (org-element-property :end lb)))))))
21328 t)))
21329 ;; Contents of `comment-block' type elements should be
21330 ;; filled as plain text, but only if point is within block
21331 ;; markers.
21332 (comment-block
21333 (let* ((case-fold-search t)
21334 (beg (save-excursion
21335 (goto-char (org-element-property :begin element))
21336 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21337 (forward-line)
21338 (point)))
21339 (end (save-excursion
21340 (goto-char (org-element-property :end element))
21341 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21342 (line-beginning-position))))
21343 (when (and (>= (point) beg) (< (point) end))
21344 (fill-region-as-paragraph
21345 (save-excursion
21346 (end-of-line)
21347 (re-search-backward "^[ \t]*$" beg 'move)
21348 (line-beginning-position))
21349 (save-excursion
21350 (beginning-of-line)
21351 (re-search-forward "^[ \t]*$" end 'move)
21352 (line-beginning-position))
21353 justify)))
21355 ;; Fill comments.
21356 (comment (fill-comment-paragraph justify))
21357 ;; Ignore every other element.
21358 (otherwise t)))))))
21360 (defun org-auto-fill-function ()
21361 "Auto-fill function."
21362 ;; Check if auto-filling is meaningful.
21363 (let ((fc (current-fill-column)))
21364 (when (and fc (> (current-column) fc))
21365 (let ((fill-prefix (org-adaptive-fill-function)))
21366 (when fill-prefix (do-auto-fill))))))
21368 (defun org-comment-line-break-function (&optional soft)
21369 "Break line at point and indent, continuing comment if within one.
21370 The inserted newline is marked hard if variable
21371 `use-hard-newlines' is true, unless optional argument SOFT is
21372 non-nil."
21373 (if soft (insert-and-inherit ?\n) (newline 1))
21374 (save-excursion (forward-char -1) (delete-horizontal-space))
21375 (delete-horizontal-space)
21376 (indent-to-left-margin)
21377 (insert-before-markers-and-inherit fill-prefix))
21380 ;;; Comments
21382 ;; Org comments syntax is quite complex. It requires the entire line
21383 ;; to be just a comment. Also, even with the right syntax at the
21384 ;; beginning of line, some some elements (i.e. verse-block or
21385 ;; example-block) don't accept comments. Usual Emacs comment commands
21386 ;; cannot cope with those requirements. Therefore, Org replaces them.
21388 ;; Org still relies on `comment-dwim', but cannot trust
21389 ;; `comment-only-p'. So, `comment-region-function' and
21390 ;; `uncomment-region-function' both point
21391 ;; to`org-comment-or-uncomment-region'. Eventually,
21392 ;; `org-insert-comment' takes care of insertion of comments at the
21393 ;; beginning of line.
21395 ;; `org-setup-comments-handling' install comments related variables
21396 ;; during `org-mode' initialization.
21398 (defun org-setup-comments-handling ()
21399 (interactive)
21400 (org-set-local 'comment-use-syntax nil)
21401 (org-set-local 'comment-start "# ")
21402 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21403 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21404 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21405 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21407 (defun org-insert-comment ()
21408 "Insert an empty comment above current line.
21409 If the line is empty, insert comment at its beginning."
21410 (beginning-of-line)
21411 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21412 (org-indent-line)
21413 (insert "# "))
21415 (defvar comment-empty-lines) ; From newcomment.el.
21416 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21417 "Comment or uncomment each non-blank line in the region.
21418 Uncomment each non-blank line between BEG and END if it only
21419 contains commented lines. Otherwise, comment them."
21420 (save-restriction
21421 ;; Restrict region
21422 (narrow-to-region (save-excursion (goto-char beg)
21423 (skip-chars-forward " \r\t\n" end)
21424 (line-beginning-position))
21425 (save-excursion (goto-char end)
21426 (skip-chars-backward " \r\t\n" beg)
21427 (line-end-position)))
21428 (let ((uncommentp
21429 ;; UNCOMMENTP is non-nil when every non blank line between
21430 ;; BEG and END is a comment.
21431 (save-excursion
21432 (goto-char (point-min))
21433 (while (and (not (eobp))
21434 (let ((element (org-element-at-point)))
21435 (and (eq (org-element-type element) 'comment)
21436 (goto-char (min (point-max)
21437 (org-element-property
21438 :end element)))))))
21439 (eobp))))
21440 (if uncommentp
21441 ;; Only blank lines and comments in region: uncomment it.
21442 (save-excursion
21443 (goto-char (point-min))
21444 (while (not (eobp))
21445 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21446 (replace-match "" nil nil nil 1))
21447 (forward-line)))
21448 ;; Comment each line in region.
21449 (let ((min-indent (point-max)))
21450 ;; First find the minimum indentation across all lines.
21451 (save-excursion
21452 (goto-char (point-min))
21453 (while (and (not (eobp)) (not (zerop min-indent)))
21454 (unless (looking-at "[ \t]*$")
21455 (setq min-indent (min min-indent (current-indentation))))
21456 (forward-line)))
21457 ;; Then loop over all lines.
21458 (save-excursion
21459 (goto-char (point-min))
21460 (while (not (eobp))
21461 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21462 (org-move-to-column min-indent t)
21463 (insert comment-start))
21464 (forward-line))))))))
21467 ;;; Other stuff.
21469 (defun org-toggle-fixed-width-section (arg)
21470 "Toggle the fixed-width export.
21471 If there is no active region, the QUOTE keyword at the current headline is
21472 inserted or removed. When present, it causes the text between this headline
21473 and the next to be exported as fixed-width text, and unmodified.
21474 If there is an active region, this command adds or removes a colon as the
21475 first character of this line. If the first character of a line is a colon,
21476 this line is also exported in fixed-width font."
21477 (interactive "P")
21478 (let* ((cc 0)
21479 (regionp (org-region-active-p))
21480 (beg (if regionp (region-beginning) (point)))
21481 (end (if regionp (region-end)))
21482 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21483 (case-fold-search nil)
21484 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21485 off)
21486 (if regionp
21487 (save-excursion
21488 (goto-char beg)
21489 (setq cc (current-column))
21490 (beginning-of-line 1)
21491 (setq off (looking-at re))
21492 (while (> nlines 0)
21493 (setq nlines (1- nlines))
21494 (beginning-of-line 1)
21495 (cond
21496 (arg
21497 (org-move-to-column cc t)
21498 (insert ": \n")
21499 (forward-line -1))
21500 ((and off (looking-at re))
21501 (replace-match "" t t nil 1))
21502 ((not off) (org-move-to-column cc t) (insert ": ")))
21503 (forward-line 1)))
21504 (save-excursion
21505 (org-back-to-heading)
21506 (cond
21507 ((looking-at (format org-heading-keyword-regexp-format
21508 org-quote-string))
21509 (goto-char (match-end 1))
21510 (looking-at (concat " +" org-quote-string))
21511 (replace-match "" t t)
21512 (when (eolp) (insert " ")))
21513 ((looking-at org-outline-regexp)
21514 (goto-char (match-end 0))
21515 (insert org-quote-string " ")))))))
21517 (defun org-reftex-citation ()
21518 "Use reftex-citation to insert a citation into the buffer.
21519 This looks for a line like
21521 #+BIBLIOGRAPHY: foo plain option:-d
21523 and derives from it that foo.bib is the bibliography file relevant
21524 for this document. It then installs the necessary environment for RefTeX
21525 to work in this buffer and calls `reftex-citation' to insert a citation
21526 into the buffer.
21528 Export of such citations to both LaTeX and HTML is handled by the contributed
21529 package org-exp-bibtex by Taru Karttunen."
21530 (interactive)
21531 (let ((reftex-docstruct-symbol 'rds)
21532 (reftex-cite-format "\\cite{%l}")
21533 rds bib)
21534 (save-excursion
21535 (save-restriction
21536 (widen)
21537 (let ((case-fold-search t)
21538 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21539 (if (not (save-excursion
21540 (or (re-search-forward re nil t)
21541 (re-search-backward re nil t))))
21542 (error "No bibliography defined in file")
21543 (setq bib (concat (match-string 1) ".bib")
21544 rds (list (list 'bib bib)))))))
21545 (call-interactively 'reftex-citation)))
21547 ;;;; Functions extending outline functionality
21549 (defun org-beginning-of-line (&optional arg)
21550 "Go to the beginning of the current line. If that is invisible, continue
21551 to a visible line beginning. This makes the function of C-a more intuitive.
21552 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21553 first attempt, and only move to after the tags when the cursor is already
21554 beyond the end of the headline."
21555 (interactive "P")
21556 (let ((pos (point))
21557 (special (if (consp org-special-ctrl-a/e)
21558 (car org-special-ctrl-a/e)
21559 org-special-ctrl-a/e))
21560 refpos)
21561 (if (org-bound-and-true-p line-move-visual)
21562 (beginning-of-visual-line 1)
21563 (beginning-of-line 1))
21564 (if (and arg (fboundp 'move-beginning-of-line))
21565 (call-interactively 'move-beginning-of-line)
21566 (if (bobp)
21568 (backward-char 1)
21569 (if (org-truely-invisible-p)
21570 (while (and (not (bobp)) (org-truely-invisible-p))
21571 (backward-char 1)
21572 (beginning-of-line 1))
21573 (forward-char 1))))
21574 (when special
21575 (cond
21576 ((and (looking-at org-complex-heading-regexp)
21577 (= (char-after (match-end 1)) ?\ ))
21578 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21579 (point-at-eol)))
21580 (goto-char
21581 (if (eq special t)
21582 (cond ((> pos refpos) refpos)
21583 ((= pos (point)) refpos)
21584 (t (point)))
21585 (cond ((> pos (point)) (point))
21586 ((not (eq last-command this-command)) (point))
21587 (t refpos)))))
21588 ((org-at-item-p)
21589 ;; Being at an item and not looking at an the item means point
21590 ;; was previously moved to beginning of a visual line, which
21591 ;; doesn't contain the item. Therefore, do nothing special,
21592 ;; just stay here.
21593 (when (looking-at org-list-full-item-re)
21594 ;; Set special position at first white space character after
21595 ;; bullet, and check-box, if any.
21596 (let ((after-bullet
21597 (let ((box (match-end 3)))
21598 (if (not box) (match-end 1)
21599 (let ((after (char-after box)))
21600 (if (and after (= after ? )) (1+ box) box))))))
21601 ;; Special case: Move point to special position when
21602 ;; currently after it or at beginning of line.
21603 (if (eq special t)
21604 (when (or (> pos after-bullet) (= (point) pos))
21605 (goto-char after-bullet))
21606 ;; Reversed case: Move point to special position when
21607 ;; point was already at beginning of line and command is
21608 ;; repeated.
21609 (when (and (= (point) pos) (eq last-command this-command))
21610 (goto-char after-bullet))))))))
21611 (org-no-warnings
21612 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21614 (defun org-end-of-line (&optional arg)
21615 "Go to the end of the line.
21616 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21617 first attempt, and only move to after the tags when the cursor is already
21618 beyond the end of the headline."
21619 (interactive "P")
21620 (let ((special (if (consp org-special-ctrl-a/e)
21621 (cdr org-special-ctrl-a/e)
21622 org-special-ctrl-a/e)))
21623 (cond
21624 ((or (not special) arg
21625 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21626 (call-interactively
21627 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21628 ((fboundp 'move-end-of-line) 'move-end-of-line)
21629 (t 'end-of-line))))
21630 ((org-at-heading-p)
21631 (let ((pos (point)))
21632 (beginning-of-line 1)
21633 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21634 (if (eq special t)
21635 (if (or (< pos (match-beginning 1))
21636 (= pos (match-end 0)))
21637 (goto-char (match-beginning 1))
21638 (goto-char (match-end 0)))
21639 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21640 (goto-char (match-end 0))
21641 (goto-char (match-beginning 1))))
21642 (call-interactively (if (fboundp 'move-end-of-line)
21643 'move-end-of-line
21644 'end-of-line)))))
21645 ((org-at-drawer-p)
21646 (move-end-of-line 1)
21647 (when (overlays-at (1- (point))) (backward-char 1)))
21648 ;; At an item: Move before any hidden text.
21649 (t (call-interactively
21650 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21651 ((fboundp 'move-end-of-line) 'move-end-of-line)
21652 (t 'end-of-line)))))
21653 (org-no-warnings
21654 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21656 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21657 (define-key org-mode-map "\C-e" 'org-end-of-line)
21659 (defun org-backward-sentence (&optional arg)
21660 "Go to beginning of sentence, or beginning of table field.
21661 This will call `backward-sentence' or `org-table-beginning-of-field',
21662 depending on context."
21663 (interactive "P")
21664 (cond
21665 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21666 (t (call-interactively 'backward-sentence))))
21668 (defun org-forward-sentence (&optional arg)
21669 "Go to end of sentence, or end of table field.
21670 This will call `forward-sentence' or `org-table-end-of-field',
21671 depending on context."
21672 (interactive "P")
21673 (cond
21674 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21675 (t (call-interactively 'forward-sentence))))
21677 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21678 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21680 (defun org-kill-line (&optional arg)
21681 "Kill line, to tags or end of line."
21682 (interactive "P")
21683 (cond
21684 ((or (not org-special-ctrl-k)
21685 (bolp)
21686 (not (org-at-heading-p)))
21687 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21688 org-ctrl-k-protect-subtree)
21689 (if (or (eq org-ctrl-k-protect-subtree 'error)
21690 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21691 (error "C-k aborted - would kill hidden subtree")))
21692 (call-interactively
21693 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21694 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21695 (kill-region (point) (match-beginning 1))
21696 (org-set-tags nil t))
21697 (t (kill-region (point) (point-at-eol)))))
21699 (define-key org-mode-map "\C-k" 'org-kill-line)
21701 (defun org-yank (&optional arg)
21702 "Yank. If the kill is a subtree, treat it specially.
21703 This command will look at the current kill and check if is a single
21704 subtree, or a series of subtrees[1]. If it passes the test, and if the
21705 cursor is at the beginning of a line or after the stars of a currently
21706 empty headline, then the yank is handled specially. How exactly depends
21707 on the value of the following variables, both set by default.
21709 org-yank-folded-subtrees
21710 When set, the subtree(s) will be folded after insertion, but only
21711 if doing so would now swallow text after the yanked text.
21713 org-yank-adjusted-subtrees
21714 When set, the subtree will be promoted or demoted in order to
21715 fit into the local outline tree structure, which means that the level
21716 will be adjusted so that it becomes the smaller one of the two
21717 *visible* surrounding headings.
21719 Any prefix to this command will cause `yank' to be called directly with
21720 no special treatment. In particular, a simple \\[universal-argument] prefix \
21721 will just
21722 plainly yank the text as it is.
21724 \[1] The test checks if the first non-white line is a heading
21725 and if there are no other headings with fewer stars."
21726 (interactive "P")
21727 (org-yank-generic 'yank arg))
21729 (defun org-yank-generic (command arg)
21730 "Perform some yank-like command.
21732 This function implements the behavior described in the `org-yank'
21733 documentation. However, it has been generalized to work for any
21734 interactive command with similar behavior."
21736 ;; pretend to be command COMMAND
21737 (setq this-command command)
21739 (if arg
21740 (call-interactively command)
21742 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21743 (and (org-kill-is-subtree-p)
21744 (or (bolp)
21745 (and (looking-at "[ \t]*$")
21746 (string-match
21747 "\\`\\*+\\'"
21748 (buffer-substring (point-at-bol) (point)))))))
21749 swallowp)
21750 (cond
21751 ((and subtreep org-yank-folded-subtrees)
21752 (let ((beg (point))
21753 end)
21754 (if (and subtreep org-yank-adjusted-subtrees)
21755 (org-paste-subtree nil nil 'for-yank)
21756 (call-interactively command))
21758 (setq end (point))
21759 (goto-char beg)
21760 (when (and (bolp) subtreep
21761 (not (setq swallowp
21762 (org-yank-folding-would-swallow-text beg end))))
21763 (org-with-limited-levels
21764 (or (looking-at org-outline-regexp)
21765 (re-search-forward org-outline-regexp-bol end t))
21766 (while (and (< (point) end) (looking-at org-outline-regexp))
21767 (hide-subtree)
21768 (org-cycle-show-empty-lines 'folded)
21769 (condition-case nil
21770 (outline-forward-same-level 1)
21771 (error (goto-char end))))))
21772 (when swallowp
21773 (message
21774 "Inserted text not folded because that would swallow text"))
21776 (goto-char end)
21777 (skip-chars-forward " \t\n\r")
21778 (beginning-of-line 1)
21779 (push-mark beg 'nomsg)))
21780 ((and subtreep org-yank-adjusted-subtrees)
21781 (let ((beg (point-at-bol)))
21782 (org-paste-subtree nil nil 'for-yank)
21783 (push-mark beg 'nomsg)))
21785 (call-interactively command))))))
21787 (defun org-yank-folding-would-swallow-text (beg end)
21788 "Would hide-subtree at BEG swallow any text after END?"
21789 (let (level)
21790 (org-with-limited-levels
21791 (save-excursion
21792 (goto-char beg)
21793 (when (or (looking-at org-outline-regexp)
21794 (re-search-forward org-outline-regexp-bol end t))
21795 (setq level (org-outline-level)))
21796 (goto-char end)
21797 (skip-chars-forward " \t\r\n\v\f")
21798 (if (or (eobp)
21799 (and (bolp) (looking-at org-outline-regexp)
21800 (<= (org-outline-level) level)))
21801 nil ; Nothing would be swallowed
21802 t))))) ; something would swallow
21804 (define-key org-mode-map "\C-y" 'org-yank)
21806 (defun org-truely-invisible-p ()
21807 "Check if point is at a character currently not visible.
21808 This version does not only check the character property, but also
21809 `visible-mode'."
21810 ;; Early versions of noutline don't have `outline-invisible-p'.
21811 (if (org-bound-and-true-p visible-mode)
21813 (outline-invisible-p)))
21815 (defun org-invisible-p2 ()
21816 "Check if point is at a character currently not visible."
21817 (save-excursion
21818 (if (and (eolp) (not (bobp))) (backward-char 1))
21819 ;; Early versions of noutline don't have `outline-invisible-p'.
21820 (outline-invisible-p)))
21822 (defun org-back-to-heading (&optional invisible-ok)
21823 "Call `outline-back-to-heading', but provide a better error message."
21824 (condition-case nil
21825 (outline-back-to-heading invisible-ok)
21826 (error (error "Before first headline at position %d in buffer %s"
21827 (point) (current-buffer)))))
21829 (defun org-before-first-heading-p ()
21830 "Before first heading?"
21831 (save-excursion
21832 (end-of-line)
21833 (null (re-search-backward org-outline-regexp-bol nil t))))
21835 (defun org-at-heading-p (&optional ignored)
21836 (outline-on-heading-p t))
21837 ;; Compatibility alias with Org versions < 7.8.03
21838 (defalias 'org-on-heading-p 'org-at-heading-p)
21840 (defun org-at-comment-p nil
21841 "Is cursor in a line starting with a # character?"
21842 (save-excursion
21843 (beginning-of-line)
21844 (looking-at "^#")))
21846 (defun org-at-drawer-p nil
21847 "Is cursor at a drawer keyword?"
21848 (save-excursion
21849 (move-beginning-of-line 1)
21850 (looking-at org-drawer-regexp)))
21852 (defun org-at-block-p nil
21853 "Is cursor at a block keyword?"
21854 (save-excursion
21855 (move-beginning-of-line 1)
21856 (looking-at org-block-regexp)))
21858 (defun org-point-at-end-of-empty-headline ()
21859 "If point is at the end of an empty headline, return t, else nil.
21860 If the heading only contains a TODO keyword, it is still still considered
21861 empty."
21862 (and (looking-at "[ \t]*$")
21863 (when org-todo-line-regexp
21864 (save-excursion
21865 (beginning-of-line 1)
21866 (let ((case-fold-search nil))
21867 (looking-at org-todo-line-regexp)
21868 (string= (match-string 3) ""))))))
21870 (defun org-at-heading-or-item-p ()
21871 (or (org-at-heading-p) (org-at-item-p)))
21873 (defun org-at-target-p ()
21874 (or (org-in-regexp org-radio-target-regexp)
21875 (org-in-regexp org-target-regexp)))
21876 ;; Compatibility alias with Org versions < 7.8.03
21877 (defalias 'org-on-target-p 'org-at-target-p)
21879 (defun org-up-heading-all (arg)
21880 "Move to the heading line of which the present line is a subheading.
21881 This function considers both visible and invisible heading lines.
21882 With argument, move up ARG levels."
21883 (if (fboundp 'outline-up-heading-all)
21884 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21885 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21887 (defun org-up-heading-safe ()
21888 "Move to the heading line of which the present line is a subheading.
21889 This version will not throw an error. It will return the level of the
21890 headline found, or nil if no higher level is found.
21892 Also, this function will be a lot faster than `outline-up-heading',
21893 because it relies on stars being the outline starters. This can really
21894 make a significant difference in outlines with very many siblings."
21895 (let (start-level re)
21896 (org-back-to-heading t)
21897 (setq start-level (funcall outline-level))
21898 (if (equal start-level 1)
21900 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21901 (if (re-search-backward re nil t)
21902 (funcall outline-level)))))
21904 (defun org-first-sibling-p ()
21905 "Is this heading the first child of its parents?"
21906 (interactive)
21907 (let ((re org-outline-regexp-bol)
21908 level l)
21909 (unless (org-at-heading-p t)
21910 (error "Not at a heading"))
21911 (setq level (funcall outline-level))
21912 (save-excursion
21913 (if (not (re-search-backward re nil t))
21915 (setq l (funcall outline-level))
21916 (< l level)))))
21918 (defun org-goto-sibling (&optional previous)
21919 "Goto the next sibling, even if it is invisible.
21920 When PREVIOUS is set, go to the previous sibling instead. Returns t
21921 when a sibling was found. When none is found, return nil and don't
21922 move point."
21923 (let ((fun (if previous 're-search-backward 're-search-forward))
21924 (pos (point))
21925 (re org-outline-regexp-bol)
21926 level l)
21927 (when (condition-case nil (org-back-to-heading t) (error nil))
21928 (setq level (funcall outline-level))
21929 (catch 'exit
21930 (or previous (forward-char 1))
21931 (while (funcall fun re nil t)
21932 (setq l (funcall outline-level))
21933 (when (< l level) (goto-char pos) (throw 'exit nil))
21934 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21935 (goto-char pos)
21936 nil))))
21938 (defun org-show-siblings ()
21939 "Show all siblings of the current headline."
21940 (save-excursion
21941 (while (org-goto-sibling) (org-flag-heading nil)))
21942 (save-excursion
21943 (while (org-goto-sibling 'previous)
21944 (org-flag-heading nil))))
21946 (defun org-goto-first-child ()
21947 "Goto the first child, even if it is invisible.
21948 Return t when a child was found. Otherwise don't move point and
21949 return nil."
21950 (let (level (pos (point)) (re org-outline-regexp-bol))
21951 (when (condition-case nil (org-back-to-heading t) (error nil))
21952 (setq level (outline-level))
21953 (forward-char 1)
21954 (if (and (re-search-forward re nil t) (> (outline-level) level))
21955 (progn (goto-char (match-beginning 0)) t)
21956 (goto-char pos) nil))))
21958 (defun org-show-hidden-entry ()
21959 "Show an entry where even the heading is hidden."
21960 (save-excursion
21961 (org-show-entry)))
21963 (defun org-flag-heading (flag &optional entry)
21964 "Flag the current heading. FLAG non-nil means make invisible.
21965 When ENTRY is non-nil, show the entire entry."
21966 (save-excursion
21967 (org-back-to-heading t)
21968 ;; Check if we should show the entire entry
21969 (if entry
21970 (progn
21971 (org-show-entry)
21972 (save-excursion
21973 (and (outline-next-heading)
21974 (org-flag-heading nil))))
21975 (outline-flag-region (max (point-min) (1- (point)))
21976 (save-excursion (outline-end-of-heading) (point))
21977 flag))))
21979 (defun org-get-next-sibling ()
21980 "Move to next heading of the same level, and return point.
21981 If there is no such heading, return nil.
21982 This is like outline-next-sibling, but invisible headings are ok."
21983 (let ((level (funcall outline-level)))
21984 (outline-next-heading)
21985 (while (and (not (eobp)) (> (funcall outline-level) level))
21986 (outline-next-heading))
21987 (if (or (eobp) (< (funcall outline-level) level))
21989 (point))))
21991 (defun org-get-last-sibling ()
21992 "Move to previous heading of the same level, and return point.
21993 If there is no such heading, return nil."
21994 (let ((opoint (point))
21995 (level (funcall outline-level)))
21996 (outline-previous-heading)
21997 (when (and (/= (point) opoint) (outline-on-heading-p t))
21998 (while (and (> (funcall outline-level) level)
21999 (not (bobp)))
22000 (outline-previous-heading))
22001 (if (< (funcall outline-level) level)
22003 (point)))))
22005 (defun org-end-of-subtree (&optional invisible-OK to-heading)
22006 ;; This contains an exact copy of the original function, but it uses
22007 ;; `org-back-to-heading', to make it work also in invisible
22008 ;; trees. And is uses an invisible-OK argument.
22009 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22010 ;; Furthermore, when used inside Org, finding the end of a large subtree
22011 ;; with many children and grandchildren etc, this can be much faster
22012 ;; than the outline version.
22013 (org-back-to-heading invisible-OK)
22014 (let ((first t)
22015 (level (funcall outline-level)))
22016 (if (and (derived-mode-p 'org-mode) (< level 1000))
22017 ;; A true heading (not a plain list item), in Org-mode
22018 ;; This means we can easily find the end by looking
22019 ;; only for the right number of stars. Using a regexp to do
22020 ;; this is so much faster than using a Lisp loop.
22021 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22022 (forward-char 1)
22023 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22024 ;; something else, do it the slow way
22025 (while (and (not (eobp))
22026 (or first (> (funcall outline-level) level)))
22027 (setq first nil)
22028 (outline-next-heading)))
22029 (unless to-heading
22030 (if (memq (preceding-char) '(?\n ?\^M))
22031 (progn
22032 ;; Go to end of line before heading
22033 (forward-char -1)
22034 (if (memq (preceding-char) '(?\n ?\^M))
22035 ;; leave blank line before heading
22036 (forward-char -1))))))
22037 (point))
22039 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22040 "Use Org version in org-mode, for dramatic speed-up."
22041 (if (derived-mode-p 'org-mode)
22042 (progn
22043 (org-end-of-subtree nil t)
22044 (unless (eobp) (backward-char 1)))
22045 ad-do-it))
22047 (defun org-end-of-meta-data-and-drawers ()
22048 "Jump to the first text after meta data and drawers in the current entry.
22049 This will move over empty lines, lines with planning time stamps,
22050 clocking lines, and drawers."
22051 (org-back-to-heading t)
22052 (let ((end (save-excursion (outline-next-heading) (point)))
22053 (re (concat "\\(" org-drawer-regexp "\\)"
22054 "\\|" "[ \t]*" org-keyword-time-regexp)))
22055 (forward-line 1)
22056 (while (re-search-forward re end t)
22057 (if (not (match-end 1))
22058 ;; empty or planning line
22059 (forward-line 1)
22060 ;; a drawer, find the end
22061 (re-search-forward "^[ \t]*:END:" end 'move)
22062 (forward-line 1)))
22063 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22064 (point)))
22066 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22067 "Move forward to the arg'th subheading at same level as this one.
22068 Stop at the first and last subheadings of a superior heading.
22069 Normally this only looks at visible headings, but when INVISIBLE-OK is
22070 non-nil it will also look at invisible ones."
22071 (interactive "p")
22072 (org-back-to-heading invisible-ok)
22073 (org-at-heading-p)
22074 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22075 (re (format "^\\*\\{1,%d\\} " level))
22077 (forward-char 1)
22078 (while (> arg 0)
22079 (while (and (re-search-forward re nil 'move)
22080 (setq l (- (match-end 0) (match-beginning 0) 1))
22081 (= l level)
22082 (not invisible-ok)
22083 (progn (backward-char 1) (outline-invisible-p)))
22084 (if (< l level) (setq arg 1)))
22085 (setq arg (1- arg)))
22086 (beginning-of-line 1)))
22088 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22089 "Move backward to the arg'th subheading at same level as this one.
22090 Stop at the first and last subheadings of a superior heading."
22091 (interactive "p")
22092 (org-back-to-heading)
22093 (org-at-heading-p)
22094 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22095 (re (format "^\\*\\{1,%d\\} " level))
22097 (while (> arg 0)
22098 (while (and (re-search-backward re nil 'move)
22099 (setq l (- (match-end 0) (match-beginning 0) 1))
22100 (= l level)
22101 (not invisible-ok)
22102 (outline-invisible-p))
22103 (if (< l level) (setq arg 1)))
22104 (setq arg (1- arg)))))
22106 ;;;###autoload
22107 (defun org-forward-element ()
22108 "Move forward by one element.
22109 Move to the next element at the same level, when possible."
22110 (interactive)
22111 (cond ((eobp) (error "Cannot move further down"))
22112 ((org-with-limited-levels (org-at-heading-p))
22113 (let ((origin (point)))
22114 (org-forward-heading-same-level 1)
22115 (unless (org-with-limited-levels (org-at-heading-p))
22116 (goto-char origin)
22117 (error "Cannot move further down"))))
22119 (let* ((elem (org-element-at-point))
22120 (end (org-element-property :end elem))
22121 (parent (org-element-property :parent elem)))
22122 (if (and parent (= (org-element-property :contents-end parent) end))
22123 (goto-char (org-element-property :end parent))
22124 (goto-char end))))))
22126 ;;;###autoload
22127 (defun org-backward-element ()
22128 "Move backward by one element.
22129 Move to the previous element at the same level, when possible."
22130 (interactive)
22131 (cond ((bobp) (error "Cannot move further up"))
22132 ((org-with-limited-levels (org-at-heading-p))
22133 ;; At an headline, move to the previous one, if any, or stay
22134 ;; here.
22135 (let ((origin (point)))
22136 (org-backward-heading-same-level 1)
22137 (unless (org-with-limited-levels (org-at-heading-p))
22138 (goto-char origin)
22139 (error "Cannot move further up"))))
22141 (let* ((trail (org-element-at-point 'keep-trail))
22142 (elem (car trail))
22143 (prev-elem (nth 1 trail))
22144 (beg (org-element-property :begin elem)))
22145 (cond
22146 ;; Move to beginning of current element if point isn't
22147 ;; there already.
22148 ((/= (point) beg) (goto-char beg))
22149 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22150 ((org-before-first-heading-p) (goto-char (point-min)))
22151 (t (org-back-to-heading)))))))
22153 ;;;###autoload
22154 (defun org-up-element ()
22155 "Move to upper element."
22156 (interactive)
22157 (if (org-with-limited-levels (org-at-heading-p))
22158 (unless (org-up-heading-safe) (error "No surrounding element"))
22159 (let* ((elem (org-element-at-point))
22160 (parent (org-element-property :parent elem)))
22161 (if parent (goto-char (org-element-property :begin parent))
22162 (if (org-with-limited-levels (org-before-first-heading-p))
22163 (error "No surrounding element")
22164 (org-with-limited-levels (org-back-to-heading)))))))
22166 ;;;###autoload
22167 (defvar org-element-greater-elements)
22168 (defun org-down-element ()
22169 "Move to inner element."
22170 (interactive)
22171 (let ((element (org-element-at-point)))
22172 (cond
22173 ((memq (org-element-type element) '(plain-list table))
22174 (goto-char (org-element-property :contents-begin element))
22175 (forward-char))
22176 ((memq (org-element-type element) org-element-greater-elements)
22177 ;; If contents are hidden, first disclose them.
22178 (when (org-element-property :hiddenp element) (org-cycle))
22179 (goto-char (or (org-element-property :contents-begin element)
22180 (error "No content for this element"))))
22181 (t (error "No inner element")))))
22183 ;;;###autoload
22184 (defun org-drag-element-backward ()
22185 "Move backward element at point."
22186 (interactive)
22187 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22188 (let* ((trail (org-element-at-point 'keep-trail))
22189 (elem (car trail))
22190 (prev-elem (nth 1 trail)))
22191 ;; Error out if no previous element or previous element is
22192 ;; a parent of the current one.
22193 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22194 (error "Cannot drag element backward")
22195 (let ((pos (point)))
22196 (org-element-swap-A-B prev-elem elem)
22197 (goto-char (+ (org-element-property :begin prev-elem)
22198 (- pos (org-element-property :begin elem)))))))))
22200 ;;;###autoload
22201 (defun org-drag-element-forward ()
22202 "Move forward element at point."
22203 (interactive)
22204 (let* ((pos (point))
22205 (elem (org-element-at-point)))
22206 (when (= (point-max) (org-element-property :end elem))
22207 (error "Cannot drag element forward"))
22208 (goto-char (org-element-property :end elem))
22209 (let ((next-elem (org-element-at-point)))
22210 (when (or (org-element-nested-p elem next-elem)
22211 (and (eq (org-element-type next-elem) 'headline)
22212 (not (eq (org-element-type elem) 'headline))))
22213 (goto-char pos)
22214 (error "Cannot drag element forward"))
22215 ;; Compute new position of point: it's shifted by NEXT-ELEM
22216 ;; body's length (without final blanks) and by the length of
22217 ;; blanks between ELEM and NEXT-ELEM.
22218 (let ((size-next (- (save-excursion
22219 (goto-char (org-element-property :end next-elem))
22220 (skip-chars-backward " \r\t\n")
22221 (forward-line)
22222 ;; Small correction if buffer doesn't end
22223 ;; with a newline character.
22224 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22225 (org-element-property :begin next-elem)))
22226 (size-blank (- (org-element-property :end elem)
22227 (save-excursion
22228 (goto-char (org-element-property :end elem))
22229 (skip-chars-backward " \r\t\n")
22230 (forward-line)
22231 (point)))))
22232 (org-element-swap-A-B elem next-elem)
22233 (goto-char (+ pos size-next size-blank))))))
22235 ;;;###autoload
22236 (defun org-mark-element ()
22237 "Put point at beginning of this element, mark at end.
22239 Interactively, if this command is repeated or (in Transient Mark
22240 mode) if the mark is active, it marks the next element after the
22241 ones already marked."
22242 (interactive)
22243 (let (deactivate-mark)
22244 (if (and (org-called-interactively-p 'any)
22245 (or (and (eq last-command this-command) (mark t))
22246 (and transient-mark-mode mark-active)))
22247 (set-mark
22248 (save-excursion
22249 (goto-char (mark))
22250 (goto-char (org-element-property :end (org-element-at-point)))))
22251 (let ((element (org-element-at-point)))
22252 (end-of-line)
22253 (push-mark (org-element-property :end element) t t)
22254 (goto-char (org-element-property :begin element))))))
22256 ;;;###autoload
22257 (defun org-narrow-to-element ()
22258 "Narrow buffer to current element."
22259 (interactive)
22260 (let ((elem (org-element-at-point)))
22261 (cond
22262 ((eq (car elem) 'headline)
22263 (narrow-to-region
22264 (org-element-property :begin elem)
22265 (org-element-property :end elem)))
22266 ((memq (car elem) org-element-greater-elements)
22267 (narrow-to-region
22268 (org-element-property :contents-begin elem)
22269 (org-element-property :contents-end elem)))
22271 (narrow-to-region
22272 (org-element-property :begin elem)
22273 (org-element-property :end elem))))))
22275 ;;;###autoload
22276 (defun org-transpose-element ()
22277 "Transpose current and previous elements, keeping blank lines between.
22278 Point is moved after both elements."
22279 (interactive)
22280 (org-skip-whitespace)
22281 (let ((end (org-element-property :end (org-element-at-point))))
22282 (org-drag-element-backward)
22283 (goto-char end)))
22285 ;;;###autoload
22286 (defun org-unindent-buffer ()
22287 "Un-indent the visible part of the buffer.
22288 Relative indentation (between items, inside blocks, etc.) isn't
22289 modified."
22290 (interactive)
22291 (unless (eq major-mode 'org-mode)
22292 (error "Cannot un-indent a buffer not in Org mode"))
22293 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22294 unindent-tree ; For byte-compiler.
22295 (unindent-tree
22296 (function
22297 (lambda (contents)
22298 (mapc
22299 (lambda (element)
22300 (if (memq (org-element-type element) '(headline section))
22301 (funcall unindent-tree (org-element-contents element))
22302 (save-excursion
22303 (save-restriction
22304 (narrow-to-region
22305 (org-element-property :begin element)
22306 (org-element-property :end element))
22307 (org-do-remove-indentation)))))
22308 (reverse contents))))))
22309 (funcall unindent-tree (org-element-contents parse-tree))))
22311 (defun org-show-subtree ()
22312 "Show everything after this heading at deeper levels."
22313 (interactive)
22314 (outline-flag-region
22315 (point)
22316 (save-excursion
22317 (org-end-of-subtree t t))
22318 nil))
22320 (defun org-show-entry ()
22321 "Show the body directly following this heading.
22322 Show the heading too, if it is currently invisible."
22323 (interactive)
22324 (save-excursion
22325 (condition-case nil
22326 (progn
22327 (org-back-to-heading t)
22328 (outline-flag-region
22329 (max (point-min) (1- (point)))
22330 (save-excursion
22331 (if (re-search-forward
22332 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22333 (match-beginning 1)
22334 (point-max)))
22335 nil)
22336 (org-cycle-hide-drawers 'children))
22337 (error nil))))
22339 (defun org-make-options-regexp (kwds &optional extra)
22340 "Make a regular expression for keyword lines."
22341 (concat
22342 "^#\\+\\("
22343 (mapconcat 'regexp-quote kwds "\\|")
22344 (if extra (concat "\\|" extra))
22345 "\\):[ \t]*\\(.*\\)"))
22347 ;; Make isearch reveal the necessary context
22348 (defun org-isearch-end ()
22349 "Reveal context after isearch exits."
22350 (when isearch-success ; only if search was successful
22351 (if (featurep 'xemacs)
22352 ;; Under XEmacs, the hook is run in the correct place,
22353 ;; we directly show the context.
22354 (org-show-context 'isearch)
22355 ;; In Emacs the hook runs *before* restoring the overlays.
22356 ;; So we have to use a one-time post-command-hook to do this.
22357 ;; (Emacs 22 has a special variable, see function `org-mode')
22358 (unless (and (boundp 'isearch-mode-end-hook-quit)
22359 isearch-mode-end-hook-quit)
22360 ;; Only when the isearch was not quitted.
22361 (org-add-hook 'post-command-hook 'org-isearch-post-command
22362 'append 'local)))))
22364 (defun org-isearch-post-command ()
22365 "Remove self from hook, and show context."
22366 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22367 (org-show-context 'isearch))
22370 ;;;; Integration with and fixes for other packages
22372 ;;; Imenu support
22374 (defvar org-imenu-markers nil
22375 "All markers currently used by Imenu.")
22376 (make-variable-buffer-local 'org-imenu-markers)
22378 (defun org-imenu-new-marker (&optional pos)
22379 "Return a new marker for use by Imenu, and remember the marker."
22380 (let ((m (make-marker)))
22381 (move-marker m (or pos (point)))
22382 (push m org-imenu-markers)
22385 (defun org-imenu-get-tree ()
22386 "Produce the index for Imenu."
22387 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22388 (setq org-imenu-markers nil)
22389 (let* ((n org-imenu-depth)
22390 (re (concat "^" (org-get-limited-outline-regexp)))
22391 (subs (make-vector (1+ n) nil))
22392 (last-level 0)
22393 m level head)
22394 (save-excursion
22395 (save-restriction
22396 (widen)
22397 (goto-char (point-max))
22398 (while (re-search-backward re nil t)
22399 (setq level (org-reduced-level (funcall outline-level)))
22400 (when (and (<= level n)
22401 (looking-at org-complex-heading-regexp))
22402 (setq head (org-link-display-format
22403 (org-match-string-no-properties 4))
22404 m (org-imenu-new-marker))
22405 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22406 (if (>= level last-level)
22407 (push (cons head m) (aref subs level))
22408 (push (cons head (aref subs (1+ level))) (aref subs level))
22409 (loop for i from (1+ level) to n do (aset subs i nil)))
22410 (setq last-level level)))))
22411 (aref subs 1)))
22413 (eval-after-load "imenu"
22414 '(progn
22415 (add-hook 'imenu-after-jump-hook
22416 (lambda ()
22417 (if (derived-mode-p 'org-mode)
22418 (org-show-context 'org-goto))))))
22420 (defun org-link-display-format (link)
22421 "Replace a link with either the description, or the link target
22422 if no description is present"
22423 (save-match-data
22424 (if (string-match org-bracket-link-analytic-regexp link)
22425 (replace-match (if (match-end 5)
22426 (match-string 5 link)
22427 (concat (match-string 1 link)
22428 (match-string 3 link)))
22429 nil t link)
22430 link)))
22432 (defun org-toggle-link-display ()
22433 "Toggle the literal or descriptive display of links."
22434 (interactive)
22435 (if org-descriptive-links
22436 (progn (org-remove-from-invisibility-spec '(org-link))
22437 (org-restart-font-lock)
22438 (setq org-descriptive-links nil))
22439 (progn (add-to-invisibility-spec '(org-link))
22440 (org-restart-font-lock)
22441 (setq org-descriptive-links t))))
22443 ;; Speedbar support
22445 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22446 "Overlay marking the agenda restriction line in speedbar.")
22447 (overlay-put org-speedbar-restriction-lock-overlay
22448 'face 'org-agenda-restriction-lock)
22449 (overlay-put org-speedbar-restriction-lock-overlay
22450 'help-echo "Agendas are currently limited to this item.")
22451 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22453 (defun org-speedbar-set-agenda-restriction ()
22454 "Restrict future agenda commands to the location at point in speedbar.
22455 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22456 (interactive)
22457 (require 'org-agenda)
22458 (let (p m tp np dir txt)
22459 (cond
22460 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22461 'org-imenu t))
22462 (setq m (get-text-property p 'org-imenu-marker))
22463 (with-current-buffer (marker-buffer m)
22464 (goto-char m)
22465 (org-agenda-set-restriction-lock 'subtree)))
22466 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22467 'speedbar-function 'speedbar-find-file))
22468 (setq tp (previous-single-property-change
22469 (1+ p) 'speedbar-function)
22470 np (next-single-property-change
22471 tp 'speedbar-function)
22472 dir (speedbar-line-directory)
22473 txt (buffer-substring-no-properties (or tp (point-min))
22474 (or np (point-max))))
22475 (with-current-buffer (find-file-noselect
22476 (let ((default-directory dir))
22477 (expand-file-name txt)))
22478 (unless (derived-mode-p 'org-mode)
22479 (error "Cannot restrict to non-Org-mode file"))
22480 (org-agenda-set-restriction-lock 'file)))
22481 (t (error "Don't know how to restrict Org-mode's agenda")))
22482 (move-overlay org-speedbar-restriction-lock-overlay
22483 (point-at-bol) (point-at-eol))
22484 (setq current-prefix-arg nil)
22485 (org-agenda-maybe-redo)))
22487 (eval-after-load "speedbar"
22488 '(progn
22489 (speedbar-add-supported-extension ".org")
22490 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22491 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22492 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22493 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22494 (add-hook 'speedbar-visiting-tag-hook
22495 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22497 ;;; Fixes and Hacks for problems with other packages
22499 ;; Make flyspell not check words in links, to not mess up our keymap
22500 (defun org-mode-flyspell-verify ()
22501 "Don't let flyspell put overlays at active buttons, or on
22502 {todo,all-time,additional-option-like}-keywords."
22503 (let ((pos (max (1- (point)) (point-min)))
22504 (word (thing-at-point 'word)))
22505 (and (not (get-text-property pos 'keymap))
22506 (not (get-text-property pos 'org-no-flyspell))
22507 (not (member word org-todo-keywords-1))
22508 (not (member word org-all-time-keywords))
22509 (not (member word org-options-keywords))
22510 (not (member word (mapcar 'car org-startup-options)))
22511 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22513 (defun org-remove-flyspell-overlays-in (beg end)
22514 "Remove flyspell overlays in region."
22515 (and (org-bound-and-true-p flyspell-mode)
22516 (fboundp 'flyspell-delete-region-overlays)
22517 (flyspell-delete-region-overlays beg end))
22518 (add-text-properties beg end '(org-no-flyspell t)))
22520 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22521 (eval-after-load "bookmark"
22522 '(if (boundp 'bookmark-after-jump-hook)
22523 ;; We can use the hook
22524 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22525 ;; Hook not available, use advice
22526 (defadvice bookmark-jump (after org-make-visible activate)
22527 "Make the position visible."
22528 (org-bookmark-jump-unhide))))
22530 ;; Make sure saveplace shows the location if it was hidden
22531 (eval-after-load "saveplace"
22532 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22533 "Make the position visible."
22534 (org-bookmark-jump-unhide)))
22536 ;; Make sure ecb shows the location if it was hidden
22537 (eval-after-load "ecb"
22538 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22539 "Make hierarchy visible when jumping into location from ECB tree buffer."
22540 (if (derived-mode-p 'org-mode)
22541 (org-show-context))))
22543 (defun org-bookmark-jump-unhide ()
22544 "Unhide the current position, to show the bookmark location."
22545 (and (derived-mode-p 'org-mode)
22546 (or (outline-invisible-p)
22547 (save-excursion (goto-char (max (point-min) (1- (point))))
22548 (outline-invisible-p)))
22549 (org-show-context 'bookmark-jump)))
22551 ;; Make session.el ignore our circular variable
22552 (eval-after-load "session"
22553 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22555 ;;;; Experimental code
22557 (defun org-closed-in-range ()
22558 "Sparse tree of items closed in a certain time range.
22559 Still experimental, may disappear in the future."
22560 (interactive)
22561 ;; Get the time interval from the user.
22562 (let* ((time1 (org-float-time
22563 (org-read-date nil 'to-time nil "Starting date: ")))
22564 (time2 (org-float-time
22565 (org-read-date nil 'to-time nil "End date:")))
22566 ;; callback function
22567 (callback (lambda ()
22568 (let ((time
22569 (org-float-time
22570 (apply 'encode-time
22571 (org-parse-time-string
22572 (match-string 1))))))
22573 ;; check if time in interval
22574 (and (>= time time1) (<= time time2))))))
22575 ;; make tree, check each match with the callback
22576 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22578 ;;;; Finish up
22580 (provide 'org)
22582 (run-hooks 'org-load-hook)
22584 ;;; org.el ends here